1
votes

This is my first laravel Application, and my first database based application so please be patient with me !! I will try to be specific!!

Categories Table: Id Name Timestamps

Posts table: Id title body slug Category_id timestamps

Lets say i have 4 catergories. Laptops, computers,phones,tablets

I want when i go to /computers to be able to get all the posts that are specific to that category.

Posts Model

Category Model

Category Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\Category;

class CatController extends Controller
{
   public function getCategory($Category_id)
{
   $posts = Post::where('Category_id',$Category_id);
  return view('blog.index',['posts' => $posts]);
}

Route:

Route::get('computer/{Category_id}','CatController@getCategory');

I am really confused at the moment !! Thanks everyone in advance!!

3
Try $posts = DB::table('posts')->where('Category_id', $Category_id)->get();Stefan Blamberg

3 Answers

1
votes

Define your Model

class Category extends Model
{
    /**
     * Get the posts.
     */
    public function posts()
    {
        return $this->hasMany('App\Post', 'Category_id');
    }
}

class Post extends Model
{
    /**
     * Get the category.
     */
    public function category()
    {
        return $this->belongsTo('App\Category', 'Category_id');
    }
}

Define your Controller

class CatController extends Controller
{
    public function getCategory($Category_id)
    {
        $category = Category::find($Category_id);
        if($category !== null){
            $posts = $category->posts;
            return view('blog.index',['posts' => $posts]);
        }
    }
0
votes

I hope this will help you.

Route:

Route::get('categories/{category_id}/computers','CatController@show');

Controller:

public function show($category_id)
{
   $category = Category::findOrFail($category_id);

    if($category){
       $posts = Post::where('Category_id',$category_id)->get();

        return view('category.index', compact('posts'));
    }

    return view('errors.404');
}
0
votes

Simply add this to your controller

public function category($id){


  $data['posts'] = Post::where('status', 1)->where('category_id', $id)->orderBy('id', 'DESC')->get();

  return view('frontEnd.home', $data);
}