How to use Auth::user()->id on route?

Asked

Viewed 173 times

0

| id | user_id | url_to | controller |  isAuthorized |
| 1  |    1    |  page1 | DadosCtrl  |       1       |  
| 2  |    2    |  page3 | Dados3Ctrl |       1       |  
| 3  |    1    |  page2 | Dados2Ctrl |       1       |  

I have a middleware that is only allowed to enter who is authorized (isAuthorized = 1). But I have to make a permit for that one user do not have access to Controller of the other

Route::group(['middleware' => ['auth', 'activated', 'pages.auth']], function(){

    echo Auth::user()->id; // ERRO : Trying to get property of non-object
    Route::get('pages', 'Pages\PagesController@index');
    $pages = Pages::where('isAuthorized', true)->get();
    //$pages = Pages::where('isAuthorized', true)->where('user_id', Auth::user()->id)->get(); 
    // precisaria do Auth::user()->id, mas ocorre um erro
    foreach($pages AS $p){
        $s = $p->page;
        Route::get($s->url_to.'/', "Pages\\$s->controller@index");
        Route::get($s->url_to.'/{id}', "Pages\\$s->controller@show");
    }
});

The user can only have access to Controller if you are authorized. You may not have access to Controller other’s user. for example:

  • If user_id => 1: may have access to Controller DadosCtrl and Dados2Ctrl; if he accesses the Dados3Ctrl, he won’t have access.
  • If user_id => 2: may have access to Controller Dados3Ctrl; if he accesses the DadosCtrl and Dados2Ctrl, he won’t have access.

You are returning an error Trying to get property of non-object when using Auth::user->id en route.

1 answer

0

You instantiate the stab to the Auth:: ?

using the stab wound:

use Illuminate\Support\Facades\Auth;

// receives the current user :

 $user = Auth::user();

// receives the current user id:

$id = Auth::id();

Reference - authentication

--

I suggest using a Middleware to "filter" the user to a respective route.

reference - Standard middleware

*I didn’t write the code because I’m a little rusty in the basement;

  • Auth::id() is returning null

  • Strange, you’re wearing the $user = Auth::user(); to receive the current user ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.