Home > Software design >  Overriding routeKeyName to slug not working
Overriding routeKeyName to slug not working

Time:09-27

Here is my show method in my PostController and when I dd($slug) I get my slug from the database but when I try to search the post associated with that slug I get a 404 | Not Found. I've override my routeKeyName in my model but it seems like it'still fetching using id column since when I replace $slug with a hard coded id of 2 in this line $post = Post::findOrFail($slug); then I get the post from the database. I can't figure out what it is that I'm missing.

 public function show($slug)
    {
        //dd($slug);
        $post = Post::findOrFail($slug);
        return view('single-blog', compact('post'));
    }

My Model Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class Post extends Model
{
    use HasFactory;

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

CodePudding user response:

Even using a different database field, you're still using route model binding. From the docs:

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.

So your route variable and the field you pass to your controller method need to match, and you need to type hint it:

Route:

Route::get('/posts/{post}', [PostController::class, 'show']);

Controller:

public function show(Post $post) {
  • Related