How to split a query of an Eloquent model

I am trying to expose an Eloquent query like this

$query = new Product;

if (!empty($req->query['id'])) {
    $query->where('id', '=', '1');
}

$products = $query->get();

      

The result above gives me all the products in the database. It does, however, work.

$products = Product::where('id', '=', '1')->get();

      

Is there a way to do this?

+1


source to share


2 answers


In Laravel 4, you need to add your request parameters to your request variable. In Laravel 3 it will work the way you do.

This is what you need to do (I'm not sure if it will work with new Product

tho):



$query = new Product;

if (!empty($req->query['id'])) {
    $query = $query->where('id', '=', '1');
}

$products = $query->get();

      

+1


source


Your code doesn't make sense. If you do new Product

- then it will never have an ID associated with it, so yours if (!empty($req->query['id']))

will always be false.

Are you just trying to get a specific product idea?

$products = Product::find(1);

      



coincides with

$products = Product::where('id', '=', '1')->get();

      

0


source







All Articles