Reputation: 41
I try to create a application using php Laravel framework .When i use Auth::user()->id in my route file i got error "Trying to get property of non-object" .So how to i fix it?
This is my route file
`
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', 'HomeController@index');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
$common_variable=App\MyModel::where('site_id',Auth::user()->id)->count();
view()->share(compact('common_variable'));
`
Upvotes: 4
Views: 13155
Reputation: 10487
If you want something to execute you should use laravel 5 middleware.
1.- php artisan make:middleware newMiddleware.
2.- Add your middleware to all routes you need by setting the middleware property.
Route::get('test', ['before' => 'newMiddleware', function(){
//
}]);
3.- Now do in a proper way what you where trying to accomplish
$user_id = Auth::user()->id()
if($user_id){
$variable = \App\Model::where('site_id', '=', $user_id)
}
return $variable
4.- Now you have your wanted value in your route function / controller, you can pass it to the view along with other data.
Upvotes: 2
Reputation: 1602
You can't access the authenticated user in a route model binding because the authentication middleware has not run. Please see thus discussion thread where some workarounds are proposed.
Upvotes: 1
Reputation: 1092
This is how I did this. I wanted to restrict a view to an owner of the requested object, in my case an "API Key". I used Laravel's route model binding to do this.
Route::model('apikeys', 'Apikey');
Route::bind('apikeys', function($value, $route) {
return Apikey::whereSlug($value)->where('users_id', '=', Auth::user()->id)->where('approved', '=', true)->where('deleted', '=', false)->first();
});
Route::resource('apikeys', 'ApikeysController');
In this case, I'm passing in the value of the requested "slug" (i.e. the friendly url of the api key), then appending an AND'ed where clause with the authenticated user ID, approved = true, and deleted = false.
Upvotes: 0
Reputation: 2741
you have to define your route, otherwise it will not work
Route::get('/testauth', function()
{
var_dump(Auth::user());
// your code here
});
Now hit the 'testauth' route. It should be working.
Upvotes: 1
Reputation: 10618
you have to make sure your user is authenticated
$common_variable=Auth::check() ?App\MyModel::where('site_id',Auth::user()->id)->count() : 0;
when you are not authenticated Auth::user() will always return null and you are referring id on a null object which give you the error
Upvotes: 0