Laravel : gitリポジトリからローカル環境でのプロジェクト複製の流れ

———————
$ git clone https://github.com/***/***.git
$ cd ***
$ git branch ${issue}
$ git checkout ${issue}
// vendorの作成
$ php composer.phar install
// .envファイルの作成 ※.env.exampleの複製ではなく、必要に応じてMAIL_DRIVER、AWS_ACCESS_KEY、PUSHER_APP_IDなどを記述する
.env
$ php artisan key:generate
// mysql
mysql> create database ***_dev
mysql> use ***_dev

$ php artisan migrate
// テーブルの初期値入力

$ php composer.phar dump-autoload
$ php artisan storage:link
———————

– .env作成のところは、DATABASEだけでなく、MAIL_DRIVER、AWS_ACCESS_KEY、PUSHER_APP_IDを自分用のアカウントで作らないといけないので、丁寧にドキュメントを作成する必要がありそう。
– シンボリックリンクは、git push, git cloneでは設定が反映されないので、改めて設定する必要がある。

php artisan一覧

$ php artisan
Laravel Framework version 5.2.45

Usage:
command [options] [arguments]

Options:
-h, –help Display this help message
-q, –quiet Do not output any message
-V, –version Display this application version
–ansi Force ANSI output
–no-ansi Disable ANSI output
-n, –no-interaction Do not ask any interactive question
–env[=ENV] The environment the command should run under.
-v|vv|vvv, –verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
clear-compiled Remove the compiled class file
down Put the application into maintenance mode
env Display the current framework environment
help Displays help for a command list Lists commands
migrate Run the database migrations
optimize Optimize the framework for better performance
serve Serve the application on the PHP development server
tinker Interact with your application
up Bring the application out of maintenance mode
app
app:name Set the application namespace
auth
auth:clear-resets Flush expired password reset tokens
cache
cache:clear Flush the application cache
cache:table Create a migration for the cache database table
config
config:cache Create a cache file for faster configuration loading
config:clear Remove the configuration cache file
db
db:seed Seed the database with records
event
event:generate Generate the missing events and listeners based on registration
key
key:generate Set the application key
make
make:auth Scaffold basic login and registration views and routes
make:console Create a new Artisan command
make:controller Create a new controller class
make:event Create a new event class
make:job Create a new job class
make:listener Create a new event listener class
make:middleware Create a new middleware class
make:migration Create a new migration file
make:model Create a new Eloquent model class
make:policy Create a new policy class
make:provider Create a new service provider class
make:request Create a new form request class
make:seeder Create a new seeder class
make:test Create a new test class
migrate
migrate:install Create the migration repository
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
migrate:rollback Rollback the last database migration
migrate:status Show the status of each migration
queue
queue:failed List all of the failed queue jobs
queue:failed-table Create a migration for the failed queue jobs database table
queue:flush Flush all of the failed queue jobs
queue:forget Delete a failed queue job
queue:listen Listen to a given queue
queue:restart Restart queue worker daemons after their current job
queue:retry Retry a failed queue job
queue:table Create a migration for the queue jobs database table
queue:work Process the next job on a queue
route
route:cache Create a route cache file for faster route registration
route:clear Remove the route cache file
route:list List all registered routes
schedule
schedule:run Run the scheduled commands
session
session:table Create a migration for the session database table
vendor
vendor:publish Publish any publishable assets from vendor packages
view
view:clear Clear all compiled view files

make, migrate以外にもたくさんありますね。

Laravelでseederを使おう

まず、seeder fileを作ります。

[vagrant@localhost test]$ php artisan make:seeder SmartTableSeeder
Seeder created successfully.

すると、database/seeds配下に SmartTableSeeder.php が出来る。

runメソッドでデータ挿入

use Illuminate\Database\Seeder;

class SmartTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $ministers = ['taro', 'masatoshi', 'takashi','masahiko','takumi'];
        foreach ($ministers as $minister) {
        	DB::table('minister')->('minister')
        }
    }
}

あれ、DB::table(‘minister’)->(‘minister’) って、なんかおかしいぞ。
で、シーダーファイルは、DatabaseSeeder.phpから呼び出す。

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
        $this->call('SmartTableSeeder::class');
    }
}

seeder 実行
[vagrant@localhost test]$ php artisan db:seed
Seeding: SmartTableSeeder::class

In Container.php line 729:

Class SmartTableSeeder::class does not exist

ん?
[vagrant@localhost test]$ php composer.phar dump-autoload
Generating optimized autoload filesCarbon 1 is deprecated, see how to migrate to Carbon 2.
https://carbon.nesbot.com/docs/#api-carbon-2
You can run ‘./vendor/bin/upgrade-carbon’ to get help in updating carbon and other frameworks and libraries that depend on it.
Generated optimized autoload files containing 3116 classes
[vagrant@localhost test]$ php artisan db:seed
Seeding: SmartTableSeeder::class

In Container.php line 729:

Class SmartTableSeeder::class does not exist

あれええええええー

あ、こうか

use Illuminate\Database\Seeder;


class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
        $this->call(
        	SmartTableSeeder::class
        );
    }
}

[vagrant@localhost test]$ php artisan db:seed
Seeding: SmartTableSeeder

In Connection.php line 647:

SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘test.minister’ d
oesn’t exist (SQL: insert into `minister` (`age`, `name`) values (54, taro)
, (54, taro))

In Connection.php line 445:

SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘test.minister’ d
oesn’t exist

うん、seederが複数あるときと、一つの場合だと書き方が異なりますね。
migrationしてないので、カラムが無いと表示されていますが、seederについてはわかりました。

userの論理削除

論理削除用のカラムを追加します
[vagrant@localhost test]$ php artisan make:migration add_column_softDeletes_users_table –table=users
Created Migration: 2019_08_20_001651_add_column_softDeletes_users_table

migrationsにも追加されていますね。

laravel migrate:refreshとmigrate:resetの違い

migrate:refresh と migrate:reset 何が違うんや?
migrationを再実行の場合はrefreshでいいのかな?

[vagrant@localhost test]$ php artisan migrate:refresh
Nothing to rollback.

In Connection.php line 647:
                                                                                                                                   
  SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists (SQL: create table `users` (`id` int unsi  
  gned not null auto_increment primary key, `name` varchar(255) not null, `email` varchar(255) not null, `password` varchar(255)   
  not null, `remember_token` varchar(100) null, `created_at` timestamp null, `updated_at` timestamp null) default character set u  
  tf8 collate utf8_unicode_ci)                                                                                                     
                                                                                                                                   

In Connection.php line 449:
                                                                                         
  SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists

already existってエラーが出てる。resetでやってみると、

[vagrant@localhost test]$ php artisan migrate:reset
Nothing to rollback.                                                                                      

mysql> use test;
Database changed
mysql> show tables;
+—————-+
| Tables_in_test |
+—————-+
| migrations |
| users |
+—————-+
2 rows in set (0.00 sec)

あれ、うまくいってない??
mysql> drop table migrations;
Query OK, 0 rows affected (0.01 sec)

mysql> drop table users;
Query OK, 0 rows affected (0.00 sec)

[vagrant@localhost test]$ php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table

mysql> show tables;
+—————–+
| Tables_in_test |
+—————–+
| migrations |
| password_resets |
| users |
+—————–+
3 rows in set (0.00 sec)

いまいち理解できてないです。

公式では、、
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
resethはrollbackで、refreshはre-runですな。

register controller

ユーザー情報はここで編集する

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }

Laravelの認証をカスタマイズする

/app/Http/Controllers/Auth/LoginController.php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function username()
    {
        return 'email';
    }
}

usernameメソッドを変更する

public function username()
    {
        return 'username';
    }

ほう、そういうことか。

laravelでlogin後のリダイレクト先を変更

App/Http/Middleware/RedirectAuthenticated.phpを編集します。

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            // return redirect('/home');
            return redirect('/top');
        }

        return $next($request);
    }
}

TopController.phpをつくります。

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TopController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('top');
    }
}

上手くいくようになりました。

mailgun

Transactional Email API Service for Developersと書いてある。
APIベースのメール配信サービスとのこと。
Mailgunでは、毎月10,000通までのメール送信が無料で使えるとのこと。
Google Cloud PlatformのCompute Engineのサードパーティメールサービスとしても提供。

DNSを設定して、Laravelに導入するのね。
うむ、これはテストしないとあかんやつやね。