The setVisible and setHidden Eloquent methods in Laravel 9.x
Laravel gives you a lot of flexibility when it comes to working with Eloquent models. You can easily customize the way you want to work with your models.
For instance, you can use the hidden
property to specify which attributes should be hidden from the model’s JSON form.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = ['api_token'];
}
So, when you try to convert the model to an array or JSON, the api_token
attribute will be hidden.
$user = User::find(1);
return $user->toArray();
/*
[
"id" => 1,
"name" => "Amit Merchant",
"email" => "[email protected]",
]
*/
But, what if you want to hide some attributes from the model’s JSON form but don’t want to specify them in the hidden
property? Sure, you can use the makeHidden
and makeVisible
methods to hide the attributes you don’t want to show or make them visible. But, what if you want to be explicit about what should be visible and what should be hidden?
Laravel 9.x comes with two new methods in the Illuminate\Database\Eloquent\Model
class that can help you with this.
The setVisible
method
The setVisible
method allows you to specify which attributes should be visible in the model’s JSON form.
$user = User::find(1);
return $user->setVisible(['name', 'email'])->toArray();
/*
[
"name" => "Amit Merchant",
"email" => "
]
*/
Unlike the existing makeVisible
method, the setVisible
method will not make the specified attributes visible in the model’s JSON form. Instead, it will only show the specified attributes in the model’s JSON form. So, you’re sure shot that the attributes you don’t want to show will not be shown.
The setHidden
method
Similarly, the setHidden
method allows you to specify which attributes should be hidden in the model’s JSON form.
$user = User::find(1);
return $user->setHidden(['api_token'])->toArray();
/*
[
"id" => 1,
"name" => "Amit Merchant",
"email" => "[email protected]",
]
*/
Unlike the existing makeHidden
method, the setHidden
method will not hide the specified attributes in the model’s JSON form. Instead, it will only hide the specified attributes in the model’s JSON form. So, you’re sure shot that the attributes you don’t want to hide will not be hidden.
Conclusion
The setVisible
and setHidden
methods are very useful when you want to hide or show some attributes in the model’s JSON form explicitly but you don’t want to specify them in the hidden
property. Also, these method doesn’t leak the attributes you don’t want to show or hide which is their main USP.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.