Home >PHP Framework >Laravel >How to exclude unwanted fields in Laravel model query
Laravel is a very popular PHP web development framework that provides powerful and flexible database operation functions. When using Laravel to query data, we often need to filter and return certain specified fields, but in some cases, we need to exclude certain fields so that they do not appear in the query results. This article explains how to exclude unwanted fields in Laravel model queries.
First, we can use the select()
method provided by Laravel to specify the fields of the query, for example:
$users = User::select('name', 'email')->get();
This will return a ## containing each user A collection of #name and
email fields. But what if we need to exclude some fields? The following are two ways:
select() method to specify all fields to be returned, and then use
except () method to exclude unnecessary fields. For example:
$users = User::select('id', 'name', 'email', 'password') ->get() ->map(function ($user) { return collect($user->toArray()) ->except(['password']) ->all(); });Here we first use the
select() method to specify all the fields to be returned, and then use the
get() method to execute the query. Then we use the
map() method to process the query results, convert each user's information into an associative array, and use the
except() method to exclude its password field .
$hidden attribute of the model to hide fields that do not need to be output. For example:
class User extends Model { protected $hidden = ['password']; }In this example, we set the
$hidden attribute of the user model to
['password'], so that when querying, Laravel will automatically Exclude password fields from results.
makeVisible() method to override the
$hidden attribute of the model when querying . For example:
$user = User::find(1); $user->makeVisible(['password']);This will cause the obtained
$user object to contain a password field.
The above is the detailed content of How to exclude unwanted fields in Laravel model query. For more information, please follow other related articles on the PHP Chinese website!