1

I'm using Laravel 4 and I need to take entries from my database, put them into an array and use them in a foreach loop in my view.

I'm not getting any errors but I'm also not getting anything from the database.

I'm trying to edit this page of a Laravel bundle to get products from the database, rather than statically.

This is my query from my Model

return $products = \DB::select('select * from products', array('sku', 'name'));

Controller...

public function getIndex()
{
    // Get the products.
    //
    $products = Products::all();

    // Show the page.
    //
    return View::make('shpcart::home')->with('products', $products);
}

This is my view

<pre>
<?php
   print_r($products);
?>
</pre>

This is the result

Array ( )

This works to insert into the database:

DB::insert('insert into products (sku, name) values (?, ?)', array('WS004', 'Test'));

This...

$products = DB::table('products')->get();

foreach ($products as $product)
{
echo $product->sku;
}

returns the error

Invalid argument supplied for foreach()

You can see it here...

http://wilsonswan.co.uk/collection

Thanks in advance.

Tayler Hughes
  • 41
  • 2
  • 7

2 Answers2

0

You should not return $products as such.

You should perhaps do something like:

public function index()
{
$products = Products::where('sku', '=', 'name')->get();

return View::make('view', compact('products'));
}
Glad To Help
  • 5,299
  • 4
  • 38
  • 56
  • I'm getting the error 'Class 'Products' not found'. I guess this is because I have not set it up. I'm trying to customise this page of a bundle to get products from the database, rather than statically. https://github.com/rktaiwala/Shpcart/blob/master/src/Models/Products.php – Tayler Hughes Sep 30 '13 at 13:14
  • I am not familiar with that package, but you will have to check the SQL query passed to the database to identify what exactly is happening. http://stackoverflow.com/a/14536215/385402 – Glad To Help Sep 30 '13 at 13:33
0

try this:

public function getIndex() {
    $db = DB::table('products as p')
               ->where('p.sku', '=', 'WS004');

    $products = $db->get();

    return View::make('shpcart::home')
              ->with('products', $products);
}
helderam
  • 37
  • 1
  • 7