Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide relationship columns in laravel?

I have a statement like this:

App\User::with('client')->find(2)->makeHidden('client.phone_no');

I want to hide certain columns from a relation, but I can't do that with makeHidden(), because it only takes the arguments for the Model not the relation.

How can I hide some columns from the relation?

like image 769
Tanmay Avatar asked Aug 14 '18 13:08

Tanmay


2 Answers

If you don't want to hide the phone_no for all the requests by adding it to the hidden property, you could do something like this:

$user = App\User::with('client')->find(2);
$user->client->makeHidden('phone_no');
return $user;

As I stated in my comment to the original question: I found this method as well. I believe this should be the method you should use when you want to exclude columns more often. If you only want to exclude a column once, my solution should be sufficient.

like image 129
Douwe de Haan Avatar answered Oct 12 '22 17:10

Douwe de Haan


You can either hide the column in the query result (eager loading is unnecessary):

$user = User::find(2);
$user->client->makeHidden('phone_no');

Or you don't even get it from the database:

$user = User::with('client:id,user_id,...' /* other columns except phone_no */)->find(2);
like image 23
Jonas Staudenmeir Avatar answered Oct 12 '22 16:10

Jonas Staudenmeir