0

Does it have to be the 'id' column in database table which works fine for show($id), edit($id) method in controller?
I want to replace $id with the value of 'post_id' column in database table, but it throws error: ModelNotFoundException
How can I fix it?

sample code:

database table:

id(int), post_id(varchar32), post_title(varchar32), post_content(text)

routes:

Route::resource('posts', 'PostsController');

PostsController:

public function show($id) { return View::make('posts.show'); }

When I visit http://localhost/posts/1 it should return the view of post which has id 1 in the table.
What if I what to return the view based on post_id value in the table?
Does it have to replace the parameter in show() or ?

JackpotK
  • 313
  • 1
  • 8
  • 18
  • can you please add relevant code ? – Chris May 19 '13 at 13:28
  • sure, added as above. – JackpotK May 19 '13 at 13:36
  • 3
    You're not really using the $id, you're just rendering the view in show method. And yes, you can pass whatever you need, your links just have to be in conformity with the resource: route.show must be `http://host/route_name/id-or-anything-else`. But if you are getting ModelNotFoundException is because FindOrFail or FirstOrFail is being used somewhere else in your code. I don't see them being used in Laravel source code, they must be yours. – Antonio Carlos Ribeiro May 19 '13 at 16:13
  • Thank you!It turns out that the FindOrFail($id) will look for the primary key in table.In my case, I can solve the problem either by setting post_id as primary key or use where () to retrieve the post. Can you please have a look at another problems related to nested controller? http://stackoverflow.com/questions/16633898/laravel-4-how-to-write-the-correct-nested-controller-for-nested-resource – JackpotK May 20 '13 at 01:11

2 Answers2

2

In your PostsController you need to access the Post model to get the data from the db.

like this: //PostsController

public function show($id) { 
$post = Post::where('post_id', $id)->first();

return View::make('posts.show', compact('post')); 
}
Dustin Fraker
  • 524
  • 1
  • 5
  • 9
  • Thanks!I also find it since laravel set id as the default primary column, i may also manually define post_id as the primary key in model, though not a best practice. – JackpotK May 21 '13 at 08:47
0

you can also use find

public function show($id) { 
$post = Post::find($id);
return View::make('posts.show', compact('post')); 
}
abhayendra
  • 197
  • 6