lukeboy_2002's avatar

Wrong data

Hello I don't now of this wright channel to ask my question.

is the made a small blog component. The blog post belongs to many categories and a categorie belongs to many posts.

Everything works well without post by category. If I select a categorie, route, I want to show all posts belong to that categorie but it is not working. I get wrong categories or is empty.

I select my categories with:

@foreach($post->categories as $category)
<x-link.category href="{{ route('posts.by-category', $category ) }}" class="hidden sm:inline-flex mx-1 uppercase">
 {{ $category->title }}
</x-link.category>
@endforeach

in my web route:

Route::get('category/{category:slug}', [\App\Http\Controllers\PostController::class, 'byCategory'])->name('posts.by-category');

in my model Post

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function categories(): BelongsToMany
    {
        return $this->belongsToMany(Category::class)->withTimestamps();
    }

in my model Categorie

    public function posts(): BelongsToMany
    {
        return $this->belongsToMany(Post::class);
    }

in my PostController

public function byCategory(Category $category)
    {
        $posts = Post::query()
            ->join('category_post', 'posts.id', '=', 'category_post.post_id')
            ->where('category_post.category_id', '=', $category->id)
            ->where('active', 1)
            ->whereDate('published_at', '<=', Carbon::now())
            ->orderBy('published_at', 'desc')
            ->with('user', 'categories', 'views')
            ->paginate(6);

        return view('posts.index', [
            'posts' => $posts,
            'category' => $category
        ]);
    }

im my index file

<x-app-layout>
    <div class="w-full bg-white dark:bg-gray-800 mb-6">
        <div class="relative w-full bg-white dark:bg-gray-800 overflow-hidden">
            <div class="relative float-left w-full">
                <img
                    src="{{ asset('storage/backgrounds/blog.jpg') }}"
                    class="block w-full h-64 sm:h-64 md:h-64 object-center object-cover"
                    alt="$slide->title"
                />
                <div class="absolute inset-0 h-full text-center">
                    <div class="flex flex-col h-full items-center justify-center">
                        <h5 class="text-3xl font-black text-orange-500 uppercase">TripleB post</h5>
                    </div>
                </div>
            </div>
        </div>

        <section class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-4 py-6">
            <div class="border-l-4 border-orange-500 pl-4 flex justify-between items-center">
                <div class="text-orange-500 hover:text-orange-600 font-black uppercase focus:outline-none focus:text-orange-600">
                    Blog
                </div>
            </div>
            @if ($posts->count())
                <div class="mt-4 md:grid md:grid-cols-6 md:gap-4">
                    @foreach ($posts as $post)
                        <x-blog.single-post
                            :post="$post"
                            class="md:col-span-3 lg:col-span-2 mt-4 lg:mt-0"
                        />
                    @endforeach
                </div>
                <div class="py-6">
                    {{ $posts->links() }}
                </div>
            @else
                <x-error.404>
                    <x-link.btn-primary href="{{ route('posts.index') }}" class="px-3 py-2 text-xs font-medium">
                        Back to news
                    </x-link.btn-primary>
                </x-error.404>
            @endif
        </section>
    </div>
</x-app-layout>

And my single-post

<article {{ $attributes->merge(['class' => 'bg-white border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-700']) }}>
    <div class="relative">
        <a href="{{ route('posts.show', $post->slug) }}">
            <img class="mx-auto max-h-52 w-full object-cover" src="{{ asset($post->getImage() )}}" alt="{{ $post->title }}">
        </a>
        <div class="absolute bg-orange-500 block h-16 mr-4 right-0 text-center text-lg text-white top-0 w-16">
            <p class="text-3xl font-extrabold">{{ $post->published_at->format('d') }}</p>
            <p class="text-sm">{{ $post->published_at->format('M') }}</p>
        </div>
    </div>
    <div class="p-3">
        <div class="mb-4 flex justify-end">
            @foreach($post->categories as $category)
                <x-link.category href="{{ route('posts.by-category', $category ) }}" class="hidden sm:inline-flex mx-1 uppercase">
                    {{ $category->title }}
                </x-link.category>
            @endforeach
        </div>

        <div class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white w-5/6">
            <a href="{{ route('posts.show', $post->slug) }}">
                {{ $post->title }}
            </a>
        </div>
        <div class="mb-3 font-normal text-gray-700 dark:text-gray-400">
            {!! $post->shortBody() !!}
        </div>
        <footer class="hidden sm:block space-y-2">
            <div class="flex items-center space-x-2">
                <div class="text-xs text-gray-500">
                    <i class="fa-regular fa-clock mr-2"></i>{{ $post->getFormattedDate() }}
                </div>
                <div class="text-xs text-gray-500">
                    <i class="fa-regular fa-user mr-2"></i>{{ $post->user->username }}
                </div>
                <div class="text-xs text-gray-500">
                    {{--                <i class="fa-solid fa-comments ml-4 mr-2"></i>{{ $post->comments->count() }}--}}
                    <i class="fa-solid fa-comments mr-2"></i>10
                </div>
            </div>
        </footer>
    </div>
</article>

The full code of the website including the branch for the front end is on GitHub https://github.com/lukeboy2002/TBV-Tripleb_New/tree/Front-end_blog

I will upload this website so there is an example, https://www.la-online.nl

0 likes
2 replies
LaryAI's avatar
Level 58

The issue seems to be with the byCategory method in the PostController. The query is not correctly retrieving the posts that belong to the selected category.

To fix this, you can modify the byCategory method as follows:

public function byCategory(Category $category)
{
    $posts = $category->posts()
        ->where('active', 1)
        ->whereDate('published_at', '<=', Carbon::now())
        ->orderBy('published_at', 'desc')
        ->with('user', 'categories', 'views')
        ->paginate(6);

    return view('posts.index', [
        'posts' => $posts,
        'category' => $category
    ]);
}

This will use the relationship between the Category and Post models to retrieve the posts that belong to the selected category. The join statement is not necessary in this case.

Make sure to import the Category model at the top of the PostController file:

use App\Models\Category;

Also, ensure that the Category model is correctly imported in the Post model:

use App\Models\Category;

With these changes, the byCategory method should correctly retrieve the posts belonging to the selected category.

Snapey's avatar

Use relationships?

Make a relationship that is tailored to the data you want.

    public function byCategory(Category $category)
    {
			$category->load(['latestActivePosts' => ['user','categories','views']);

            return view('posts.index', [
                'posts' => $category->posts
            ]);
    }

Category model

public function latestActivePosts()
{
	return $this->belongsToMany(Post::class)
		->where('active',1)
		->whereDate('published_at', '<=', now())
        ->orderBy('published_at', 'desc');
}

Please or to participate in this conversation.