MB
1 month ago
254
9
Laravel

Error when $request->user()->cannot()

Posted 1 month ago by MB

Hope one of you might be able to help me here :)

I'm trying to validate if user is allowed to update a model, but getting the following error:

Error
Call to a member function cannot() on null

My controller:

    public function store(Request $request)
    {

        ...

        $pug = Pug::find($request->pug_id);

        # Error if locked and access denied
        if($pug->locked == 1 && $request->user()->cannot('update', $pug)) {

            notify()->error('Error... Stuff has been closed');
            return redirect()->back();
        }
....
PugPolicy

    public function update(?User $user, Pug $pug)
    {

        if(request()->hasCookie($pug->id.'-'.$pug->assist)) {
            return true;
        }

        if($user) {

            if($user->id == $pug->user_id) {
                return true;
            }

        }

        return false;

    }

The Policy works fine for the rest of the site, do I dont think that is the problem. Also, found the following in the documentation:

https://laravel.com/docs/5.2/authorization#via-the-user-model

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller
{
    /**
     * Update the given post.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        $post = Post::findOrFail($id);

        if ($request->user()->cannot('update-post', $post)) {
            abort(403);
        }

        // Update Post...
    }
}

Also, using @can('update', $pug) in Blade works fine.

It should work, right? Not sure what is wrong.

Please sign in or create an account to participate in this conversation.