Laravel初学者です。
オリジナルアプリを作成しているのでその過程を記事にしています。
理解が曖昧なところも多いため、ご指摘等ありましたらご連絡いただければ幸いです。
今回は一覧表示の実装について備忘録のため記録として残します。
環境
| Version | |
|---|---|
| PHP | 7.4.14 |
| Laravel | 8.24.0 |
| mysql | 8.0.23 |
| docker | 20.10.2 |
| docker-compose | 1.27.4 |
ルーティング
Route::get('/', [GameController::class, 'index']);
私の場合は/(ルート)を一覧表示として実装したかったので上記のようなルーティングになります。
/(ルート)にアクセスがあった時にGameControllerのindexアクションが動きますという意味です。
モデル
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Game extends Model
{
use HasFactory;
protected $table = "games";
protected $fillable = [
"id",
"user_id",
"name",
"describe",
"play_time",
"players_minimum",
"players_max",
"image_path",
"updated_at",
"created_at",
];
public function user()
{
return $this->belongsTo(User::class);
}
}
こちらは今回の一覧表示機能にだけ必要というものではないですが。
$fillableで指定して保存を許可します。
$fillableについてはこちらの記事が分かりやすかったです。
ありがとうございます。
コントローラー
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Game;
use Illuminate\Support\Facades\Auth;
use Storage;
class GameController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
//下記がindexアクション
public function index()
{
$games = Game::all();
return view('game.index', compact('games'));
}
}
$gamesにGame::all();でGameモデルから全てのデータを取ってきて代入しています。全てとるので複数形の$gamesになってます。
プログラミング学び始めのとき、複数形なのか単数形なのか分からなかったんですよね。
allで全てとる=複数のデータ=つまり複数形なので普通に考えれば簡単ですよね。
その後return viewでindexのviewを返す動きになってます。
compact('games')と記述することでview側で$gamesという変数が使えます。
逆にcompact書かないとエラーになりますので注意です。
compactについてはこちらの記事が分かりやすかったです。
ありがとうございます。
ビュー
<section class="page-section bg-light" id="portfolio">
<div class="container">
<div class="text-center">
<h2 class="section-heading text-uppercase">新着ボードゲーム</h2>
<h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3>
</div>
<div class="row">
@foreach($games as $game)
@if($game->image_path)
<div class="col-lg-4 col-sm-6 mb-4">
<div class="portfolio-item" style="text-align:center">
<a class="portfolio-link" href="{{ route('game.show', $game->id) }}">
<img src="{{ $game->image_path }}" height="200" width="200">
</a>
<div class="portfolio-caption" style="margin-top:10px">
<div class="portfolio-caption-heading">{{ $game->name }}</div>
<div class="portfolio-caption-subheading text-muted">プレイ時間:{{ $game->play_time }}分</div>
<div class="portfolio-caption-subheading text-muted">人数:{{ $game->players_minimum }}~{{ $game->players_max }}人</div>
</div>
</div>
</div>
@endif
@endforeach
</div>
</div>
</section>
@foreach($games as $game)
//この中に処理を書く
@endforeach
上記のようにforeachで繰り返し処理をしています。
コントローラーがデータを$gamesに入れてviewに渡してくれているのでそれをforeachの中では$gameとして一つずつ取り出します。
つまり一つずつ呼び出すためには
{{ $game->name }}
上記のように$gameのnameというように記述します。
こちらで一覧表示の実装は完了です。