Why my where query is not executed in controller? - laravel

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'));
}
}

::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();

$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();

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);

Related

Laravel eloquent call realtionship based on a boolean parameter

I'm trying to make a method to retrieve model with a relationship I'd like to be able to fetch the relation based on a boolean parameter
for example, I can do it using the if condition like the following
if($load == true){
$users = User::with('login')->all()->paginate();
}else{
$users = User::all()->paginate();
}
I'm wondering if there's a way to do it without the if condition on the fly
You can use the when() method on the query builder. Note that you don't need to use the all() method when you want to use a paginator.
User::query()
->when($load, fn($query) => $query->with('login'))
->paginate();
you can use when method:
$users = User::when($load, function ($query) {
return $query->with('login');
})->paginate(10);
The when method only executes the given closure when the first argument is true. If the first argument is false, the closure will not be executed

laravel: odd behavior when query is empty

I have a model
I call it this way:
Sight::filter(['type'=>'menu']);
and in model:
public function scopeFilter($query,$params)
{
return $query
->wherePublish(1)
->whereIn_special(1)
->latest()
->first();
}
when there is one or more records, it works normally.
but when database is empty I get an odd behavior:
with dd(Sight::filter(['type'=>'menu']))
or
$query
->wherePublish(1)
->whereIn_special(1)
->latest()
->first();
dd($query);
I got this result:
But with
dd(
$query
->wherePublish(1)
->whereIn_special(1)
->latest()
->first();
)
I got Null so it is right!
how can I return Null? what is my wrong?
You shouldn't be calling first() inside of a scope - you are only meant to adjust the query by constraining it. You should call first() in your chain after applying the filter() scope. If you want to use the same syntax rather than chaining like that you would be best to define a custom static method.
public static function filter($params)
{
return self::wherePublish(1)
->whereIn_special(1)
->latest()
->first();
]
Also note that in your example your scope accepts an argument (and you pass it one) but it isn't actually used in your code.

How to solve Method orderBy does not exist on laravel?

I use this package : https://github.com/andersao/l5-repository
My user repository is like this :
public function getList($year)
{
$query = parent::findWhere(['year' => $year])
->orderBy('updated_at')
->paginate(10);
return $query;
}
When executed, there exist error like this :
Method orderBy does not exist.
Whereas I see in the documentation, there exist orderBy
How can I solve it?
If you'll look into the findWhere() method, you'll see that it executes query:
$model = $this->model->get($columns);
So, you'll not be able to use orderBy() or paginate() after findWhere().
findWhere exec the query and get your values using get().
try to change your code to this:
public function getList($year)
{
$query = parent::where('year', '=>', $year)
->orderBy('updated_at')
->paginate(10);
return $query;
}
use something like that for compound searches
$posts = $this->repository->scopeQuery(function($query){
return $query->orderBy('name','asc');
})->findByField('user_id',$dataForm['user_id']);

How to add subqueries in eloquent db of laravel 5?

I am building an api in laravel 5.3 using eloquent if I use /api/location/event_name/event_status then I am getting results.
But when I use /api/location/event_name or /api/location/ nothing comes.
How to write the query so that all my link show result?
class events_api extends Controller
{
public function events($location = "",$event_name="",$event_status="")
{
$events = DB::table('event_table')
->join('event_details', 'event_table.event_id', '=', 'event_details.event_id')
->join('venue', 'event_details.venue_id', '=', 'venue.venue_id')
->where('venue.venue_city','=',$location)
->where('event_table.event_name','=','$event_name')
->where('event_table.event_status','=','$event_status')
->where('event_table.event_post_status','=','publish')
->select('event_table.event_title','event_details.event_start_ts','event_details.event_views','venue.venue_name','venue.venue_city','venue.venue_location')
->get();
echo $events;
}
}``
If you would like to make a subQuery try using toSql method:
class events_api extends Controller
{
public function events($location = "",$event_name="",$event_status="")
{
$subQuery = DB::table('event_table')
->join('event_details', 'event_table.event_id', '=', 'event_details.event_id')
->join('venue', 'event_details.venue_id', '=', 'venue.venue_id')
->where('venue.venue_city','=',$location)
->where('event_table.event_name','=','$event_name')
->where('event_table.event_status','=','$event_status')
->where('event_table.event_post_status','=','publish')
->select('event_table.event_title','event_details.event_start_ts','event_details.event_views','venue.venue_name','venue.venue_city','venue.venue_location');
DB::table(DB::raw("{$subQuery->toSql()} as main_query"))
->mergeBindings($subQuery->getBindings())
// build your query here
->get()
}
}
You'll also need to mergeBindings if you use any bindings in subquery

Active Record and queries with CodeIgniter

I am using codeigniter for my application and i am a bit confused, I wrote some queries like that:
public function checkemail($email) {
$this->db->select('email')->from('user')->where('email', $email);
}
But in the manual of codeigniter ( http://codeigniter.com/user_guide/database/active_record.html ) they talk about $this->db->get();
Should I add it after the $this->db->select query?
My function works fine...
When should I use get() ?
Thanks you!
Yes, you'll need to run get() after the other methods. select(), from() and where() add their respective statements to the query, and get() actually runs the query and returns the result as an object.
In this case, you could just add it on to the end of the chain.
public function checkemail($email) {
$this->db
->select('email')
->from('user')
->where('email', $email)
->get();
}
If you want to work with the result afterwards, make sure that you are assigning it to a variable.
$user = $this->db
->select('email')
->from('user')
->where('email', $email)
->get();
If you use get("table_name") then you don't need to use from("table_name"). It's just an alternative syntax it seems.
From the user guide, all the way at the bottom it says: As shown earlier, the FROM portion of your query can be specified in the $this->db->get() function, so use whichever method you prefer.

Resources