Get data without appends and relations in Laravel from Eloquent

Viewed 20526

I have model Project which has some $appends and some relations like pages, brands, status etc.

And in $appends it has pages, and in Page model it has lot of other $appends. Now while I do Project::find($id) it retrieves project, it's pages and other models which belongs to Page. And I havn't done with, so for each page it fires lots of queries.

Without using

DB::table('projects')->where('id', $id)->get();

Is there any better approach to load only Project model, no relation, no appends, nothing via Eloquent ?

7 Answers

Unfortunately thats not how it works. If you want to remove the appends you could do so as follows:

$project = Project::find(1);
$project->setAppends([]);

return $project; //no values will be appended

However if those appends are doing database calls and you prefer not to you should rexamine whether or not it makes sense for the appends to be there. It's really a matter of whether you think it makes sense for the appends to always be included or not.

It was usefull for me:

$services = Service::all()->makeHidden(['appendField1', 'appendField2'])->toArray();
// YourModel.php

public static $withoutAppends = false;

public function scopeWithoutAppends($query)
{
    self::$withoutAppends = true;

    return $query;
}

protected function getArrayableAppends()
{
    if (self::$withoutAppends){
        return [];
    }

    return parent::getArrayableAppends();
}
$result = YourModel::withoutAppends()->all();

I had a problem with the append fields of the second model i was trying to access, it was going into an infinite loop. So in User Model;

Instead of

return $this->organisation->is_enabled;

using:

return $this->organisation->setAppends([])->is_enabled;

Solved the problem for me since setAppends([]) function is unappending the unnecessary relations

You can try this

User::where('user_id',$user_id)->get()->makeHidden(['full_name','start_end_date']);

In your case,

->makeHidden(['usages']) 

option can help you. To ignore other relations, YouModel::setEagerLoads([]) cab help you.

Remember that, you have to use makeHidden as Statically. For example,

ScientistModel::where('name','Aziz Sancar')->first()->makeHidden(['appendsName']);
Related