簡體   English   中英

如何在Laravel中顯示所有類別

[英]How to Display All Categories in Laravel

我試圖在單個帖子中顯示數據庫中的所有類別,但是,我也將數據庫中的五個類別顯示為我的導航菜單。 我不確定這是我正在使用的循環,因為我不斷獲得五個類別而不是所有類別。

public function index()
{
    return view('index')->with('title', Setting::first()->site_name)
        ->with('categories', Category::take(5)->get())
        ->with('first_post', Post::orderBy('created_at', 'desc')->first())
        ->with('second_post', Post::orderBy('created_at', 'desc')->skip(1)->take(1)->get()->first())
        ->with('third_post', Post::orderBy('created_at', 'desc')->skip(2)->take(1)->get()->first())
        ->with('wordpress', Category::find(4))
        ->with('laravel', Category::find(3))
        ->with('settings', Setting::first());
}

這是我的單個發布控制器的代碼

public function singlePost($slug)
{
    $post = Post::where('slug', $slug)->first();
    $next_id = Post::where('id', '>', $post->id)->min('id');
    $prev_id = Post::where('id', '<', $post->id)->max('id');

    return view('single')->with('post', $post)
        ->with('title', $post->title)
        ->with('settings', Setting::first())
        ->with('categories', Category::all())
        ->with('next', Post::find($next_id))
        ->with('prev', Post::find($prev_id))
        ->with('tags', Tag::all())
        ->with('first_post', Post::orderBy('created_at', 'desc')->first())
        ->with('second_post', Post::orderBy('created_at', 'desc')->skip(1)->take(1)->get()->first())
        ->with('third_post', Post::orderBy('created_at', 'desc')->skip(2)->take(1)->get()->first());
}

這就是我在single.blade.php中傳遞值的方式

@foreach($categories as $category)
    <div class="post-category-wrap">
        <div class="category-post-item">
            <!-- <span class="post-count">168</span> -->
            <a href="{‌{route('category.single', ['id' => $category->slug])}}" class="category-title">{‌{$category->name}}
                <i class="seoicon-right-arrow"></i>
            </a>
        </div>
    </div>
@endforeach 

我認為您應該在“類別”的索引查詢中更改var名稱。 類似於->with('categories_to_navigation', Category::take(5)->get()) 如果視圖single.blade.php擴展index.blade.php此var名稱將被覆蓋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM