Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findOrFail Laravel 5 function for specific field

This is my code:

$get_all = Geo_Postal_us::findOrFail($postal);

With this query, Laravel tries to find the id field in the table.

I don't have an id field. I use the postal column as primary key.

How do you set the function to find value in postal column and not search from id column?

Thanks,

like image 576
pavlenko Avatar asked Jun 17 '15 10:06

pavlenko


2 Answers

You could create the behaviour you are looking for with the following:

Geo_Postal_us::where('postal', $postal)->firstOrFail();
like image 142
James Flight Avatar answered Nov 04 '22 07:11

James Flight


Laravel by default is searching for the "id" column inside the table if you are using find(). To avoid running into errors here and maybe later, you should always tell laravel that you did take another name for your primary field.

To do that, in your Geo_Postal_us just edit as the following:

class Geo_Postal_us extends Model
{
      protected $primaryKey = 'postal'; //tell laravel to use 'postal' as primary key field
...
...

I ran into this issue within Voyager and it really drove me nuts :).

Hope this helps some people as they google the issue.

like image 6
errorinpersona Avatar answered Nov 04 '22 06:11

errorinpersona