Search code examples
laravellaravel-5middlewarelaravel-bladehttp-status-code-403

Laravel middleware 403


I was watching laravel tutorial about Authorization Essentials (8:15) and tried to do the same as in the video.

I generated auth, created and registered a policy when I added middleware to routes file, but it always shows 403 even I change user role_id. I don't understand why it doesn't work and shows 403, maybe someone can explain to me? Where I made a mistake? Also, dd() don't work in policy when I using middleware in route file.

Laravel 5.8

web.php

Route::get('/home', 'HomeController@index')->name('home')->middleware('can:view,order');

AuthServiceProvider.php

protected $policies = [
     'App\Order' => 'App\Policies\OrderPolicy',
];

OrderPolicy.php

public function view(User $user, Order $order)
{
    return $user->role_id === 2;
}

but policy works in home.blade.php when I using can in views file. $this->authorize and other ways also work in controller

@can('view', $order)
    test
@endcan

HomeController.php

public function index(Order $order)
{
    //$this->authorize('view', $order);
    $orders = Order::all();

    return view('home', [
        'orders' => $orders,
        'order' => $order,
    ]);
}

Solution

  • Code didn't work because there was no attribute in home route. Passing variable to url is the answer http://localhost/home/1 and everything works as it should