mercredi 30 août 2017

Convert eloquent query constraints to function in Laravel model (eager loading)

i want to convert this part:

'likes as is_liked' => function($query){
                        $query->where('user_id', auth()->user()->id);
                    }]);
                }

and this part :

'post' => function($query){
                return $query->withCount(['comments', 'likes', 'likes as is_liked' => function($query){
                    $query->where('user_id', auth()->user()->id);
                }]);
            }

of below query to function in Laravel model , but i dont know how can i do this; is there any way to add this constraints in Laravel model and summarize the code in controller action?

$bookmarks = auth()->user()->bookmarks()
            ->with(['post.user', 'post.categories', 'post' => function($query){
                return $query->withCount(['comments', 'likes', 'likes as is_liked' => function($query){
                    $query->where('user_id', auth()->user()->id);
                }]);
            }])
            ->paginate(10);

Laravel version : 5.4



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire