Ahmad Badpey
Ahmad Badpey

Reputation: 6612

using with() method Along with find() method return all model instances instead one instance in laravel

This is my Product Model:

class Product extends Model
    {
        protected $primaryKey = 'product_id';
        public    $guarded    = ['created_at', 'updated_at'];

        public function product_pics ()
        {
            return $this->hasMany('App\ProductPics');
        }

    }

And this is ProductPics Model:

class ProductPics extends Model
{
    public    $timestamps = false;
    protected $fillable   = ['pic_name'];
    protected $primaryKey = 'pic_id';

    public function product ()
    {
        return $this->belongsTo('App\Product');
    }
}

Now I want to fetch a specific product along with all it's product pictures in ProductController show() method . for that I write this :

public function show ($id)
        {
            $product    =   Product::find($id)->with('product_pics')->get();
            return $product;

            return view('main.pages.product')->with(['product'=> $product]);
        }

But contrary to expectations,while I use find() method to select only one Model, it return a set of all Products model with related Product pictures.

What is Problem ?

Upvotes: 1

Views: 72

Answers (1)

Sven van Zoelen
Sven van Zoelen

Reputation: 7229

It's because you use the get() at the last part. Remove the get() and change the order of the methods bacause the find() method is returning a Illuminate\Database\Eloquent\Model or an Collection.

So to explain what's happening in your case: it finds and returns the model with the given $id. Then you start a new query on the returned Product model with static method with( .. ) and then get() to return all results as an Collection.

Maybe more clear in a programming style:

$product = Product::find($id); // SELECT * FROM products WHERE `id` = $id
// $product is now the model Product with loaded data from the DB.

$product = $product->with('product_pics')->get(); // SELECT * FROM products JOIN product_pics ON ... 
// $product var is replaced with the collection of all products of the DB.

Rewrite your method to the following to make it work:

public function show ($id)
{
    $product = Product::with('product_pics')->find($id);

    return view('main.pages.product')->with(['product'=> $product]);
}

Upvotes: 3

Related Questions