Home > Software design >  laravel two foreach in controller not working
laravel two foreach in controller not working

Time:07-09

my controller

  $albums =Album::where('verified',1)->get();;
        foreach($albums as $key => $album){
            $tracks = Track::whereIn('id',$album->track_id)->where('verified',1)->get();
            foreach($tracks as $key => $track){
                $singers =Singers::whereIn('id',$track->singers_id)->pluck('singers_name');
                dd($track->track_title);
                }
        }

Here $track get 2 data but second foreach dd($track->track_title) show only one data

CodePudding user response:

dd means dump and die, so it will just show first value and then exit the code.

use

Like below -

$albums =Album::where('verified',1)->get();;
        foreach($albums as $key => $album){


            $tracks = Track::whereIn('id',$album->track_id)->where('verified',1)->get();

            foreach($tracks as $key => $track){
                $singers =Singers::whereIn('id',$track->singers_id)->pluck('singers_name');
                print_R($track->track_title);
    
                }
die;
           

        }

CodePudding user response:

You are using wrong veribale to fetch Track: Follow the Step

 $albums =Album::where('verified',1)->get();
        foreach($albums as $album){
            $tracks = Track::whereIn('id',$album->track_id)->where('verified',1)->get();
            foreach($tracks as $track){
                $singers =Singers::whereIn('id',$track->singers_id)->pluck('singers_name');
                dd($track->track_title);
                }
        }
  • Related