More Related Content Similar to わかってるフレームワーク Laravel (20) More from Masashi Shinbara (14) わかってるフレームワーク Laravel7. マイグレーションファイル
(c) 2014 Masashi Shinbara @shin1x1
public function up()
{
Schema::create('roles', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
});
}
• メソッド名が列の型
• 引数が列名
8. マイグレーションファイル
(c) 2014 Masashi Shinbara @shin1x1
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('email')->unique();
$table->string('password');
$table->integer('role_id')->index();
$table->foreign(‘role_id')
->references(‘id')->on('roles')
->onUpdate('cascade');
$table->timestamps();
});
}
• インデックス、ユニーク制約、外部キー も設定可能
9. マイグレーション実行
(c) 2014 Masashi Shinbara @shin1x1
• マイグレーション実行 [up()]
(過去に適用したファイルは適用されない)
$ php artisan migrate
• マイグレーションロールバック [down()]
(直前に実施したマイグレーションのdown()を実行)
$ php artisan migrate:rollback
13. データベースクエリ
(c) 2014 Masashi Shinbara @shin1x1
• クエリビルダ
DB::table('roles')->where('name', '=', ‘Mike')->get();
• Eloquent(ORM)
Role::whereName('Mike')->first();
14. データベースクエリ
(c) 2014 Masashi Shinbara @shin1x1
• WHERE
• IN
• AND / OR
• BETWEEN
• IS NULL
• OFFSET / LIMIT
• GROUP BY / HAVING
• JOIN / LEFT JOIN
• EXISTS
• COUNT()
• SUM()
• MAX() / MIN() / AVG()
•
•
豊富な表現力
15. クエリビルダとEloquent
(c) 2014 Masashi Shinbara @shin1x1
記法 レコード 複数レコード
クエリビルダ SQLライク stdclass array()
Eloquent ORM
自分自身
(ex. User クラス)
Illuminate
Database
Eloquent
Collection
実行できるクエリは、ほぼ同じ
16. データベースコレクション
(c) 2014 Masashi Shinbara @shin1x1
• 取得した値をカンマで連結
Role::all()->implode('name', ‘,');
// role1,role2,role3
• contains()
• each()
• filter()
• sortBy()
• map()
• sum()
• toArray() / toJson()
• and more…
18. バリデーション
(c) 2014 Masashi Shinbara @shin1x1
バリデーションルールの拡張が簡単
Validator::extend('fukuoka', function($attribute, $value, $parameters) {
return $value === 'Fukuoka';
});
$rules = [
'area' => 'fukuoka',
];
19. バリデーション
(c) 2014 Masashi Shinbara @shin1x1
条件が合致した時だけバリデートする
$validator = Validator::make(Input::all(), $rules);
$validator->sometimes('email_and_pass_unique', 'validate_rule', function($input) {
if ($input->has('email') || $input->has('pass')) {
return true;
}
return false;
});
21. Route::group
(c) 2014 Masashi Shinbara @shin1x1
クロージャの意図を入れ子で表現
=> 全てのルートで auth フィルタが有効
Route::group(['before' => 'auth'], function() {
Route::get('/home', function() {
// something
});
Route::get('/', function() {
// something
});
});
22. DB::transaction
(c) 2014 Masashi Shinbara @shin1x1
クロージャ内に正常処理
=> 自動で BEGIN
=> 例外が飛べば ROLLBACK
=> 正常終了なら COMMIT
DB::transaction(function() {
DB::table('users')->insert(['name' => 'user-name']);
DB::table('roles')->insert(['name' => 'role-name']);
});
26. Laravel
(c) 2014 Masashi Shinbara @shin1x1
こんなふうに考えてください。
アプリケーションは Laravel フレーム
ワークの実装ではありませ ん。
逆に、Laravel が私達のアプリケーショ
ンの実装なのです。
Implementing Laravel 日本語版