i want to make authorize for edit page to not display for anyone except users and authorize function don't work with me it return 403 THIS ACTION IS UNAUTHORIZED. in the two case
class ProfilesController extends Controller
{
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index($user)
{
return view('profiles.index', [
'user' =>User::findOrFail($user)
]);
}
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profiles.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'url' => 'url',
'image' => '',
]);
auth()->user->profile->update($data);
return redirect("/profile/{$user->id}");
}
}
CodePudding user response:
You need to create and register the policy in AuthServiceProvider class. For more info: https://laravel.com/docs/master/authorization#registering-policies
Assuming you have a Profile model class which contains a "user_id", the implementation would be more or less like this.
<?php
namespace App\Policies;
use App\Models\Profile;
use App\Models\User;
class ProfilePolicy
{
/**
* Determine if the given profile can be updated by the user.
*
* @param \App\Models\User $user
* @param \App\Models\Profile $profile
* @return bool
*/
public function update(User $user, Profile $profile)
{
return $user->id === $profile->user_id;
}
}
Of course this is just an example, as there are different ways the policy might be implemented