· 1 min read · Laravel / APIs / security
Your Laravel API is probably exposing sensitive data
Returning Eloquent models straight from a controller sends every column over the network, password hashes included. Here's why, and what to return instead.
When building an API with Laravel, some developers do this: return response()->json(User::find($id));. It's a huge security risk. It looks harmless, because the frontend only shows the fields you care about, so nothing else is exposed, right? Actually, no.
That statement doesn't just send the data you want to show. It sends everything on that model in the network response, and anyone who opens the network tab can read all of it. That's dangerous, especially when some of it is personal data.
An example
Say you're building a social media app and you want to list accounts. If you do it like this: return response()->json(Account::all()); you're passing every detail of those accounts through the request: password hashes, names, addresses, emails and more.
Fixing it
One option is the $hidden property on the model. The trade-off is that those attributes are hidden in every serialized context, including the ones where you actually need them, so it isn't the best solution.
Another option is to map the data to exactly what you want before returning it:
$users = User::all()->map(function ($user) {
return [
'name' => $user->name,
'user_name' => $user->user_name,
];
});That's much safer. There are more alternatives too, such as API Resources and the pluck method.
In summary: when building a system, make sure you're not leaking data by returning models as-is. Only return the data that's safe to show publicly.
— Omar. Questions or corrections? Tell me.