Support the ongoing development of Laravel.io →
Security Requests Eloquent

I am building a back-end API with Laravel and need some help with a problem.

Example I grab all my Post's and Grab latest 10 Comments along with it.

Problem is the JSON contains the user_id and other fields in the comments data not needed or should be visible to anyone who views the json. But the id, user_id has to be used in the find for the association. How can data not needed for the view be removed after the find before its send to the front end? I do not want to expose user_id's, or any id's if it can be helped, especially if it not the users.

I know about the ->select(['fields', 'to', 'grab']) but the id, user_id what not needs to be there for the find so removing it there is not an option.

Thanks,

Dave

Last updated 3 years ago.
0

Not sure if I understand you correctly or not. But you don't have to have the query fields in the select statement in order to reference them. a raw DB pull would look like:

DB::Raw("SELECT fields,to,grab FROM posts WHERE user_id=1");

You can do the same thing with the helpers

$Posts = DB::table('posts')->select(['fields','to','grab'])->where('user_id',1)->get();
0

I know thats not a real query, I can get the data fine, but for example I can view a post, I get the posts data which also grabs the comments associated, and the comments belong to a User, so to display the name of the user who posted the comment I have to grab the user info. But looking at the JSON response You can clearly see the user_id and user info which I do not want. I need to use the id's in the find, but no need to return them to the view / response. So I want to remove them after the query grabs the data, if you do not include id, user_id you do not get the associated data.

$Posts = DB::table('posts')->select(['fields','to','grab'])->where('user_id',1)->get(); will display the user id.

If a post has 50 comments the JSON will return 50 user.id's in the find, not what I want, I do not want to expose any primary id's of any kind, any record in the responses.

0

I'm not positive if this works on the DB controller, but after doing your query try something like this maybe

$Posts = DB::table('posts')->select(['fields','to','grab'])->where('user_id',1)->get();

$FilteredPosts = Posts::only(['fields','you','want']);

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.