PHPバージョン:7.1.14
Laravelバージョン:5.7.9
今回はLaravelのEloquent、where検索についてです!
以前作成したResourceControllerに追加する形で
実装していきます!
下準備
実際にwhere検索を使う前に下準備をします!
ちなみに現在のArticleモデルをMySQLで確認すると、
mysql> show columns from articles; +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | title | varchar(255) | NO | | NULL | | | body | varchar(255) | NO | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +------------+------------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec)
このような状態です。
Migrationを使って、
category:カテゴリー
good:いいね数
を追加していきます。
$ php artisan make:migration add_columns_articles_table
Migrationファイルを作成し、
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddColumnsArticlesTable extends Migration { public function up() { Schema::table('articles', function(Blueprint $table) { $table->string('category'); $table->integer('good'); }); } public function down() { Schema::table('articles', function(Blueprint $table) { $table->dropColumn('category'); $table->dropColumn('good'); }); } }
database>migrations>xxxx_xx_xx_xxxxxx_add_columns_articles_table.php
categoryとlikeカラムを追加しました。
Migrationを実行します。
$ php artisan migrate
Migrationを実行し、MySQLにカラムが追加されました。
MySQLのtruncateで既に登録されているデータを全件削除します。
mysql> truncate table articles; Query OK, 0 rows affected (0.00 sec)
ちなみにEloquentにもtruncateメソッドは用意されており、
テーブルのデータを全件削除することができます。
Article::truncate();
続いてDBの初期値を設定するArticlesSeederを編集します。
<?php use Illuminate\Database\Seeder; class ArticlesSeeder extends Seeder { public function run() { $param = [ 'title' => '【Unity】GetComponentの使い方', 'body' => '今回は GetComponentの使い方についてです!', 'category' => 'Unity', 'good' => 20, ]; DB::table('articles')->insert($param); $param = [ 'title' => '【Laravel】 Controllerの使い方', 'body' => '今回はコントローラーの使い方についてです!', 'category' => 'Laravel', 'good' => 15, ]; DB::table('articles')->insert($param); $param = [ 'title' => '【日記】8月1日', 'body' => 'きょうはなんにもないすばらしい一日だった', 'category' => '日記', 'good' => 12, ]; DB::table('articles')->insert($param); $param = [ 'title' => '【日記】8月2日', 'body' => 'きょうはなんにもないすばらしい一日だった', 'category' => '日記', 'good' => 5, ]; DB::table('articles')->insert($param); $param = [ 'title' => '【日記】8月3日', 'body' => 'きょうはなんにもないすばらしい一日だった', 'category' => '日記', 'good' => 0, ]; DB::table('articles')->insert($param); } }
database>seeds>ArticlesSeeder.php
database>seeds>DatabaseSeeder.phpにArticlesSeederは既に登録されているので、
Seedingを実行していきます。
ArticlesSeederのみを指定して実行します。
$ php artisan db:seed --class=ArticlesSeeder
以上で下準備は完了です。
where検索を実践
まずはResourceController機能で作成した
ResControllerにsearchメソッドを追加します。
<?php namespace App\Http\Controllers; use App\Models\Article; use Illuminate\Http\Request; class ResController extends Controller { public function index() { // 〜省略〜 } public function create() { // 〜省略〜 } public function store(Request $request) { // 〜省略〜 } public function show(Article $article) { // 〜省略〜 } public function edit(Article $article) { // 〜省略〜 } public function update(Request $request, Article $article) { // 〜省略〜 } public function destroy(Article $article) { // 〜省略〜 } // ***** 開始 ***** public function search(Request $request) { $articles = Article::where('category', $request->category)-> get(); return view('res.index', ['articles' => $articles]) ; } // ***** 終了 ***** }
app>Http>Controllers>ResController.php
searchメソッド一行目にあるArticle::where()で検索が行われます。
第一引数にカラム名(今回は'category')、
第二引数に$requestで受け取ったcategory変数を指定しています。
where句で取得されるのはBuilder型と呼ばれ、そのままでは使えません。
getメソッドをチェーンしCollection型で取得します。
検索結果の$articlesを引数に指定し、
index.blade.phpのビューを表示します。
** Routeの設定
最後にRouteを設定します。
routes>web.phpを編集します。
<?php Route::get('articles/search', 'ResController@search'); Route::resource('articles', 'ResController');
routes>web.php
ResourceControllerのルートの上に、
articles/searchへアクセスした時に
ResControllerのsearchメソッドを実行するルートを記述しました。
※※ 注意 ※※
ResourceControllerで使用したコントローラーにメソッドを追加する時は、
必ずResourceControllerのルートの上に記述しましょう。
ResourceControllerのルートの下に記述すると404エラーとなります。
結果
まずは
http://localhost:8000/articles
へアクセスし、記事一覧を表示するindexページを確認します。
次に
http://localhost:8000/articles/search?category=日記
へアクセスし、日記カテゴリーの記事一覧を表示します。
where検索により、無事日記カテゴリーの記事のみ表示されました!
今回はここまでです、ありがとうございました〜!