Gediminas Šukys
Gediminas Šukys

Reputation: 7391

Why my where query is not executed in controller?

I'm trying to reach items table from CategoriesController.php, but I see in Laravel(5.3) Debugbar, that my query is not executed. Why? Here is my code:

# Http/Controllers/CategoriesController.php

use App\Category;
use App\Item;
use App\Http\Requests;
use App\Http\Controllers\Controller;

namespace App\Http\Controllers;

use Request;

class CategoriesController extends Controller {

  public function show($id) {

    $items = \App\Item::where('id', $id); # <- This is not executed!

    $category = \App\Category::find($id);

    return view('categories.show', compact('category', 'items'));

  }

}

Upvotes: 0

Views: 47

Answers (3)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You need to use get() or first() or paginate or pluck() or find() etc to execute the query. In this case you want to use first() method:

\App\Item::where('id', $id)->first();

Or just:

\App\Item::find($id);

Upvotes: 1

Loek
Loek

Reputation: 4135

$items = \App\Item::where('id', $id);

This line is preparing a query for Eloquent to execute, but you never actually execute it.

Try running the following to execute the query and get all the results.

$items = \App\Item::where('id', $id)->get();

Upvotes: 1

Ohgodwhy
Ohgodwhy

Reputation: 50787

::where() is chaining off of the query builder, however you never execute the request.

::where('id', $id)->first(); //if you only want the first result
//shorthand would be ::find($id);

Alternatively if you want every match:

::where('id', $id)->get(); 

Upvotes: 5

Related Questions