Writing a Blog in Laravel: App Policy

Naren Chitrakar
Sep 7, 2018 · 2 min read

We have added the creating and updating a post. User should be able to add a post and user should be able to update posts as well but only the posts that belong to that very user.

Laravel provides an easy way to do this as well in form of Policies. It is obvious by now that Laravel has a command to create policies as well.

Let’s do this

php artisan make:policy Post

This will create a file app/Policies/Post.php with content.

We have created a policy for post, now we need to register the Policy and tell Laravel what model corresponds to which policy. This is done in app/Providers/AuthServiceProvider.php

The $policies of AuthServiceProvider property map these.

After this we can start creating policies. For first implementation, let’s use this in updating post. Typically, we check if the logged in user can do things. We have mapped out Post policy with Post model. So for specific permission of a model, we add method with the name. For example to check if a user can update a post, we create a method update in post policy.

public function update(User $user, \App\Post $post)
{
return $user->id === $post->user_id;
}

The method receives currently logged in user as the first argument and the model we are editing as the second argument. We simply check if the author of the post is same as the logged in user.

We use this while updating post as.

$user->can('update', $post)

Implementing this code into our controller, it looks like this

We pass an error message to the view with with.The key and value is stored in session which we can fetch in view. These values are stored for a single redirect, meaning, if we refresh the page, the session remove the value from session. We can use Session::get('key') to fetch the value

We are redirecting the user to listing page with error message. So the change also needs to be in the blog listing view.

This is it, now if I go to edit link of a post that I did not write and try to submit the change. I will get this error.

The changes I made for this post are here.