Laravel Authorize (Authorized)

Source: Internet
Author: User

1. Method One

namespace App\providers;...classAuthserviceproviderextendsserviceprovider{... Public functionBoot (gatecontract$gate) {Parent:: Registerpolicies ($gate); Defining authorization Capabilities$gate-Define(' Update-post ',function($user,$post){            return $user->id = =$post-user_id;    }); }}
namespace App\http\controllers;...//Verify authorization in the controllerclassPostcontrollerextendscontroller{ Public functionShow$id)    {        //auth ()->logout ();Auth ()->loginusingid (3); $post= Post::findorfail ($id); //if (Gate::d enies (' Show-post ', $post)) {//Abort (403, ' Sorry, not sorry! '); }//$this->authorize (' Update-post ', $post);        returnView (' Posts.show ',Compact(' Post ')); }}
Verify authorization in view and Show Update link if passed
$post->title}}@can ($post)<a href=# >update</a>@endcan

2. Method Two

Establish policy

PHP Artisan Make:policy Postpolicy

Registered

namespace App\providers; ... class extends serviceprovider{    protected$policies = [        //  ' app\model ' = > ' App\policies\modelpolicy ',        \app\post::class = \app\policies\postpolicy: : Class,    ];

Defining class policy functions

namespace App\policies;  Use App\user;  Use App\post; class postpolicy{   // can establish multiple test methods corresponding to different scenes public    function$ User$post)    {        return$user$post  user_id;}    }

Use the same method as above.

Laravel Authorize (Authorized)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.