samedi 29 avril 2017

Laravel API give json response when got error This action is unauthorized

I newbie in Laravel API. I do the update function. User can update the only their own post and cant update other people post. It worked. When user try to update other user's post, it will show the error response. But now it just show error like image below.

error diplay like this

I want show error like this

{
"status": "error",
"message": "This action is unauthorized",
}

This is my code for PostController.

public function update(Request $request, Post $post)
{

    $this->authorize('update', $post);    
//this will check the authorization of user but how to make if else statement, if the post belong to the user it will show this json below but if the post belong to other, it will show error message(response json) 


    $post->content = $request->get('content', $post->content);
    $post->save();

    return fractal()
        ->item($post)
        ->transformWith(new PostTransformer)
        ->toArray();

}

This code for PostPolicy

public function update(User $user, Post $post)
 {
    return $user->ownsPost($post);
 }

This is code for User model

public function ownsPost(Post $post)
{
    return Auth::user()->id === $post->user->id;
}

This code for AuthServiceProvider

 protected $policies = [
        'App\Post' => 'App\Policies\PostPolicy',
];

Aucun commentaire:

Enregistrer un commentaire