Building a dynamic query of a many-to-many relationship in Laravel 5

Jim

I am pretty new to the Laravel Eloquent ORM and am having difficulty building a dynamic query to query products of a category.

I parse the request object and return products according to what vars have been passed through. This is easy enough when I am querying a single Model but I want to know how to build a query dynamically if a category is passed through to. This is easy enough using standard MYSQL and PHP but I am unsure as to how this is achieved in LAravel.

Here is my code:

Product Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $primaryKey = 'id',
              $table      = 'products',
              $fillable   = array('title', 'SKU', 'description', 'created_at', 'updated_at');

    public $timestamps = true;

    /**
     * Get the categories assoicated with the product
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     *
     */
    public function categories() {
        return $this->belongsToMany('App\Category')->withTimestamps();
    }
}

Category model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * Returns all products related to a category
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function products() {
        return $this->belongsToMany('App\Product')->withTimestamps();
    }

}

Inside my product controller I have this function to get products which calls a method 'filterProduct' in a class called 'filtervars':

public function index(Request $request)
{
    return FilterVars::filterProduct($request->all());
}

And here is the filterProduct method:

public static function filterProduct($vars) {

        $query = Product::query();

        if((array_key_exists('order_by', $vars)) && (array_key_exists('order', $vars))) {
            $query = $query->orderBy($vars['order_by'], $vars['order']);
        }

        if(array_key_exists('cat', $vars)) {
            $query = $query->whereHas('categories', function($q) use ($vars){
                return $q->where('category_id', $vars['cat']);
            });
        }     

        return $query->get();

The product database migration:

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function(Blueprint $table) {
            $table->increments('id');
            $table->string('title', 75);
            $table->string('SKU')->unique();
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

And the migration which shows the structure of the categories table, the pivot table and foreign keys etc:

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description');
            $table->timestamps();
        });

        Schema::create('category_product', function(Blueprint $table) {
            $table->integer('product_id')->unsigned()->index();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

            $table->integer('category_id')->unsigned()->index();
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
            $table->timestamps();
        });
    }

I had a go at trying to incorporate the 'has' method on the query but this doesn't seem to work. can anyone advise as to where I am going wrong?

Thanks!

huuuk

May be you need whereHas method

$query = $query->whereHas('categories', function($q) use ($vars) {
    $q->where('id', $vars['cat']);
});

EDIT

You should use id column in whereHas method because you apply where condition to categories table, which hasn't category_id column

public static function filterProduct($vars) {

    $query = Product::query();

    if((array_key_exists('order_by', $vars)) && (array_key_exists('order', $vars))) {
        $query = $query->orderBy($vars['order_by'], $vars['order']);
    }

    if(array_key_exists('cat', $vars)) {
        $query = $query->whereHas('categories', function($q) use ($vars){
            $q->where('id', $vars['cat']);
        });
    }     

    return $query->get();
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Laravel 5 - Dedicated Query string filtering on many-to-many Relationship

From Dev

Laravel Many to Many query relationship with where clause

From Dev

Many to Many relationship query. Laravel

From Dev

Laravel Many to Many query relationship with where clause

From Dev

Laravel many-to-many relationship query

From Dev

Laravel 5 Eloquent count many to many relationship

From Dev

Laravel 5 | Many to Many Relationship not working

From Dev

Laravel - Many to Many relationship

From Dev

Many to many relationship in Laravel

From Dev

Many to Many relationship with Laravel

From Dev

Laravel 5.2 Many to Many Relationship inverse query empty results

From Dev

many-to-many relationship OrderBy - Laravel query builder

From Dev

Laravel - SQL query equals the value of id to null in many to many relationship

From Dev

Laravel 5 Eloquent Relationship - Has Many Though

From Dev

Laravel 5 Deleting a one-to-many relationship

From Dev

Laravel 5 one to many eloquent relationship

From Dev

Laravel 5 Eloquent Relationship - Has Many Though

From Dev

Query many to many relationship with DetachedCriteria

From Dev

how to query a many to many relationship?

From Dev

eloquent: query many to many relationship

From Dev

Laravel 5 - access specific model on many to many relationship

From Dev

Empty data returning from many to many relationship laravel 5

From Dev

Laravel 6 many to many relationship

From Dev

Pagination with many to many relationship in laravel

From Dev

Laravel many to many relationship error

From Dev

Laravel many to many relationship with conditions

From Dev

Laravel ORM many to many relationship

From Dev

Building many-to-many relationship off of another?

From Dev

How to query only one foreign row in a one-to-many relationship in Laravel 5

Related Related

  1. 1

    Laravel 5 - Dedicated Query string filtering on many-to-many Relationship

  2. 2

    Laravel Many to Many query relationship with where clause

  3. 3

    Many to Many relationship query. Laravel

  4. 4

    Laravel Many to Many query relationship with where clause

  5. 5

    Laravel many-to-many relationship query

  6. 6

    Laravel 5 Eloquent count many to many relationship

  7. 7

    Laravel 5 | Many to Many Relationship not working

  8. 8

    Laravel - Many to Many relationship

  9. 9

    Many to many relationship in Laravel

  10. 10

    Many to Many relationship with Laravel

  11. 11

    Laravel 5.2 Many to Many Relationship inverse query empty results

  12. 12

    many-to-many relationship OrderBy - Laravel query builder

  13. 13

    Laravel - SQL query equals the value of id to null in many to many relationship

  14. 14

    Laravel 5 Eloquent Relationship - Has Many Though

  15. 15

    Laravel 5 Deleting a one-to-many relationship

  16. 16

    Laravel 5 one to many eloquent relationship

  17. 17

    Laravel 5 Eloquent Relationship - Has Many Though

  18. 18

    Query many to many relationship with DetachedCriteria

  19. 19

    how to query a many to many relationship?

  20. 20

    eloquent: query many to many relationship

  21. 21

    Laravel 5 - access specific model on many to many relationship

  22. 22

    Empty data returning from many to many relationship laravel 5

  23. 23

    Laravel 6 many to many relationship

  24. 24

    Pagination with many to many relationship in laravel

  25. 25

    Laravel many to many relationship error

  26. 26

    Laravel many to many relationship with conditions

  27. 27

    Laravel ORM many to many relationship

  28. 28

    Building many-to-many relationship off of another?

  29. 29

    How to query only one foreign row in a one-to-many relationship in Laravel 5

HotTag

Archive