findOrFail Laravel 5 function for specific field
33,677
Solution 1
You could create the behaviour you are looking for with the following:
Geo_Postal_us::where('postal', $postal)->firstOrFail();
Solution 2
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.
Comments
-
pavlenko over 3 years
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 thepostal
column as primary key.How do you set the function to find value in
postal
column and not search fromid
column?Thanks,
-
pavlenko almost 9 yearsThis slove problem,tnx! BUt now,when I tray to make upload,until there was id,working fine,bud now,again get error, that Laravel still try to find ID filed. this is code: $email_update = Geo_Postal_us::where('postal', $postal)->firstOrFail();
-
James Flight almost 9 yearsTo use a different column as the primary key, add the following property to the Geo_Postal_us model
protected $primaryKey = 'postal';