Home > Enterprise >  Laravel 8 : Attempt to read property "user_id" on int
Laravel 8 : Attempt to read property "user_id" on int

Time:11-15

I have this error when i want to create my gates for giving permissions to edit the events for the user who create it. Thank you for helping :)

my list page:

@if(Gate::allows('Utilisateur', $events))
        <a class="btn btn-warning" href="{{route('events.edit',$events->id)}}">Editer</a> 
        @endif

EventsController:

 public function edit($id)
    {
        
        if(!Auth::check())
        { 
            return redirect('login');
        }
        $event=Events::findOrFail($id);
    if(!Gate::allows('Utilisateur', Auth::id(), $event)){ 
        abort('403');
    }
    return view('events.edit', ['events' => Events::findOrFail($id)]);
    }

Authserviceprovider:

 public function boot()
    {
        $this->registerPolicies();
        
        Gate::define('Utilisateur', function ($user,$event) {
            // dd("zzzz".$event);
            if($user->id===$event->user_id){
                return 1;
            }
            return 0;


        });
    }

CodePudding user response:

Remove Auth::id() from allows method.

if(! Gate::allows('Utilisateur', $event)) { 
    abort('403');
}

Note that you are not required to pass the currently authenticated user to these methods. Laravel will automatically take care of passing the user into the gate closure.

https://laravel.com/docs/8.x/authorization#authorizing-actions-via-gates

  • Related