简体   繁体   中英

Laravel, Category relations posts

So I don't how to use posts with categories in my foreach. Controller

        $Categories = \App\Category::Where('displayed',1)->get();
        foreach ($Categories as $Category){
        $CategoryPosts[]=$Category->load('posts');
        }
        dd($CategoryPosts);
        return view('welcome', compact($CategoryPosts));

Page

@forelse($CategoryPosts as $post)
         <div  id="content-number-1" class="col-12 col-md-8 col-lg-8 home-post1 content-number-1">
            <div class=""><img class="content-one-img content-img-chapter" src="{{$post->image}}"></div>
            <div class="content-text-img p-3"><p><a class="m-0 underImage aTagsHover" style="font-size: 20px" href="/inside/{{$post->id}}">{{$post->title}}</a><br><span class="date-font"><i class="fa fa-clock-o" aria-hidden="true"></i>{{$post->created_at}}</span><span class="underBusiness"><br>{{$post->short_desc}}</span></p></div>
        </div>
@empty
        <div  id="content-number-1" class="col-12 col-md-8 col-lg-8 home-post1 content-number-1">
            <div class="content-one-img content-img-chapter"></div>
            <div class="content-text-img p-3"><p><a class="m-0 underImage aTagsHover" style="font-size: 20px" href="#">No post</a><br><span class="date-font"><i class="fa fa-clock-o" aria-hidden="true"></i>No time</span><span class="underBusiness"><br>No post</span></p></div>
        </div>
@endforelse

I have 2 categories and 3 posts right there. https://prnt.sc/ujrvxs .

You can go at this from the other direction to only get the Posts:

$posts = Post::whereHas('category', function ($query) {
    $query->where('displayed', 1);
})->get();

Assuming you have the inverse of the relationship setup Post -> Category. This is saying get all Posts having Category where displayed equals 1.

Adjust the relationship name as needed.

Laravel 7.x Docs - Eloquent - Relationships - Querying Relationship Existence whereHas

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM