Miracle Hades
Miracle Hades

Reputation: 146

Laravel Eloquent Model with relationship

I have implemented eloquent relationship in my code but Laravel unable to read the function that I created to map the eloquent relationship in the model.

User Model

public function products(){
        return $this->hasMany(Product::class,'userid');
    }

Product Model

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

Product Controller

 $products = Product::with('Users')->Users()->where('users.isActive',1)->get();
        return view('product',compact('products'));

I keep getting error from the product controller, I also attached the error that I current encountered as below. enter image description here

How can I get all the product and user data with the where condition such as "Users.isActive = 1".

Thanks.

Upvotes: 0

Views: 1840

Answers (3)

Anurat Chapanond
Anurat Chapanond

Reputation: 2987

You can use whereHas to filter from a relationship.

$products = Product::with('users')
    ->whereHas('users', function ($query) {
        $query->where('isActive', 1);
    })
    ->get();

Also it is generally a good idea to use singular noun for belongsTo relationship because it returns an object, not a collection.

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

$products = Product::with('user')
    ->whereHas('user', function ($query) {
        $query->where('isActive', 1);
    })
    ->get();

EDIT

If you want to retrieve users with products you should query with User model.

$users = User::with('products')
    ->where('isActive', 1)
    ->get();

Then you can retrieve both users and products by

foreach($users as $user) {
    $user->products;
    // or
    foreach($users->products as $product) {
        $product;
    }
}

Upvotes: 2

SEYED BABAK ASHRAFI
SEYED BABAK ASHRAFI

Reputation: 4271

You can use whereHas() method for this purpose. Here is the doc

$products = Product::with('users')->whereHas('users', function (Illuminate\Database\Eloquent\Builder $query) {
    $query->where('isActive', 1);
})->get();

$users = $products->pluck('users');

return view('product',compact('products'));

Upvotes: 1

Thomas Galue
Thomas Galue

Reputation: 169

You have a typo after the with, is users instead of Users and you're redundant about the Query Builder, remove the ->Users():

Before:

$products = Product::with('Users')->Users()->where('users.isActive',1)->get();
        return view('product',compact('products')); 

After:

$products = Product::with('users')->where('users.isActive',1)->get();
            return view('product',compact('products')); 

Fix that and all should work.

Upvotes: 0

Related Questions