John Davidson

php - Laravel: Why is Eloquent displaying hidden fields?

0 comments
Message:


Simply prefixes a # to the field name


I am using Laravel Breeze, which by default sets the password and remember_token fields to hidden.


class User extends Authenticatable
{
use HasFactory, Notifiable;

protected $fillable = [
'username',
'email',
'password',
];

protected $hidden = [
'password',
'remember_token',
];

protected $casts = [
'email_verified_at' => 'datetime',
];
}

However if I fetch a User instance running User::inRandomerOrder()->first() inside Tinker I am still able to see these supposed hidden fields.


App\Models\User {#4440
id: 14,
username: "verdie10",
email: "[email protected]",
email_verified_at: "2021-08-31 11:19:47",
#password: "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi",
#remember_token: "F87k6RPxgi",
created_at: "2021-08-31 11:19:47",
updated_at: "2021-08-31 11:19:47",
},


My Answer:
Eloquent does not actually hide the fields from being retrieved from the database. The `$hidden` property in the model is used to hide certain fields when the model is converted to an array or JSON response.

If you want to prevent certain fields from being retrieved from the database altogether, you can use the `select` method to specify the fields you want to retrieve. For example, `User::select('id', 'username', 'email', 'email_verified_at')->inRandomOrder()->first()` will only retrieve the specified fields.

Alternatively, you can also use the `makeHidden` method to dynamically hide certain fields when retrieving the model. For example, `$user = User::inRandomOrder()->first()->makeHidden(['password', 'remember_token']);` will hide the `password` and `remember_token` fields when accessing the `$user` object.

Rate this post

5 of 5 based on 2650 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us