Laravel 5.4入門シリーズ9.登録とログイン、ユーザーの関連付け

11029 ワード

このセクションでは、記事、コメントをユーザーに関連付ける機能について説明します.
関係の定義
まず、postscommentsのテーブルを変更し、user_idフィールドを追加します.
/database/migrations/2017_04_12_124622_create_posts_table.php
/database/migrations/2017_04_15_062905_create_comments_table.php
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
         
           //   
        $table->integer('user_id')->unsigned();
     
        $table->foreign('user_id')
              ->references('id')
              ->on('users')
              ->onDelete('cascade');
    });
}

すべてロールバックして移行を再実行するには、次の手順に従います.
$ php artisan migrate:refresh

ユーザー・テーブルと記事テーブル、コメント・テーブルの一対の複数の関係を追加します.
/app/User.php
public function posts()
{
    return $this->hasMany(\App\Post::class);
}

public function comments()
{
    return $this->hasMany(\App\Comment::class);
}

記事、コメント・テーブルとユーザー・テーブルの複数対1の関係を追加します.
/app/Comment.php
/app/Post.php
public function user()
{
    return $this->belongsTo(\App\User::class);
}

同時に、コメントテーブルの$fillableフィールドはuser_id増加した.
登録
まず、登録関連業務を処理するコントローラを定義します.
$ php artisan make:controller RegistrationController

ルーティング応答登録要求を定義するには、次の手順に従います.
Route::get('/register','RegistrationController@create');

メソッドを定義して、登録ページビューに戻ります.
public function create()
{
    return view('registration.create');
}

登録ページの作成:
/resources/views/registration/create.blade.php
@extends('layouts.master')

@section('content')
    
    
{{ csrf_field() }}
@endsection

ルーティング応答登録コミットの定義:
Route::post('/register','RegistrationController@store');

メソッドを定義して登録コミットを処理します.
/app/Http/Controllers/RegistrationController.php
use App\User;
public function store()
{    
    $this->validate(request(),[
        'name' => 'required',
        'email' => 'required|email',
        'password' => 'required|confirmed',
    ]);

    $user = User::create(request(['name','password','email']));

    auth()->login($user);

    return redirect()->home();
}

この方法は4つの部分を含む.
  • 検証フィールド.passwordconfirmed検証ルールを使用しており、xxxxxx_confirmationが一致しているかどうかを自動的に一致させるため、以前のビューは仕様に従って名前を付けます.
  • ユーザー
  • を作成
  • 当該ユーザ
  • にログインする.
  • 「home」という名前のルーティング
  • を返す
    ここでは、4番目のステップに一致するようにルーティングに名前を付ける必要があります.
    Route::get('/posts','PostsController@index')->name('home');

    登録機能は完了しましたが、パスワードが使用されている明文を保存し、パスワードを保存するたびに自動的に暗号化するモディファイヤを定義できます.
    /app/User.php
    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }

    ログイン
    コントローラを作成し、ユーザー登録業務を処理します.
    $ php artisan make:controller SessionsController

    ユーザが/loginにアクセスすると、ルーティングは要求を配信する.
    Route::get('/login','SessionsController@create');
    createメソッドは、ユーザーログインページビューに戻ります.
    /resources/views/sessions/create.blade.php
    @extends('layouts.master')
    
    @section('content')
        
        
    {{ csrf_field() }}
    @endsection

    ユーザーがログインをクリックすると、ルーティングによって要求が配布されます.
    Route::post('/login','SessionsController@store');

    最後に、コントローラがログイン動作を処理します.
    /app/Http/Controllers/SessionsController.php
    public function store()
    {    
    
        if (!auth()->attempt(request(['email', 'password']))) {
            return back()->withErrors([
                'messages' => '          !'
            ]);
        }
    
        return redirect()->home();
    } 
    Authクラスが提供するattempt()を使用して検証を行い、emailpasswordに転送するだけでよい.attemptメソッドはパスワードを暗号化してデータベースと比較し、一致すれば認証されたセッションをユーザーに開く.また、返されるエラー情報もカスタマイズしました.
    ログアウト
    登録の実装は比較的簡単で、まずルーティングです.
    Route::get('/logout','SessionsController@destroy');

    コントローラ:
    public function destroy()
    {
        auth()->logout();
    
        return redirect()->home();
    }

    最後に、ユーザーのログイン情報に基づいて異なる設定項目を表示するようにナビゲーションを最適化します.
    
    
    
        $('.dropdown-toggle').dropdown()
    

    ドロップダウン・ボックスを有効にするには、関連するjsを導入する必要があります.
    
    

    アクセス
    ログインとログイン を し,ユーザの を できるようになった.
    まず の であり、「ログインしていない」ユーザーに しては しか めないため、Laravelが するミドルウェアを して することができる.
    /app/Http/Controllers/PostsController.php
    public function __construct()
    {
        $this->middleware('auth')->except(['index','show']);
    }
    indexおよびshowを いて、 されたユーザのみが のリクエストにアクセスできることを する.
    に、ユーザーの を います.
    /app/Http/Controllers/SessionsController.php
    public function __construct()
    {
        $this->middleware('guest')->except(['destroy']);
    }

    だけが のリクエストにアクセスできるという で、destroyを く.
    と の を する
    に、 と の を させ、ユーザーidをバインドする.まず、 の :
    /app/Http/Controllers/PostsController.php
    public function store(Request $request)
    {
        $this->validate(request(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required|min:5',
        ]);
    
        $post = new Post(request(['title', 'body']));
    
        auth()->user()->publishPost($post);
    
        return redirect("posts");
    }

    を するには、リレーショナルモデルを します.
    /app/User.php
    public function publishPost(Post $post)
    {
        $this->posts()->save($post);
    }

    に、コメントを します.
    public function store(Post $post)
    {    
        $this->validate(request(),[
            'body' => 'required|min:5'
            ]);
    
        $post->addComment(new Comment([
            'user_id' => auth()->user()->id,
            'body'       => request('body'),
    
            ]));
        return back();
    }

    リレーションシップモデルも します.
    /app/Post.php
    public function addComment(Comment $comment)
    {    
        $this->comments()->save($comment);
    }

    に、いくつかのビューの です.
    リストで、 をバインドします.
    /resources/views/posts/index.blade.php
     

    な とコメントが された 、 もバインドされます.
    /resources/views/posts/show.blade.php
    

    {{ $post->title }}

    {{$post->body}}

    @foreach ($post->comments as $comment)
    {{$comment->created_at->diffForHumans() }}

    {{ $comment->body }}

    by {{$comment->user->name }}


    @endforeach
  • Eloquent:モディファイヤ|Laravel 5.4 ドキュメント
  • Laravelのユーザー システム|Laravel 5.4 ドキュメント
  • Navs · Bootstrap