How to exclude certains columns while using eloquent
If you only need to hide attributes from your model's array or JSON representation, you may use one or both approaches:
- Add the
$hidden
property to your modelclass User extends Model
{
/**
* The attributes that should be hidden for arrays.
*/
protected $hidden = ['password'];
} - Use the
makeHidden
function$users = $users->makeHidden(['address', 'phone_number']);
See other answers for more details... But sometimes you don't want to load huge data (geospatial, html, logs...) into your application, it will be slow and take more memory. OP asked for an SQL query hence my answer, but most of the time it's more convenient to only hide the data from the JSON response.
AFAIK there is no build in option in SQL to exclude columns explicitly, so Laravel can't do it. But you can try this trick
Update
Another trick is to specify all columns in your model (or use an extra query to get all columns using $this->getTableColumns()
from this answer, it can also be cached after each migration to avoid two queries) then add a local scope function
// The below code requires you to define all columns in $columns.
// A better approach is to query the schema of the table and cache it after each
// migration, for more details: https://stackoverflow.com/a/56425794/3192276
protected $columns = ['id','pseudo','email'];
public function scopeExclude($query, $value = [])
{
return $query->select(array_diff($this->columns, (array) $value));
}
Then you can do :
$users = User::where('gender', 'M')
->where('is_active', 1)
->exclude(['pseudo', 'email', 'age', 'created_at'])
->toArray();
How to exclude certains columns while using eloquent | Laravel
One option you have is to exclude the Hotel's you don't want in your list at the query level:
Hotel::whereNotKey($group->hotels->modelKeys())->get();
How to exclude the relation column from the collection result array- eager loading
On the first try, every child will have category_id
, not the primary array.
collect($result)->map(function($item) {
return collect($item)->except('category_id');
})->toArray();
On the second one, you're using toArray()
in your main array so to unset category_id
you need to use the []
unset($i['category_id']);
PS: I see paginate()
it's the result of this the result of an endpoint? In that case, you can check out API Resource.
Laravel 5 Model: Do not include certain columns in Eloquent
You can use the $hidden
property on your Eloquent model:
class CmsUserInformation extends Model
{
protected $hidden = [
'id',
'users_id',
'created_at',
'updated_at',
];
}
This will automatically exclude the given attributes when the models are ultimately serialized.
If you only want to hide it in a specific instance, use the setHidden
method:
$info = CmsUserInformation::where('users_id', Auth::id())->first();
$info->setHidden([
'id',
'users_id',
'created_at',
'updated_at',
]);
Laravel Replicate Certain Columns to Another Table
If you know which fields you want to keep between the two models:
$fatherOrigin = \App\FatherRegistrars::where('id', $fatherID)->first();
$fieldsToKeep = [ 'name', 'email', ... etc ... ];
$father = new \App\User();
foreach($fieldsToKeep as $field) {
$father->$field = $fatherOrigin->$field;
}
If you know which field you want to discard:
$fatherOrigin = \App\FatherRegistrars::where('id', $fatherID)->first();
$fieldsToDiscard = [ 'birth', 'religion', ... etc ... ];
$originData = $fatherOrigin->toArray();
foreach($fieldsToDiscard as $field) {
unset($originData[$field]);
}
$father = \App\User::firstOrCreate($originData);
How to hide relationship columns in laravel?
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.
How can i return required columns from database through eloquent model in laravel
Try this:
$subcategoryContent = SubCategory::where('slug',$subcategory)->first()->Page()->pluck('title','id);
Related Topics
Reverse the Letters in Each Word of a String
Prevent Nginx 504 Gateway Timeout Using PHP Set_Time_Limit()
Asynchronous Function Call in PHP
Android JSON Httpclient to Send Data to PHP Server with Httpresponse
Php: Settings Memory_Limits > 1024M Does Not Work
How to Pass Variables as Stdin into Command Line from PHP
PHP on Windows with Xampp Running 100 Times Too Slow
Parse Error: Syntax Error, Unexpected '[', Expecting ')'
Hide Variable Product Dropdown That Has a Unique Variation Selected by Default in Woocommerce
MySQL - Access Denied for User
What Is an Abstract Class in PHP
Best Practice: Import MySQL File in PHP; Split Queries
Laravel 5 Class 'Form' Not Found
HTML Upload Max_File_Size Does Not Appear to Work
How to Delete Files from Directory Based on Creation Date in PHP