Saturday, March 4, 2017

[SOLVED]How can I do Authorization Policies in Laravel 5.3?

My FavoritePolicy is like this :
<?php
namespace App\Policies;
use App\User;
use App\Models\Favorite;
use Illuminate\Auth\Access\HandlesAuthorization;
class FavoritePolicy
{
    use HandlesAuthorization;
    public function view(User $user, Favorite $favorite)
    {
        return $user->id === $favorite->user_id;
    }
}

My FavoriteController is like this :
<?php
use App\Models\Favorite;
...
class FavoriteController extends ApiController
{
    ...
    public function index(Favorite $favorite)
    {
        $this->authorize('view', $favorite);
        return view('profile.favorite');
    }
}

My AuthServiceProvider is like this :
<?php
namespace App\Providers;
use App\Models\Favorite;
use App\Policies\FavoritePolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Favorite::class => FavoritePolicy::class,
    ];
    public function boot()
    {
        $this->registerPolicies();
    }
}

When I run my system to display favorite listing, there exist error like this :
Whoops, looks like something went wrong.
1/1 HttpException in Handler.php line 115: This action is unauthorized.
What the implementation of Authorization Policies is correct?
I try dd($user) in view method(FavoritePolicy), the result displays user data is being logged. It's true
But I try dd($favorite), the result does not display favorite data of the user who is currently logged. Whereas I check on the table, favorite data of the user who is currently logged is exist
How can I solve this problem?

Update
There result of dd($favorite) :
Favorite {#498 
  #fillable: array:3 [▶]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: []
  #original: []
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  +exists: false
  +wasRecentlyCreated: false
}

via moses toh

Advertisement