How to apply Mysql AND/OR clause in Laravel - php

I am trying to make a MySQL query inside Laravel.
> "select * from users u where (name like
> '%".$request->search_string."%' or email like
> '%".$request->search_string."%') and (user_type=2)";
I tried the code below
public function searchUsers(Request $request){
$query = DB::table('users as u');
$query->where('u.user_type',2);
$query->where(function($query,$request){
$query->orwhere('u.name','LIKE','%'.$request->search_string.'%');
$query->orwhere('u.email','LIKE','%'.$request->search_string.'%');
});
$result['all_users'] = $query->get();
return Response::json($result);
}
But I am getting the following error
Missing argument 2 for
App\Http\Controllers\PatientController::App\Http\Controllers{closure}()

You have syntax error in where clause. See this:
public function searchUsers(Request $request){
$query = DB::table('users as u');
$query->where('u.user_type',2);
$query->where(function($query)use($request){ // Here is the change
// ^^ Pass only one parameter to closure function and pass `$request` in `use` function
$query->orwhere('u.name','LIKE','%'.$request->search_string.'%');
$query->orwhere('u.email','LIKE','%'.$request->search_string.'%');
});
$result['all_users'] = $query->get();
return Response::json($result);
}

Related

LARAVEL: How to fetch id dynamically in a query builder?

I want to join multiple tables in laravel with query builder. My problem is that my code only works if I specify the id myself that I want like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=','1')
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
But I would want something like this(which I just can't seem to figure out)
public function showuser($id)
{
$userid = User::findOrFail($id);
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$userid)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
}
Am I making a syntax mistake? When I check the page for my json response in second page it just returns empty brackets, but when I specify the id it fetches me the right data
The findOrFail method will return the entire user model, with all its properties, since you already have the user id. You dont need to get the entire user model for that, you could just use the $id you receveid as a parameter like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
public function showuser($id)
{
$getUserByID = User::findOrFail($id); //not used
$userData = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($userData);
}
But the best way is to have relations set on models
public function showuser($id)
{
$userData = User::where('id', $id)->with(['activitates','taga_cars','clients'])->first();
return response()->json($userData);
}

How to write conditional query in laravel 5.2?

How can I write this kind of queries in laravel 5.2 eloquent or query builder?
$query = Customers::leftjoin('Query string');
if(condition)
{
//This part added to query
}
else
{
//This part added to query
}
->get();
You have to remember your query in a variable, I.E. like this:
$query = Customers::leftjoin('Query string');
if(condation){
$query = $query->where('something', '=', 'something');
} else {
$query = $query->where('somethingelse', '=', 'somethingelse');
}
$query = $query->get();
Normally you would have $query->where()-get();, which is basically the same thing, $query will hold the result of your ->where() and allows you to chain further on $query

orderBy on whereHas query in Laravel 4.2

how can I sort the return data from a query using whereHas? In my query i have to get the users data which id exist on interest table but i need to sort it using the datetime column from interest. But, the return query do not sort the data at all.
Here's my code snippets in case it would help you understand my problem.
Model (name: User)
//***relationship***//
public function interest(){
return $this->belongsTo('Interest','id','interest_by');
}
Controller
$userInterested = User::whereHas('interest',function($q) use ($id) {
return $q->where('interest_on', $id)
->orderBy('datetime');
});
$userQuery = $userInterested->get();
return $userQuery;
remove return from where has and try this.like
$userInterested = User::whereHas('interest',function($q) use ($id) {
$q->where('interest_on', $id)
->orderBy('datetime');
})->get();
return $userInterested;
$userInterested = User::whereHas('interest',function($q) use ($id) {
return $q->where('interest_on', $id);
})->orderBy('datetime');
$userQuery = $userInterested->get();
return $userQuery;

yii2: Yii\db\Query in Model function

I am trying create a query in one of my model.php
The query is like
public function getBedCategory(){
$query = (new \yii\db\Query())
->select('room_category')
->from('room_charges')
->innerJoin('patient_detail',
'patient_detail.bed_type = room_charges.room_name')
->where(['room_charges.room_name'=> 'patient_detail.bed_type',
'patient_detail.id'=> $this->id]);
$command = $query->createCommand();
$rows = $command->queryOne();
//var_dump($command);exit;
return $rows;
}
When doing a var_dump for $command I am getting the sql query like this:
SELECT `room_category` FROM `room_charges`
INNER JOIN `patient_detail` ON patient_detail.bed_type = room_charges.room_name
WHERE (`room_charges`.`room_name`=:qp0) AND (`patient_detail`.`id`=:qp1)
and on var_dump of $rows I am getting boolean:false
What I am doing wrong here and why I am getting this :qp0 and :qp1
Thanks for any suggestion.
As Tahir correctly stated :qp0 and :qp1 are place holders for the parameters. These are replaced by static values on execution of the query. Your problem is that patient_detail.bed_type should not be parametized. Your code should therefore read:
...
->where(['room_charges.room_name = patient_detail.bed_type',
'patient_detail.id'=> $this->id]);
For more information on where(), you can view the API page.

Method Chaining based on condition

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

Categories