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'));
`
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With