2

I newbie in Laravel API. There is an update function which only allows users to update their own post. It worked. When users try to update other user's post, it alswo worked, but it shows the error like this image. Actually i want it show in response json.

I want to show message 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',
];

Hope anyone can help me.

akmal
  • 21
  • 4

1 Answers1

0

I'm using Laravel 5.4

In the app/Exceptions/Handler.php class you can change the render function like so

public function render($request, Exception $exception)
{
    $preparedException = $this->prepareException($exception);

    if ($preparedException instanceof HttpException) {
        return response(
            [
                'message' => sprintf(
                    '%d %s',
                    $preparedException->getStatusCode(),
                    Response::$statusTexts[$preparedException->getStatusCode()]
                ),
                'status' => $preparedException->getStatusCode()
            ],
            $preparedException->getStatusCode(),
            $preparedException->getHeaders()
        );
    }

    return parent::render($request, $exception);
}

Or if you look further in the rendering, overriding the renderHttpException might be a little safer. This will remove the custom error pages in views/errors

protected function renderHttpException(HttpException $e)
{
    return response(
        [
            'message' => sprintf(
                '%d %s',
                $e->getStatusCode(),
                Response::$statusTexts[$e->getStatusCode()]
            ),
            'status' => $e->getStatusCode()
        ],
        $e->getStatusCode(),
        $e->getHeaders()
    );
}