Laravel application is an interesting framework which makes it easy for developers to create any functionality with less coding. It uses the MVC (Model, View, Controller) Structure, where functions and backend operations occurs in the Controller, while the end results or display data comes up in the view blades. The view files are also called blade files. During application development, we might come up with errors in the blade files. Let’s discuss about a strange issue, I recently came across, where the $user->id show 0 in a Laravel blade file.
A user id that is fetched from database should always have positive, non-zero values. It is the auto-incremented field that should never be 0 or negative.
To avoid such errors, we will look into the Model from the MVC structure of our Laravel application. Firstly, you will set a custom primary key using the code below.
protected $primaryKey = 'id'; // user_id in this case
In cases you don’t have a primary key, you need to write the following code in your Model.
protected $primaryKey = null;
public $incrementing = false;
In addition, remove the $fillable array you have added in your model.
Laravel Eloquent assumes that each table has a primary key column named as id
. So, you should define a protected $primaryKey
property to override this convention.
In addition, it also assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int
data type automatically. To avoid this and errors like ‘$user->id show 0’ you should set the public $incrementing
property on your model to false
. Therefore, if your primary key is not of an integer type, you should also set the protected $keyType
property on your model as string
data type.