PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 8, 2022

[FIXED] Show category posts in Laravel is not working

 January 08, 2022     laravel     No comments   

Issue

I want to show posts that are in a category by clicking on them, but when I click on a category,$articles in category.blade.php returns null.

$articles should return articles that have a specific category

this is my index.blade.php:

                    <div class="tab-pane fade" id="show-categories" role="tabpanel">
                        <h6 class="sidebar-title">Categories</h6>
                        <div class="row link-color-default fs-14 lh-24">
                          @foreach($categories as $category)
                            <div class="col-6">
                              <a href="{{ route('cms.category', $category->id) }}">
                                {{ $category->name }}
                              </a>
                            </div>
                          @endforeach
                        </div>
                    </div>

category.blade.php:

@extends('layouts.app')
@section('content')
    @forelse ($articles as $article)
    <h1>{{$article->title}}</h1>
    @empty 
        <span>array is empty</span>
    @endforelse
   
@endsection

router:

Route::get('cms/categories/{category}', [articlesController::class, 'category'])->name('cms.category');

and articlesController:

    public function category(Category $category)
    {
      return view('cms.category')
        ->with('category', $category)
        ->with('articles', $category->articles()->searched()->simplePaginate(3))
        ->with('categories', Category::all())
        ->with('tags', Tag::all());
    }

Solution

Please, don't forget to define the relationship from Category to Article on your model. Like: one category has many articles. For example:

On your Category.php model:

public function articles() 
{
    return $this->hasMany(Article::class);
}

Then on your, controller, you may call the relationship like this way:

public function category(Category $category)
{
    $articles = Category::with("articles")->where("id", $category->id)->simplePaginate(3);
    return view('cms.category')
        ->with('category', $category)
        ->with('articles', $articles)
        ->with('categories', Category::all())
        ->with('tags', Tag::all());
}


Answered By - S Ahmed Naim
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing