当前位置: 首页 > 后端技术 > PHP

Laravel5.4入门系列9.注册登录、用户关联

时间:2023-03-29 17:19:27 PHP

本节将实现文章、评论、用户关联功能。关系定义首先修改posts和comments表,添加user_id字段/database/migrations/2017_04_12_124622_create_posts_table.php/database/migrations/2017_04_15_062905_create_comments_table.phppublicfunctionup(){Schema::create('posts',$printtable){//添加$table->integer('user_id')->unsigned();$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');});}回滚,重新执行迁移:$phpartisanmigrate:refresh添加用户表、文章表、评论表的一对多关系:/app/User.phppublicfunctionposts(){return$this->hasMany(\App\Post::class);}publicfunctioncomments(){return$this->hasMany(\App\Comment::class);}添加多对一关系在文章、评论表和用户表之间:/app/Comment.php/app/Post.phppublicfunctionuser(){return$this->belongsTo(\App\User::class);}同时添加user_id添加到评论表的$fillable字段中。注册首先定义一个控制器,处理注册相关的业务:定义返回注册页面视图的方法:publicfunctioncreate(){returnview('registration.create');}创建注册页面:/resources/views/registration/create.blade.php@extends('layouts.master')@section('content'){{csrf_field()}}用户名:Email我们不会与他人分享您的电子邮件地址密码:再次输入密码:submit

@endsection定义路由响应注册提交:Route::post('/register','RegistrationController@store');定义处理注册提交的方法:/app/Http/Controllers/RegistrationController.phpuseApp\User;publicfunctionstore(){$this->validate(request(),['name'=>'required','email'=>'required|email','password'=>'需要|确认',]);$user=User::create(request(['name','password','email']));验证()->登录($用户);returnredirect()->home();}这个方法包括四个部分:验证字段,这里password使用confirmed验证规则,会自动匹配xxx是否和xxx_confirmation一致,所以前面的视图要按照规格创建用户并登录。用户返回名为“home”的路由。我们需要给路由命名以匹配第四步:Route::get('/posts','PostsController@index')->name('home');注册功能虽然完成了,但是我们保存密码使用的明文。我们可以定义一个修改器,每次保存密码时自动加密:/app/User.php处理用户登录业务的控制器:$phpartisanmake:controllerSessionsController当用户访问/login时,路由分发请求:Route::get('/login','SessionsController@create');create方法返回用户登录页面视图:/resources/views/sessions/create.blade.php@extends('layouts.master')@section('content'){{csrf_field()}}电子邮件<输入类型="email"class="form-control"name="email"id="email"required>密码:Login
@endsection用户点击登录后,路由分发请求:Route::post('/login','SessionsController@store');最后,控制器进程登录行为:/app/Http/Controllers/SessionsController.phppublicfunctionstore(){if(!auth()->attempt(request(['email','password']))){returnback()->withErrors(['messages'=>'请确保邮箱和密码正确!']);}returnredirect()->home();}我们使用Auth提供的attempt()用于认证的类,只需通过输入email和密码即可。attempt方法会对密码进行加密,并与数据库进行比对,匹配则为用户开启认证会话。同时,我们还自定义了返回的错误信息。logout和logout的实现比较简单。首先是路由:Route::get('/logout','SessionsController@destroy');控制器:publicfunctiondestroy(){auth()->logout();returnredirect()->home();}最后,我们优化导航,根据用户登录信息显示不同的设置项:主页新功能新闻新员工关于设置@if(Auth::check()){{Auth::user()->name}}注销@else登录注册@endif
注意如果要下拉down框架生效,需要引入相关js:权限控制实现登录和注销功能,进而实现用户行为可以控制首先是文章的权限控制。对于“未登录”的用户,只能阅读文章,所以可以直接使用Laravel提供的中间件来实现:/app/Http/Controllers/PostsController.phppublicfunction__construct(){$this->middleware('auth')->except(['index','show']);}表示只有授权用户才能访问除index和show之外的其他请求。然后是用户的权限控制:/app/Http/Controllers/SessionsController.phppublicfunction__construct(){$this->middleware('guest')->except(['destroy']);}表示只有访问者可以访问除销毁外的其他请求。完善文章和评论的创建最后,完善文章和评论的创建,绑定用户id。首先是文章的创建:/app/Http/Controllers/PostsController.phppublicfunctionstore(Request$request){$this->validate(request(),['title'=>'required|unique:posts|max:255','body'=>'required|min:5',]);$post=newPost(request(['title','body']));auth()->user()->publishPost($post);returnredirect("posts");}直接使用关系模型创建一个帖子:/app/User.phppublicfunctionpublishPost(Post$post){$this->posts()->save($post);}然后创建评论:publicfunctionstore(Post$post){$this->validate(request(),['body'=>'required|min:5']);$post->addComment(newComment(['user_id'=>auth()->user()->id,'body'=>request('body'),]));returnback();}同样使用关系模型:/app/Post。phppublicfunctionaddComment(Comment$comment){$this->comments()->save($comment);}最后更新一些视图:在文章列表中,绑定作者:/resources/views/posts/index。blade.php{{$post->created_at->toFormattedDateString()}}by{{$post->user->name}}

具体文章与评论显示时,也绑定作者:/resources/views/posts/show.blade.php{{$post->title}}{{$post->created_at->toFormattedDateString()}}作者:{{$post->user->name}}

{{$post->body}}

@foreach($post->commentsas$comment){{$comment->created_at->diffForHumans()}}{{$comment->body}}

来自{{$comment->user->name}}


@endforeachEloquent:修饰符|Laravel5.4文档Laravel的用户认证系统|Laravel5.4文档NavsBootstrap