Gates & Policies

  • Système de permission plus avancé que le système d'authentification (auth).

Gates

  • Permet d'ouvrir ou de fermer une action selon des conditions.

Exemple:

  • Dans App/Providers:

<?php

public function boot()
    {
        $this->registerPolicies();

        Gate::define('update-post', function($user, $post){

            return $user->id==$post->user_id;});
    }

//ou

public function boot()
    {
        $this->registerPolicies();
         Gate::define('update-post', 'PostPolicy@update');
    }

//ou

public function boot()
    {
        $this->registerPolicies();
        Gate::resource('posts', 'PostPolicy');
    }

Exemple:

  • Dans le controller:

<?php

    public function edit()
    {
        dd(Gate::allows('update-post'));
        //instructions
    }

//ou

    public function edit()
    {
        this->authorize('update-post', $post);
        //instructions
    }

//ou pour un utilisateur en particulier

    public function edit()
    {
        Gate::forUser($user)->denies('update-post');
        //instructions
    }

Middleware

Exemple:

  • Dans les routes:

<?php

       Route::get('/post/{post}', function($post)
        { 
            //instructions
        }->middleware ('can:update-post, post);

//ou 

        Route::get('/post/{post}', function($post)
        { 
            //instructions
        }->middleware ('cant:update-post, post);
Made with Slides.com