Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel Closure Function is not working (with) relation

Hello Developers I hope you are all good.
I have had a problem for 2 or 3 days, and I can’t figure out how to solve this. The code is below here. but it always returns

Error: Method name must be a string in file /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 764

            $feeds = Feed::where("id",$request->feed_id)
                ->with("media","likes","customer",['comments'=>function($query){
                    foreach ($query as $comment){
                        return $comment->id;
                    }
                }])
                ->first();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use nested with() to get user name and picture.

$feed = Feed::where("id",$request->feed_id)
        ->with([
            "media",
            "likes",
            "customer",
            "comments"=> fn($query) => $query->with('user')
        ])
        ->first();


foreach ($feed->comments as $comment) {
    $user_name = $comment->user->name;
    $user_picture = $comment->user->picture;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading