Search code examples
phplaravel-5authorize

Laravel 5 Authorize User to see certain Buttons


I just started learning Laravel 5 and came across a problem i could't solve: How to tell that a certain user can only see certain things.

For example if i view a profile which is not my own, the "Edit Profile" button should not be visible. But if i look at my own profile this button should be visible.

What i already got is to authorize certain requests. For example to authorize a user to actually update a profile:

public function updateProfile(Profile $profile, UpdateProfile $request){
      //update the given profile
}

So UpdateProfile is here a Request Class which has a authorize() and a rule() method and in the authorize() Method i check if the logged User is updating his own profile.

So i thought maybe i can use the authorize() method on its own, but i am not really sure how.

Now of course i could always check sth like:

if($user -> userID == Auth::user() -> userID)

But what if i need to check sth more complex, for example when i write a post and want to show a delete button for that post i want to check: Is the user admin, if not is the user writer of that post, if any of this is true, show delete button.

So my question would be, where would i check sth like this in laravel 5?


Solution

  • You could write a userCanEdit method on your Post class. Something like this:

    function userCanEdit(User $user)
    {
        return $user->isAdmin() || $this->user_id == $user->id;
    }
    

    And then just call it on your view:

    @if ($post->userCanEdit(Auth::user()))
        <a href="{{ url("edit/{$post->getId()}") }}">Edit</a>
    @endif
    

    The advantage of this is that you keep your view clean and centralize the business logic in a single, reusable, method. If the definitions for a user who can edit a post ever change, that is the only place you'll have to worry about.