Home > Blockchain >  Laravel Closure Function is not working (with) relation
Laravel Closure Function is not working (with) relation

Time:10-12

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();

CodePudding user response:

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;
}
  • Related