Search code examples
phplaravelviewmiddlewarelaravel-artisan

Laravel: Why should I use Middlewares?


For example in my User class I have an 'isAdmin' function which checks the role value of the user in the users table column, So I really don't see the need of using middlewares in this case.
If I want to check if the user is the owner of a particular post in my application I will do something like this in my view:

@if(Auth::user()->id == $user->id) //$user is the passed user to the view
    <p>I am the owner of the post</p>
@elseif(Auth::guest())
    <p>I'm a visitor</p>
@else
    <p>I'm a registered user visiting this post</p>

Am i right or I'm doing something wrong?


Solution

  • One of the great benefits of middleware is that you can apply a set of logic to a route group and not have to add that code to each controller method.

    Route::group(['prefix' => '/admin', 'middleware' => ['admin']], function () {
         // Routes go here that require admin access
    });
    

    And in the controller, you never have to add checks to see if they are an admin. They will only be able to access the route if they pass the middleware check.