YuHo のブログ

Laravel, PHP, JavaScript

Laravel 5.6 でブログサイトを制作する2 #2 Userモデルの追加

User Model を追加する

php artisan make:auth
php artisan migrate

Route を作成する

[blog/routes/web.php]

<?php

Route::resource('users', 'UserController', ['only' => [
    'index', 'show', 'edit', 'update', 'destroy'
]]);
|<
*Authorization を準備する
**Gate を作成する
>|php|
[blog/app/Providers/AuthServiceProvider.php]

<?php

public function boot()
{
    $this->registerPolicies();

    Gate::resource('users', 'UserPolicy');
}

UserPolicy を作成する

php artisan make:policy UserPolicy --model=User

UserPolicy を User Model に紐付ける

[blog/app/Providers/AuthServiceProvider.php]

<?php

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    'App\User' => 'App\Policies\UserPolicy',
];

UserPolicy を編集する

[blog/app/Policies/UserPolicy.php]

<?php

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function view(User $user, User $model)
    {
        //
    }

    /**
     * Determine whether the user can create models.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        //
    }

    /**
     * Determine whether the user can update the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function update(User $user, User $model)
    {
        return $user->id === $model->id;
    }

    /**
     * Determine whether the user can delete the model.
     *
     * @param  \App\User  $user
     * @param  \App\User  $model
     * @return mixed
     */
    public function delete(User $user, User $model)
    {
        return $user->id === $model->id;
    }
}

UserController の作成

作成

php artisan make:controller UserController --resource --model=User

編集

[app/Http/Controllers/UserController.php]

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::paginate(10);
        
        return view('users.index', ['users' => $users]);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {
        return view('users.show', ['user' => $user]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user)
    {
        if (Auth::check()) {
            $authed = Auth::user();
            if ($authed->can('users.update', $user)) {
                return view('edit', ['user' => $user]);
            }
        }
        
        return redirect('/');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, User $user)
    {
        if (Auth::check()) {
            $authed = Auth::user();
            if ($authed->can('update', $user)) {
                
                
                
                return redirect('/');
            }
        }

        return redirect('/');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        if (Auth::check()) {
            $authed = Auth::user();
            if ($authed->can('delete', $user)) {
                
                
                
                
                return redirect('/');
            }
        }

        return redirect('/');
    }
}

Blade を作成する

[blog/resources/views/users/index.blade.php]

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">User Index</div>

                <div class="card-body">
                    @foreach($users as $user)
                        <div><a href="{{ route('users.show', ['id' => $user->id])}}">{{ $user->name }}</a></div>
                    @endforeach
                </div>
                
            </div>
        </div>
    </div>
</div>
@endsection
[blog/resources/views/users/show.blade.php]

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">User Show</div>

                <div class="card-body">
                    {{ $user->name }}
                </div>
                
            </div>
        </div>
    </div>
</div>
@endsection
[blog/resources/views/users/edit.blade.php]
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">User Edit</div>

                <div class="card-body">
                    <form action="/users/{{ $user->id }}" method="POST">
                        @csrf
                        @method('PUT')
                        <input value="{{ $user->name }}" name="name">
                        <button>Update</button>
                    </form>
                </div>
                
            </div>
        </div>
    </div>
</div>
@endsection

Seed を作成する

作成

php artisan make:seeder UsersTableSeeder

DatabaseSeeder.php の編集

[blog/database/seeds/DatabaseSeeder.php]

<?php

public function run()
{
    $this->call([
        UsersTableSeeder::class,
    ]);
}

UsersTableSeeder.php の編集

[blog/database/seeds/UsersTableSeeder.php]

<?php

public function run()
{
    factory(App\User::class, 30)->create();
}

Seeder を実行する

composer dump-autoload
php artisan db:seed

不足するリンクなどを補う

[blog/resources/views/welcome.blade.php]

@extends('layouts.app')

@section('content')
    <div>
        <div>
            Laravel
        </div>

        <div>
            <a href="https://laravel.com/docs">Documentation</a>
            <a href="https://laracasts.com">Laracasts</a>
            <a href="https://laravel-news.com">News</a>
            <a href="https://forge.laravel.com">Forge</a>
            <a href="https://github.com/laravel/laravel">GitHub</a>
        </div>
    </div>
@endsection
[blog/resources/views/layouts/app.blade.php]

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Raleway:300,400,600" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav mr-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        <!-- Authentication Links -->
                        @guest
                            <li><a class="nav-link" href="{{ route('enter') }}">Enter</a></li>
                            <li><a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a></li>
                            <li><a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a></li>
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }} <span class="caret"></span>
                                </a>

                                <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>
[blog/routes/web.php]

<?php

Route::get('enter', function() {
    $user = App\User::find(1);
    
    Auth::login($user, true);
    
    return redirect('/');
})->name('enter');