K
K
Karpkarp2020-02-16 10:44:23
Laravel
Karpkarp, 2020-02-16 10:44:23

How can I fix the error trying to get property of non-object in laravel?

I get this error if an unauthenticated user tries to navigate the route

Route::get('home', '[email protected]')->name('home');

I have an intermediary working on this route
public function handle(Request $request, Closure $next)
    {

        if(\Auth::user()->role_id != 1) {
            return redirect('')->with('success', 'Я вас сюда не звал');
        }

        return $next($request);
    }

The intermediary checks the role_id field in the table and if it is not equal to 1, then throws a banana and redirects to the main one. As I understand it, the error occurs due to the fact that an unauthenticated user does not have any role_id.

How can this error be corrected?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kokhan, 2020-02-16
@SkazochNick

At you there is a check of already authorized user. Therefore, you first need to check if the user is authorized. If not, send to the authorization page, and if yes, then check the role_id property.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question