How can you do method chaining based on condition in laravel 4 ? Say if one value is not false then the method inside will be chained to the method called before the if statement.
Is it possible in laravel?
$data = User::where('username', $somevariable );
if(isset( $somevar_again ))
{
$data->where('age', 21);
}
$data->orderBy('reg_date', 'DESC')->get();
return $data->first();
// tried code above and its giving me wrong result
in codeigniter I can do this
$this->db->select('e.*, v.name_en as v_name_en')
->from($this->table_name . ' e, ' . $this->ptc_venues . ' v');
$this->db->where('e.venue_id_en = v.id');
if(isset($search)){
$this->db->where('(v.name_en LIKE "%'.$search.'%")');
}
$this->db->limit($limit, $start);
$this->db->order_by('e.added_date_en', 'DESC');
I believe your problem happened because you didn't store back the resulting query after each query builder method call.
$query = User::query();
// Checking for username if exists
if (!empty($username)) {
$query = $query->where('username', $username);
}
// Check for age if exists
if (isset($age)) {
$query = $query->where('age', $age);
}
// Ordering
$query = $query->orderBy('reg_date', 'DESC');
// Get the first result
// After this call, it is now an Eloquent model
$user = $query->first();
var_dump($user);
From Laravel 5.2 and onward, you can utilise Conditional Clauses/Statements:
Sometimes you may want statements to apply to a query only when
something else is true. For instance you may only want to apply a
where statement if a given input value is present on the incoming
request. You may accomplish this using the when method
The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.
You can use the code as follows:
$data = User::where('username', $somevariable)
->when( isset($somevar_again), function ($query) {
return $query->where('age', 21);
})
->orderBy('reg_date', 'DESC')
->get();
return $data->first();
Also, note that Laravel 5.3+, it has further been extended as documented below:
You may pass another Closure as the third parameter to the when
method. This Closure will execute if the first parameter evaluates as
false
Related
I am trying to implement a filtering method for some products.
This is the route:
Route::get('/TVs/{type?}/{producer?}', 'Product\AllProducts#getTVs')->where(['type' => '4kTV|curved|lcd|oled|plasma'], ['producer'=>'Samsung'])->name('TVs');
And this is the controller function:
public function getTVs($type = null, $producer = null)
{
$products = DB::table('products')->paginate(16);
if($type!=null) {
$products = Product::where('type', $type)->paginate(16);
}
if($producer!=null) {
$products = Product::where('description','like', '%'.$producer.'%')->paginate(16);
}
return view('product.TVs', ['products' => $products]);
}
If I select the type, the page refreshes and shows the results. Then if i enter the producer, again it works. How can i make the route in such a way, that the order of the optional parameters does not matter and i can filter the results no matter the order ?
Chain your queries; right now, you're running 3 queries, with ->paginate() being a closure and triggering a DB call. Try this:
$baseQuery = DB::table("products");
if($type){
$baseQuery->where("type", "=", $type);
}
if($producer){
$baseQuery->where("description", "like", "%".$producer."%");
}
$products = $baseQuery->paginate(16);
return view("products.TVs"->with(["products" => $products]);
As you can see, we add ->where clauses as required based on the input, and only run a single ->paginate() right before the return. Not this is additive searching, so it's WHERE ... AND ... and not WHERE ... OR ...; extra logic would be required for that.
I am getting a true return with very query in Laravel 5.2. I am making query in the controller and returning an array.
if($term = $request->get('term')){
$booking = guests::where('booking', '=', $term)->get();
$active = guests::where('booking', '=', $term)->pluck('active');
}
// dd($active);
if($active){
echo '
I have read it could potentially be solved by attribute casting by attempts have not worked.
Thanks
Both get() and pluck() will return a collection, so making an if condition like the one you are doing - will not return false even if a collection is completely empty (collection method isEmpty() would return false though). The result of if ($active) in your code has nothing to do with the value of the 'active' field itself.
You can try adding first() to the chain, assuming that you only have or you only need one item:
$booking = guests::where('booking', '=', $term)->get()->first();
$active = guests::where('booking', '=', $term)->pluck('active')->first();
I am using codeigniter active record class.
What I am trying here is calling get_users method from controller with parameter $user_id.
If $user_id is null get me all the entries from users table otherwise it should give me the entries that match the array passed with get_where() method.
But get_where method is not working instead get() method does the purpose with same parameters. Why would that happen? Thanks.
public function get_users($user_id=null)
{
if($user_id === null){
$q = $this->db->get('users');
}
elseif (is_array($user_id)) {
$q = $this->db->get('users', $user_id);
//$q = $this->db->get_where('users', $user_id); // not working
$result = $q->row_array();
}
return $q->result_array();
}
Your usage of get_where() is wrong:
It should be:
$q = $this->db->get_where('users', array('userid_fieldname_in_table'=>$user_id));
The second parameter should be an associative array where the key is the table's fieldname and the value is the value to look for.
Since you are passing an array it is better to use:
$this->db->where_in('filename', $array_of_values());
You can read more in the documentation
I have a search query that needs to be done. However, a search doesn't always have all values set, like in this case.
$aEvents = DB::table('events')
->where('client_id', '=', $client_id);
The question is, how can I make this where statement depend on the value of $client_id. So if the value is empty I don't want the Where statement to occur.
Also, I do not want to write several complete queries with if statements in PHP. To many variables. Ideally I'd like something like this:
$aEvents = DB::table('events')
->(($client_id != "") ? where('client_id', '=', $client_id) : "");
Using eloquent is (really!) nice and save, but I'm not yet up to speed with if statements in std Class objects I guess. Any help is appreciated.
You may try something like this:
$query = DB::table('events');
if(!empty($client_id)) {
$query->where('client_id', $client_id);
}
$aEvents = $query->get(); // Call this at last to get the result
If you are passing client_id to the server via a form/query string(user input) then you may try something like this:
if($client_id = Input::get('client_id')) {
$query->where('client_id', $client_id);
}
Update: For pagination try this:
$aEvents = $query->paginate(10); // For 10 per page
So you may call links() method in your view if you pass it like this:
return View::make('viewName')->with('aEvents', $aEvents);
In the view for pagination links:
$aEvents->links()
You can also use query scopes in the model for this purpose. Scopes allow you to easily re-use query logic in your models. In the model Event, you can add the following query scope:
public function scopeClientID($query, $client_id)
{
if ($client_id != '') {
return $query->where('client_id', '=', $client_id);
} else {
return $query;
}
}
Then from your controller or wherever you're calling it from, you can do the following:
$aEvents = Event::clientID($client_id);
If you want to get all the results, then you can do:
$aEvents = Event::clientID($client_id)->get();
Or if you want pagination, you can do:
$aEvents = Event::clientID($client_id)->paginate();
You can also chain it with other methods like you'd do in a eloquent query.
You can read more about model query scopes at http://laravel.com/docs/eloquent#query-scopes
I have a query builder that works:
$article = Page::where('slug', '=', $slug)
->where('hide', '=', $hidden)
->first();
But I want to only add the second where statement if hidden is equal to 1. I've tried the code below which shows the logic of what I'm trying to do, but it doesn't work.
$article = Page::where('slug', '=', $slug);
if ($hidden == 1) {
$article->where('hide', '=', 1);
}
$article->first();
I'm using Laravel 4, but I think the question still stands with Laravel 3.
Yeah there's a little "gotcha" with Eloquent and the query builder. Try the code below ;)
$query = Page::where('slug', '=', $slug);
if ($hidden == 1) {
$query = $query->where('hide', '=', 1);
}
$article = $query->first();
Note the assigning of $query within the conditional. This is becuase the first where (statically called) returns a different object to the query object within the conditional. One way to get around this, I believe due to a recent commit, is like so:
$query = Page::where('slug', '=', $slug)->query();
This will return the query object and you can do what you want as per normal (Instead of re-assigning $query).
Hope that helps.