laravelの機能「implicit binding」(暗黙のバインディング)についてお聞きしたいことがあります。
以下は、ルーティング部分の「web.php」です
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', 'PostsController@index'); // Route::get('/posts/{id}', 'PostsController@show'); Route::get('/posts/{post}', 'PostsController@show');
以下は、コントローラー部分のPostsController.phpです。
php
1<?php 2 3namespace App\Http\Controllers; 4 5use Illuminate\Http\Request; 6use App\Post; 7 8class PostsController extends Controller 9{ 10 public function index() { 11 // $posts = \App\Post::all(); 12 // $posts = Post::all(); 13 // $posts = Post::orderBy('created_at', 'desc')->get(); 14 $posts = Post::latest()->get(); 15 // $posts = []; 16 // dd($posts->toArray()); // dump die 17 // return view('posts.index', ['posts' => $posts]); 18 return view('posts.index')->with('posts', $posts); 19 } 20 21 // public function show($id) { 22 public function show(Post $post) { 23 // $post = Post::find($id); 24 // $post = Post::findOrFail($id); 25 return view('posts.show')->with('post', $post); 26 } 27}
以下は、ビュー部分の「index.blade.php」です
php
1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4 <meta charset="utf-8"> 5 <title>Blog Posts</title> 6 <link rel="stylesheet" href="/css/styles.css"> 7</head> 8<body> 9 <div class="container"> 10 <h1>Blog Posts</h1> 11 <ul> 12 {{-- 13 @foreach ($posts as $post) 14 <li><a href="">{{ $post->title }}</a></li> 15 @endforeach 16 --}} 17 @forelse ($posts as $post) 18 <!-- <li><a href="/posts/{{ $post->id }}">{{ $post->title }}</a></li> --> 19 <!-- <li><a href="{{ url('/posts', $post->id) }}">{{ $post->title }}</a></li> --> 20 <!-- <li><a href="{{ action('PostsController@show', $post->id) }}">{{ $post->title }}</a></li> --> 21 <li><a href="{{ action('PostsController@show', $post) }}">{{ $post->title }}</a></li> 22 @empty 23 <li>No posts yet</li> 24 @endforelse 25 </ul> 26 </div> 27</body> 28</html>
以下は、show.blade.phpです。
php
1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4 <meta charset="utf-8"> 5 <title>{{ $post->title }}</title> 6 <link rel="stylesheet" href="/css/styles.css"> 7</head> 8<body> 9 <div class="container"> 10 <h1>{{ $post->title }}</h1> 11 <p>{!! nl2br(e($post->body)) !!}</p> 12 </div> 13</body> 14</html>
index.blade.phpにアクセスした際の画像は、以下になります。
上記画像におきまして、「test 2」のリンクをクリックするとURL部分に「posts/4」と、数字が自動で不可されますが、これは、index.blade.phpの「<li><a href="{{ action('PostsController@show', $post) }}">{{ $post->title }}</a></li>」こちらの部分で、「$post」がid番号を自動で不可しているものといった解釈で正しいでしょうか?
$post->titleのように、「$post->id」と記載しなくても良いのは、何故でしょうか?
回答2件
あなたの回答
tips
プレビュー