Laravel政策总是错误的

时间:2018-03-05 11:01:00

标签: laravel policy

我为一个模型制定了政策。政策类如下:

namespace App\Policies;
use App\User;
use App\Models\Address;
use Illuminate\Auth\Access\HandlesAuthorization;

class AddressPolicy
{
    use HandlesAuthorization;


    public function delete(User $user, Address $address)
    {
        return $user->id === $address->user_id ;
    }
}

我在authServiceProvider

中注册了该策略
namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Models\Address ;
use App\Policies\AddressPolicy;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Address::class => AddressPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }

我在控制器中使用此策略

namespace App\Http\Controllers\User;

use App\Models\Address;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth ;

class AddressController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function destroy(Address $address)
    {

        $this->authorize('delete', $address);
        $address->delete();
        return response()->json(['msg'=>'success'], 200);  
    }

当我在控制器中请求destroy方法时,它总是返回403状态,当我删除这一行" $ this-> authorize(' delete',$ address)&# 34;,数据可以删除。我已经尝试了几个解决方案并搜索了许多相同的问题,但没有一个解决了我的问题。

0 个答案:

没有答案