laravel : i am trying to get 2 relationships methods in 1 query

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


laravel : i am trying to get 2 relationships methods in 1 query



what i am trying to do is getting my tvserious and movies from categories class



this is my categories class :


class Category extends Model
{

public function movies()
{
return $this->hasMany(Movie::class);
}

public function tvserious()
{
return $this->hasMany(Tvserious::class);
}



what i tried and it's working


public function CategoryClick($slug){



$media = Category::where('slugid',$slug)->with(['movies' => function($query) {
$query->whereNotNull('title');
},'tvserious' => function($query) {
$query->whereNotNull('title');
}])->inRandomOrder()->paginate(8);



return view('test')->with([
'catclick'=>$media,
'title'=>$slug,
]);


}



the problem with this way is in my blade i have to create a loop for movies and tvserious and the tvserious data will always stay at the end at it will show after the movies loop ends


@foreach($catclick as $media)

@foreach($media->movies as $movie )

{{ $movie->title }}

@endforeach


@foreach($media->tvserious as $tvserious )

{{ $tvserious->title }}

@endforeach

@endforeach



so how can i get both of my movies and serious in my blade mixed together



i don't want all the movies to be at first so where is the problem and how can i fix this ?




1 Answer
1



You can use this code


@php
$moviesCount = $media->movies->count();
$tvseriousCount = $media->tvserious->count();
$maxCount = ($tvseriousCount > $moviesCount) ? $tvseriousCount : $moviesCount;
@endphp

@for ($index = 0; $index < $maxCount; $index++)

@isset($media->movies[$index])
{{ $media->movies[$index]->title }}
@endisset

@isset($media->tvserious[$index])
{{ $media->tvserious[$index]->title }}
@endisset

@endfor






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS