Trying to get property of non-object laravel when accessing database - php

I am trying to code the edit route for laravel and for some reason keep getting the error "Trying to get property of non-object laravel". The Create controller works fine, however when I use the controller#update route I keep getting this error
My Controller for adding an event: (update)
public function update(Request $request, $id)
{
//create event
$my_user = my::find($id);
$my_user->programme = $request->input('programme');
$my_user->goal1 = $request->input('goal1');
$my_user->goal2 = $request->input('goal2');
$my_user->goal3 = $request->input('goal3');
$my_user->goal4 = $request->input('goal4');
$my_user->goal5 = $request->input('goal5');
$my_user->user_id = auth()->user()->id;
$my_user->save();
return redirect('/home')->with('success','Event Created');
}
edit page
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Post</h1>
{!! Form::open(['action' => ['myUserController#update', $my_user], 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('title', 'Event Name')}}
{{Form::text('goal1', $my_user->goal1, ['class' => 'form-control', 'placeholder' => 'Goal One'])}}
</div>
{{Form::hidden('_method','PUT')}}
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection

Given that you are using a Route::resource you can type-hint your parameters by writing something like
public function update(Request $request, MyUser $myuser){
// The $myuser parameter comes from the Route::resource and can be verified using php artisan route:list in your terminal
// edit $my_user
$my_user->save();
return redirect('/home')->with('success','Event Created');
}
Update after reviewing LaravelCollective documentation for Form
Thank you Sohel0415 for mentioning that you do not need to call $my_user->id for providing the route parameter with the Form facade.

You can use this method on your code:
{{ Form::open(array('url'=>'admin/users/store' , 'method' =>'POST')) }}
and your route define by this method in web.php file:
Route::post('users/store', 'admin\UserController#store');

Related

Use of Undefined Constant Demolays - Assumed [Laravel Error]

I got an error in laravel, but idk if is on controller or blade file.
Controller Code:
public function edit($id)
{
$demolays = tbl_demolay::find($id);
return view('demolay.edit', compact(demolays));
}
Blade Code:
{!! Form::model(['method' => 'PATCH','route' => ['demolay.update', $demolays->id]]) !!}
#include('demolay.form')
{!! Form::close() !!}
You're getting this error because you need to pass string to the compact(). So, change it to:
return view('demolay.edit', compact('demolays'));

error in Laravel 5.4 resource controller using various methods

I created a NotesController with php artisan command
php artisan make:controller NoteController --resource
Route
Route::resource('notes','NoteController');
I checked them using route:list command too. All route exists.
But when I try to send the form to notes.store it gets redirected to localhost/blog/notes/ and shows
Index of localhost/blog/public/notes/
[ICO] Name Last modified Size Description
[PARENTDIR] Parent Directory -
Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/7.0.9 Server at localhost Port 80
Create form is
{!! Form::open(['method' => 'POST', 'route' => 'notes.store', 'class' => 'form-horizontal']) !!}
{!! Form::hidden('user_id', Auth::user()->id) !!}
{!! Form::label('level', 'Level') !!}
{!! Form::select('level', $level,null, ['class' => 'form-control', 'required' => 'required']) !!}
{!!Form::label('faculty','Faculty:')!!}
{!!Form::text('faculty',null, array('class'=> 'form-control'))!!}
{!! Form::label('notecatagory', 'Note Catagory') !!}
{!! Form::select('notecatagory', $notecatagory,null, ['class' => 'form-control', 'required' => 'required']) !!}
{!!Form::label('title','Title:')!!}
{!!Form::textarea('title',null, array('class'=> 'form-control'))!!}
<div class="btn-group pull-right">
{!! Form::submit("Create Post", ['class' => 'btn btn-block btn-success', 'style'=>'margin-top : 20px;margin-bottom: 20px;']) !!}
</div>
{!! Form::close() !!}
I manually entered and checked data notes.show and notes.update works properly but I have problem with notes.index and notes.store I have other posts controller which works fine. I tried editing posts controller but problem is still the same
Note Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Relations\Relation;
use Session;
use App\Note;
use
App\User;
class NoteController extends Controller
{
public function __construct(){
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('notes.index');
}
public function store(Request $request)
{
$this->validate($request, array(
'user_id'=> 'required |number',
'level'=>'required',
'faculty'=>'required',
'notecatagory'=>'required',
'title'=> 'required'
));
$note = new Note;
$note->user_id = $request->user_id;
$note->level = $request->level;
$note->faculty = $request->faculty;
$note->notecatagory = $request->notecatagory;
$note->title = $request->title;
$note->save();
Session::flash('success','Note successfully created');
return redirect()->route('notes.show', $note->id);
}
I don't know what is wrong in laravel. After trying all day, I made some changes in route and it started working.
I changed the route from
Route::resource('notes','NoteController');
to
Route::resource('note','NoteController');
and changed folder name from notes to note and all other routes to note.index note.store . Without any other changes the same files started working. I still don't know what happened. If you know please let me know

Laravel 5: Trying to get property of non-object through method injection

I am using Route-Model-Binding with method injection to retrieve the $post->id of the post I am commenting on, but I keep getting this error
Trying to get property of non-object (View: C:\xampp\htdocs\reddit\resources\views\partials\post.blade.php) (View: C:\xampp\htdocs\reddit\resources\views\partials\post.blade.php)
This is the method I have, injecting Post $post then trying to get $post->id
dd($post) retrieves nothing at all even if I dump the model alone.
public function post_this_comment(Request $request, Post $post) {
$post = Post::whereId($post->id)->first(); // this is where I'm getting the post
$comment = new Comment;
$comment->user_id = Auth::id();
$comment->comment = $request->input('commenter_comment');
$comment->parent_id = $request->input('commenter_parent');
if($comment->parent_id > 0){
$my_parent = Comment::find($comment->parent_id);
$comment->parents = $my_parent->parents.'.'.$comment->parent_id;
}else{
$comment->parents = '0';
}
$comment->save();
$per_page = $request->input('per_page');
$comment_list = view('post/show')
->with('comments', $this->comment_list($per_page, $request))
->with('total_comments', $this->total_comments())
->with('per_page', $per_page)
->with('post', $post)
->render();
$response = array(
'status' => 'success',
'msg' => 'Comment Saved!',
'comment_list' => $comment_list
);
return Response::json($response);
}
This is the view, I have opened a form even though I don't need it because I'm submitting data via ajax.
{!! Form::open(['route' => ['post_this_comment', $post]]) !!}
<div class="comment-fields">
<div class="commenter-comment">
<div class="form-group col-md-12">
<textarea id="commenter_comment" name="commenter_comment" class="form-control comment-field" title="User's comment" placeholder="Comment Text"></textarea>
</div>
</div>
<div class="commenter-name-email">
<input type="hidden" id="commenter_parent" name="commenter_parent" class="commenter-parent" value="0">
</div>
<div class="commenter-captcha">
<div class="col-md-3 text-right">
Comment
</div>
</div>
{!! Form::close() !!}
Routes
Route::resource('posts', 'PostsController');
Route::post('{post}/post_this_comment', ['as' => 'post_this_comment', 'uses' => 'PostsController#post_this_comment']);
RouteServiceProvider
$router->model('articles', 'App\Article');
$router->model('subreddit', 'App\Subreddit');
$router->model('posts', 'App\Post');
$router->model('moderators', 'App\Moderator');
$router->model('comments', 'App\Comment');
The parameter in your route needs to match the one you used for your route model binding. In your case you have defined posts: $router->model('posts', 'App\Post'); but you are using {post} (without the 's') as the parameter in your route. Instead your route should be:
Route::post('{posts}/post_this_comment', ['as' => 'post_this_comment', 'uses' => 'PostsController#post_this_comment']);
If you want to inject your Post model in to you method.
You should bind the model using something like this:
$router->model('post', 'App\Post'); // 'post' parameter is used here
So that you can use the following:
Route::post(
'{post}/post_this_comment', // post parameter is used here
[
'as' => 'post_this_comment',
'uses' => 'PostsController#post_this_comment'
]
);
Bith parameters should match. When you bind some model using a parameter for example, $router->model('user', 'App\User') you said the framework to bind the appropriate User model when it sees a user parameter used in a route.

Laravel conflicting routes

My routes.php excerpt:
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function() {
Route::resource('posts', 'PostsController', [
'except' => ['show']
]);
Route::delete('posts/trash', [
'as' => 'posts.trash.empty',
'uses' => 'PostsController#emptyTrash'
]);
});
My PostsController.php excerpt:
/**
* DELETE /admin/posts/{id}
*/
public function destroy($id)
{
// code
}
/**
* DELETE /admin/posts/trash
*/
public function emptyTrash()
{
// code
}
The problem is that Laravel confuses the 'trash' string in a DELETE /admin/posts/trash request as an {id} parameter. As a consequence, the destroy() method is called instead of emptyTrash(). Why and What can I do for this?
Firstly, order matters. Laravel will search the routes for a match in the order you register them. As you figured out, Laravel will take trash as an id and therefore the URI matches the resource route. Since that route is registered before your additional one, it will use the resource route.
The simplest fix is to just change that order:
Route::delete('posts/trash', [
'as' => 'posts.trash.empty',
'uses' => 'PostsController#emptyTrash'
]);
Route::resource('posts', 'PostsController', [
'except' => ['show']
]);
If you don't like that you can try to limit the parameter for your resource route to numbers only. Unfortunately you can't just add a ->where() to the resource route like you could with others.
Instead you have to define a global pattern for the route parameter. The route parameter Route::resource chooses is the resource name (in snake_case).
So this should work for you:
Route::pattern('posts', '[0-9]+');
Somewhere in your view, you should have a button or a link for actually deleting the post. The view should look something like this:
#section('content')
<div class="panel panel-default">
<div class="panel-heading clearfix">
<b>{{ $post->post_name . ' (id:' . $post->post_id . ')' }}</b><br />
<b> {{ link_to_route('overview', 'Go Back To Post List') }} </b>
<div class="pull-right">
// FORM FOR DELETING POST
{{ Form::open(array('route' => array('delete_post', $post->post_id))) }}
{{ link_to_route('edit_post', 'Edit Post', array('id' => $post->post_id), array('class' => 'post_img_button_edit')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Delete Post', array('class' => 'post_img_button_delete')) }}
{{ Form::close() }}
</div>
<div class="pull-right">
// FORM FOR EMPTYING TRASH
{{ Form::open(array('route' => 'empty_trash')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Empty Trash', array('class' => 'post_img_button_delete')) }}
{{ Form::close() }}
</div>
</div>
/* Additional HTML code within view */
Your controller should be similar to this:
public function destroy($id)
{
$this->post->delete($id);
return \Redirect::route('overview');
}
public function emptyTrash()
{
// code for collecting and emptying Trash
}
And your routes should look similar to this:
Route::delete('admin_posts/admin_posts/{id}/destroy', array('as'=>'delete_post', 'uses'=>'PostsController#destroy'));
Route::delete('posts/trash', array('as'=>'empty_trash', 'uses'=>'PostsController#emptyTrash'));
The name of your route for actually deleting posts be 'delete_post'.
The name of your route for emptying your trash will be empty_trash
Basically you're explicitly defining your routes so that you'll avoid less ambiguity and Laravel will know which routes to take. Hopefully this information will help!

Upon seemingly correct routing getting error Route not defined! - Laravel 4

I'm developing a very basic application using Laravel 4.1 where users can signup and ask question, pretty basic stuffs. I'm now a bit confused about the restful method which would look something like this public $restful = true in laravel 3. Since then laravel has changed a lot and I got stucked with the restful idea. So I decided to leave it and go on developing the skeleton of my application. Everything went well until I created the postCreate method in my homeController to let authorized users submit their question through a form. I believe I routed the method correctly and the index.blade.php view is alright as well. I just can't figure out why I'm getting this following error even though the codes seem to be okay.
Route [ask] not defined. (View: C:\wamp\www\snappy\app\views\questions\index.blade.php)
If you have got what I'm doing wrong here would appreciate if you point it out with a little explanation.
I'm totally new in laravel 4 though had a bit of experience in the previous version.
Here's what I have in the HomeController.php
<?php
class HomeController extends BaseController {
public function __construct() {
$this->beforeFilter('auth', array('only' => array('postCreate')));
}
public function getIndex() {
return View::make('questions.index')
->with('title', 'Snappy Q&A-Home');
}
public function postCreate() {
$validator = Question::validate(Input::all());
if ( $validator->passes() ) {
$user = Question::create( array (
'question' => Input::get('question'),
'user_id' => Auth::user()->id
));
return Redirect::route('home')
->with('message', 'Your question has been posted!');
}
return Redirect::route('home')
->withErrors($validator)
->withInput();
}
}
this is what I have in the routes.php file
<?php
Route::get('/', array('as'=>'home', 'uses'=>'HomeController#getindex'));
Route::get('register', array('as'=>'register', 'uses'=>'UserController#getregister'));
Route::get('login', array('as'=>'login', 'uses'=>'UserController#getlogin'));
Route::get('logout', array('as'=>'logout', 'uses'=>'UserController#getlogout'));
Route::post('register', array('before'=>'csrf', 'uses'=>'UserController#postcreate'));
Route::post('login', array('before'=>'csrf', 'uses'=>'UserController#postlogin'));
Route::post('ask', array('before'=>'csrf', 'uses'=>'HomeController#postcreate')); //This is what causing the error
And finally in the views/questions/index.blade.php
#extends('master.master')
#section('content')
<div class="ask">
<h2>Ask your question</h2>
#if( Auth::check() )
#if( $errors->has() )
<p>The following erros has occured: </p>
<ul class="form-errors">
{{ $errors->first('question', '<li>:message</li>') }}
</ul>
#endif
{{ Form::open( array('route'=>'ask', 'method'=>'post')) }}
{{ Form::token() }}
{{ Form::label('question', 'Question') }}
{{ Form::text('question', Input::old('question')) }}
{{ Form::submit('Ask', array('class'=>'btn btn-success')) }}
{{ Form::close() }}
#endif
</div>
<!-- end ask -->
#stop
Please ask if you need any other instance of codes.
Your 'ask' route is not named. When you pass 'route' => 'foo' to Form::open, that assumes you have a route named 'foo'. add 'as' => 'ask' to your /ask route and it should work.
Alternatively, use URL or Action to resolve the form's target url instead:
Form::open(['url' => 'ask']);
Form::open(['action' => 'HomeController#postCreate']);
you are using name route ask in your form which is not exist. I have created the name route ask for you.
Route::post('ask', array('before'=>'csrf', 'as' => 'ask', 'uses'=>'HomeController#postcreate'));
{{ Form::open( array('route'=>'ask', 'method'=>'post')) }}
^^^^ -> name route `ask`
{{ Form::token() }}

Categories