Search code examples
databaselaraveleloquentcollectionscategorical-data

Get posts by category's name in HomeController (Laravel 8)


To explain it in detail: for example, i am creating posts with category, however i am saving it in a different table (post_categories), which means my posts and categories are connected through their IDs (belongToMany). Now in my HomeController i want to display posts, by the category name, for example: $posts = post::where([['status',1],['category', 'electronics'])->orderBy('created_at', 'DESC')->limit(1)->get();

I want to display my posts by the Category-NAME and not Category-ID

I tried it but it doesnt really work, i guess i forgot something or I am using the wrong methode, pls help me

CODES

Home Controller

public function index()
{
    $posts = post::where([['status',1],//here is category missing])->orderBy('created_at', 'DESC')->limit(1)->get();
    $categories = Category::all();
    return view('user.home', compact('posts', 'categories'));
}
public function category(category $category)
{
    $posts = $category->posts();
    return view('user.home',compact('posts'));
}

category Model

use HasFactory;

public function posts()
{
    return $this->belongsToMany('App\Models\user\post','category_posts')->orderBy('created_at','DESC')->paginate(5);
}

public function getRouteKeyName()
{
    return 'slug';
}

post Model

 use HasFactory;

public function categories()
{
    return $this->belongsToMany('App\Models\user\category','category_posts')->withTimestamps();;
}
public function getRouteKeyName()
{
    return 'slug';
}

DATABASE

Posts_table

    public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title',1000);
        $table->string('subtitle',1000);
        $table->string('slug',1000)->nullable();
        $table->text('body');
        $table->boolean('status')->nullable();
        $table->integer('posted_by')->nullable();
        $table->string('image')->nullable();
        $table->timestamps();
    });
}

Categories_table

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('slug');
        $table->timestamps();
    });
}

category_posts

public function up()
{
    Schema::create('category_posts', function (Blueprint $table) {
        $table->unsignedBigInteger('post_id');
        $table->unsignedInteger('category_id');
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        $table->timestamps();
    });
}

Solution

  • i already got the answer i removed the relation and added location to a value in order to c