Ahmed Essam
Ahmed Essam

Reputation: 1010

Trying to get property of non-object Error in Laravel 5.2

I searched a lot for a solution for this problem but I couldn't find anything useful. I have these routes:

Route::group(['prefix'=>'post'], function(){
    Route::get('{id}', 'PostsController@show');
    Route::get('create', function(){
        return 'ok';
    });
});

When I try to access http://localhost:8000/post/create/ I get this error:

Trying to get property of non-object (View: C:\xampp\htdocs\myblog\resources\views\post.blade.php)

but my post.blade.php shows any post correctly without any problems. Have any idea why I get this error?

Notice: The get route which uses show method in PostsController works correctly an it uses post.blade.php without any problems.

Upvotes: 0

Views: 595

Answers (3)

Saumya Rastogi
Saumya Rastogi

Reputation: 13709

The laravel is taking '/create' as the {id} parameter and this 'create' as a parameter is going as a argument to the show() method inside PostsController. This is happening because '{id}' route is coming in first order then the 'create' route in routes file.

There are 2 ways to solve this problem...

  1. Move your 'create' route above the '{id}' route.

  2. If you work in an intelligent way you can specify the parameter id (if its numeric) like this...

By specifying pattern matching in the route for the id parameter

Route::get('{id}', 'PostsController@show')->where('id', '[0-9]+');

Upvotes: 1

Shyam Naru
Shyam Naru

Reputation: 305

It's considering 'create' as a parameter to {id}.

Restructure the route. It will work.

Route::group(['prefix'=>'post'], function(){
    Route::get('create', function(){
        return 'ok';
    });
    Route::get('{id}', 'PostsController@show');
});

Upvotes: 0

Hrach
Hrach

Reputation: 347

move the "create" route above the '{id}' route,in your case it's not working as it's calling the "show" method on your PostsController,because "create" string is recognizing as a "{id}" pattern

Upvotes: 0

Related Questions