Question:
Laravel Query Solved: Laravel withOnly not restricting the query

Solution:

You start it by creating a scope inside your Notification. The following code will help you understand. 


class Notifications extends Model

{


    public function scopeWithUser($query, $relations = [])

    {

        return $query->with(['fromuser' => fn($query) => 

            empty($relations)

                ? $query->setEagerLoads([])

                : $query->withOnly($relations)

        ]);

    }

}


After this write the following code:

Notifications::withUser()->get()


Or if you have other relation to eager:

Notifications::withUser()->with('relation1')->get()


So it's up to you how to organize an modify the code to suit your needs


Update:

The $with always depends on model columns. Therefore, if you are not selecting for exmaple subscription_id and photo_file_id, automatic relation loading will not work.


Would you give it a try

Notifications::with('fromuser:id,name,email')->get()


Suggested blogs:

>Creating API in Python using Flask

>CRUD Operation on Angular

>CRUD Operations In ASP.NET Core Using Entity Framework Core Code First with Angularjs


Ritu Singh

Ritu Singh

Submit
0 Answers