主要还是使用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
user是user模型Post
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’,’修改失败!’);
}
}