pavlenko
pavlenko

Reputation: 665

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,

Upvotes: 19

Views: 44168

Answers (2)

errorinpersona
errorinpersona

Reputation: 410

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.

Upvotes: 6

James Flight
James Flight

Reputation: 1464

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

Geo_Postal_us::where('postal', $postal)->firstOrFail();

Upvotes: 79

Related Questions