Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 : How to use Auth::user()->id in route

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'));

`

like image 265
sarath lk Avatar asked Sep 28 '22 11:09

sarath lk


2 Answers

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.

like image 111
Borjante Avatar answered Oct 03 '22 00:10

Borjante


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.

like image 22
Kamran Avatar answered Oct 03 '22 00:10

Kamran