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に導入するのね。
うむ、これはテストしないとあかんやつやね。

php7.0とphp7.1の違い

1. 型宣言

function type_defined(int $argument) : string {
	return 'Hello';
}

あまり見ない気がしますが。。

$name_list = [
	'luna',
	'sunny',
	'star',
];

function type_defined(int $name_id) : string {
	return isset($name_list[$name_id]) ? $name_list[$name_id] : null; 
}

var_dump(get_name(4));

barryvdh/laravel-debugbar

debuggerはlaravel開発に役立つらしい

ただし、パスワードも丸見えになるらしい。
[vagrant@localhost tea]$ php composer.phar require barryvdh/laravel-debugbar
Using version ^3.2 for barryvdh/laravel-debugbar
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
– Installing maximebf/debugbar (v1.15.0): Downloading (100%) – Installing barryvdh/laravel-debugbar (v3.2.4): Downloading (100%)
maximebf/debugbar suggests installing kriswallsmith/assetic (The best way to manage assets)
maximebf/debugbar suggests installing predis/predis (Redis storage)
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover –ansi
Discovered Package: barryvdh/laravel-debugbar
Discovered Package: barryvdh/laravel-dompdf
Discovered Package: beyondcode/laravel-dump-server
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.