LoginSignup
0
1

More than 1 year has passed since last update.

【Laravel】 show、edit等のルーティングを主キー(id)ではなくレコード(文字列)にするgetRouteKeyNameメソッド

Last updated at Posted at 2022-07-28

参考ページ

https://qiita.com/phper_sugiyama/items/bdeee931ae2b821af895
https://www.messiahworks.com/archives/24058

こちらの情報を元にshowedit等、通常は主キー(id)を指定するルーティングを、代わりに主キーの持つレコード(文字列)を使用する方法を備忘録として残しておきます。

やりたい事

ブログページで別ページのリンクhttp://localhost:8000/sampleをつけたい。
urlをaタグに直接入れればもちろん解決できますが、ルーティングを使用して行いたい。

show.blade.php
<a href="http://localhost:8000/sample">オススメ記事</a>
↓
<a href="{{ route('blog.show','sample')}}">オススメ記事</a>

開発環境

Windows 10
XAMMP
PHP 7.4.29
Laravel Framework 8.83.15

マイグレーション

ブログテーブルにタイトル、本文、urlの3つを定義します。urlは重複出来ないのでunique()を付ける。

create_blogs_table.php
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('title');
            $table->string('contents');
            $table->string('url')->unique();
        });
    }

モデル

ルーティングの際にidの代わりにurlを指定したいので、今回のポイントであるgetRouteKeyNameメソッドをモデル内で使用します。

Blog.php
class Blog extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'contents',
        'url',
    ];

    public function getRouteKeyName()
    {
        return 'url';
    }
}

コントローラー

BlogController.php
class BlogController extends Controller
{
    public function index()
    {
        $blogs = Blog::all();
        return view('blog.index', compact('blogs'));
    }

    public function show(Blog $blog)
    {
        return view('blog.show', compact('blog'));
    }
}

ルーティング

web.php
Route::Resource('blog', BlogController::class);

ビュー

モデル内でgetRouteKeyNameメソッドを使用してurlを定義したため$blog->urlで指定できる。

index.blade.php
    @foreach ($blogs as $blog)
    <p><a href="{{ route('blog.show',$blog->url)}}">{{ $blog->title }}</a></p>
    @endforeach

モデル内でgetRouteKeyNameメソッドを使用してurlを定義したため
{{ route('blog.show','指定url')}}で指定できる。

show.blade.php
   <p>{{ $blog->title }}</p>
   <p>{{ $blog->contents }}</p>
   <a href="{{ route('blog.show','sample')}}">オススメ記事</a>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1