Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Laravel Category Example

Category Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * Get subcategories.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function subcategories()
    {
        return $this->hasMany(Subcategory::class);
    }
}

Subcategory Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subcategory extends Model
{
    /**
     * Get category.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    /**
     * Get news.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function news()
    {
        return $this->belongsToMany(News::class);
    }
}

News Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class News extends Model
{
    /**
     * Get subcategories.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function subcategories()
    {
        return $this->belongsToMany(Subcategory::class);
    }
    
    /**
     * Fetch news by category.
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @param  int                                   $id
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeByCategory($query, $id)
    {
        return $query->whereHas('subcategories', function ($query) use ($id) {
            $query->where('category_id', $id);
        });
    }
}

Fetching news by category

$category = Category::find(1);

News::byCategory($category->id)->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.