laravel权限控制(登录,增删改查权限)

主要还是使用Auth门脸类进行登录的验证

1.使用Auth门脸类要让User.php继承use Illuminate\Foundation\Auth\User as Authenticatable;
namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
use Notifiable;
//your code
}

2.门脸类的方法
Auth::attempt(‘登录要验证的数组’,’是否记住用户’)
PS:值得注意的是,这里登录要验证的数组肯定有 ‘username’和‘password’
password存储到数据库表要用bcrypt()进行用这个加密,不能用md5或者其他,因为Auth底层就是用bcrypt()对password进行加密解密,否则验证不通过
Auth::logout();

3.当你登录成功以后,可以使用的方法
Auth::id()//当前登录用户的id
Auth:check()//…
还有很多,自己查文章吧

使用 policy 进行增删改的权限(前提是使用了Auth进行了用户验证)

1.php artisan make:policy PostPolicy

2.修改PostPolicy,添加两个方法
public function update(User user,Post post) {
return user>id== post->user_id;
}
public function delete(User user,Post post) {
return user>id== post->user_id;
}
User useruserPost post 是文章模型

3.在App\Providers\AuthServiceProvider.php 中的 $policies数组添加
Post::class => PostPolicy::class(建议使用::class形式,我使用字符串写类名,结果无效,很郁闷)

4.在controller中要控制权限的方法里写逻辑,比如
public function update(Post post) {this->authorize('update', post);// post 即当前这片文章的权限
this>validate(request(),[title=>required,content=>required]); post->title = request()->input(‘title’);
post>content=request()>input(content);if( post->save()){
return redirect(‘/posts’)->with(‘success’,’修改成功!’);
}else{
return back()->with(‘error’,’修改失败!’);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值