Laravel where :: model, how to add multi statement - php

So how i can add multi statement to query in ::where model.
Actually it lok like that:
certs::where('unique', '=', $newUnique )->get()
i need somethig like that:
certs::where('unique, num', '=', $newUnique,$key )->get()
so in sql look like that
Select * From certs Where unique = $newUnique AND num = $key
I need that to check if data need to be updated or inserted.

Just append another where clause
certs::where('unique', $newUnique)->where('num', $key)->get()
For example
App\User::where('first_name', 'John')->where('last_name', 'Doe')->toSql();
Would result in
"select * from `users` where `first_name` = ? and `last_name` = ?"
Hope this helps

It can become tricky if there will be OR instead of AND, so you should always prefer
for AND
Certs::where(function($query) use ([$newUnique, $key]){
$query->where('first_name', 'John')->where('last_name', 'Doe');
})->get();
for OR
Certs::where(function($query) use ([$newUnique, $key]){
$query->where('first_name', 'John')->orWhere('last_name', 'Doe');
})->get();

Laravel allows multi statements for "where" function of Model by passing array of conditions.
The below code can be used if you are applying "and" condition and "=" operation for each data.
$conditions = ['unique'=>$newUnique,'num'=>$key];
Certs::where($conditions)->get();
Else if you want to use different operations with "and" condition, use below code.
$conditions = [
['unique','=',$newUnique],['num','!=',$key]
];
Certs::where($conditions)->get();
Also, you can use below code for "and" and "or" conditions.
Certs::where(function($query) use ($newUnique, $key]){
$query->where('unique', $newUnique);
$query->orWhere('num', $key);
})->get();
Similarly, you can use orWhere(), whereColumn(), whereBetween() and other query builder functions.

You can do something like this:
certs::where(['unique'=>$newUnique, 'num' => $key])->get()

Related

WhereIn Inside ->where() array - Laravel Query Builder

I'm trying use a whereIn inside a where array I am passing to Laravel query Builder:
$where = [['Participants.Client_Id','IN', $clientId]];
DB::table('Participants')->where($where)->get()
Something like is what I want to achieve, and I know there are works around such as using whereIn, but I'm sharing here a small piece of code to give you an idea, so I need to change the array to make it works as a whereIn, not changing the ->where to ->whereIn or ->whereRaw
DB::table('participants)->whereIn('Participants.Client_Id',$clientId)->get();
You must collect the IDs in the $clientId variables.
If I understand, you could do something like that :
$wheres = [['Participants.Client_Id','IN', [$clientId]]];
$query = DB::table('Participants');
foreach($wheres as $where) {
$query->where($where[0], $where[1], $where[2]);
}
$participants = $query->get();
As laravel document , you can use array in where and each element of this array must be a array with three value . So your $where variable is correct.
But as I searched in operator is not supported by query builder of where.

Need help for my sql query to make use of AS operator [duplicate]

Lets say we are using Laravel's query builder:
$users = DB::table('really_long_table_name')
->select('really_long_table_name.id')
->get();
I'm looking for an equivalent to this SQL:
really_long_table_name AS short_name
This would be especially helpful when I have to type a lot of selects and wheres (or typically I include the alias in the column alias of the select as well, and it gets used in the result array). Without any table aliases there is a lot more typing for me and everything becomes a lot less readable. Can't find the answer in the laravel docs, any ideas?
Laravel supports aliases on tables and columns with AS. Try
$users = DB::table('really_long_table_name AS t')
->select('t.id AS uid')
->get();
Let's see it in action with an awesome tinker tool
$ php artisan tinker
[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});
// NULL
[2] > DB::table('really_long_table_name')->insert(['id' => null]);
// true
[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
// array(
// 0 => object(stdClass)(
// 'uid' => '1'
// )
// )
To use aliases on eloquent models modify your code like this:
Item
::from( 'items as items_alias' )
->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
->select( DB::raw( 'items_alias.*' ) )
->get();
This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result.
Adding DB::raw prevents laravel from adding table prefixes to aliases.
Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.
$products = DB::table('products AS pr')
->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
->orderBy('pr.id', 'desc')
->get();
Hope this helps.
To use in Eloquent.
Add on top of your model
protected $table = 'table_name as alias'
//table_name should be exact as in your database
..then use in your query like
ModelName::query()->select(alias.id, alias.name)
You can use less code, writing this:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name'));
And of course if you want to select more fields, just write a "," and add more:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));
This is very practical when you use a joins complex query
I have tried all these options and none works for me. Then I had found something in the Laravel documentation that really works.
You could try this:
DB::table('table_one as t1')
->select(
't1.field_id as id','t2.field_on_t2 as field'
)->join('table_two as t2', function ($join) {
$join->on('t1.field_id ', '=', 't2.field_id');
})->get()
Also note that you can pass an alias as the second parameter of the table method when using the DB facade:
$users = DB::table('really_long_table_name', 'short_name')
->select('short_name.id')
->get();
Not sure if this feature came with a specific version of Laravel or if it has always been baked in.
Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'",
just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')
In the latest version of Laravel 9, you can use alias name for column as:
$events = Booking::whereBetween('sessionDateTime', [$today, $nextMonth])->get(['bookings.sessionDateTime as start']); // start is an alias here

Multiple where conditions with 'AND' & 'OR' operators in laravel

in my laravel controller i'm trying to perform the following query for the user search.
$data = User::orderBy('id','DESC')
->where('email','LIKE','%'.$request->search."%")
->orwhere('first_name','LIKE','%'.$request->search."%")
->orwhere('last_name','LIKE','%'.$request->search."%")
->WHERE('role_id','=','3')
->paginate(12);
return view('admins.participants.results',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 12 );
What I really want to perform is,
SELECT * FROM USERS WHERE role_id='3' AND email LIKE '%search_string%' OR first_name LIKE '%search_string%' OR last_name LIKE '%search_string%' ;
But the above laravel query outputs all the users without considering the `role_id=3
You can use where callback
$data = User::orderBy('id','DESC')
->where('role_id',3)
->where(function($query)use($request){
$query->where('email','LIKE','%'.$request->search."%");
$query->orwhere('first_name','LIKE','%'.$request->search."%");
$query->orwhere('last_name','LIKE','%'.$request->search."%");
})->paginate(12);
also you can change
'%'.$request->search."%"
to
"%{$request->search}%"
You need to pass OR clauses to a Closure to group them, otherwise the query doesn't really understand which clauses are optional and which are not.
$data = User::orderBy('id','DESC')
->where('role_id','=','3')
->where(function($query) use ($request) {
$query->where('email','LIKE','%'.$request->search."%")
->orwhere('first_name','LIKE','%'.$request->search."%")
->orwhere('last_name','LIKE','%'.$request->search."%");
})
->paginate(12);

Laravel Query Builder: MySQL 'LIKE' inside a multiple where conditioned query

Im trying to do a query where i have multiple conditions (including %LIKE% operator) but can't figure how to do it in Laravel's array way with query builder.
$where = ['category' => $c->id, 'name' => $c->name];
$q = Store::where($where)->get();
That way it would return an array of objects with the equal of the name, not the similar matches. Is it possible to do a %LIKE% search in that way?
You should chain them like this:
DB::table('your-table-name')
->where('category','=','$c->id')
->where('name','=','$c->name')
->where('email', 'LIKE', '%test%')
->get();

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Lets say we are using Laravel's query builder:
$users = DB::table('really_long_table_name')
->select('really_long_table_name.id')
->get();
I'm looking for an equivalent to this SQL:
really_long_table_name AS short_name
This would be especially helpful when I have to type a lot of selects and wheres (or typically I include the alias in the column alias of the select as well, and it gets used in the result array). Without any table aliases there is a lot more typing for me and everything becomes a lot less readable. Can't find the answer in the laravel docs, any ideas?
Laravel supports aliases on tables and columns with AS. Try
$users = DB::table('really_long_table_name AS t')
->select('t.id AS uid')
->get();
Let's see it in action with an awesome tinker tool
$ php artisan tinker
[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});
// NULL
[2] > DB::table('really_long_table_name')->insert(['id' => null]);
// true
[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
// array(
// 0 => object(stdClass)(
// 'uid' => '1'
// )
// )
To use aliases on eloquent models modify your code like this:
Item
::from( 'items as items_alias' )
->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
->select( DB::raw( 'items_alias.*' ) )
->get();
This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result.
Adding DB::raw prevents laravel from adding table prefixes to aliases.
Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.
$products = DB::table('products AS pr')
->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
->orderBy('pr.id', 'desc')
->get();
Hope this helps.
To use in Eloquent.
Add on top of your model
protected $table = 'table_name as alias'
//table_name should be exact as in your database
..then use in your query like
ModelName::query()->select(alias.id, alias.name)
You can use less code, writing this:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name'));
And of course if you want to select more fields, just write a "," and add more:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));
This is very practical when you use a joins complex query
I have tried all these options and none works for me. Then I had found something in the Laravel documentation that really works.
You could try this:
DB::table('table_one as t1')
->select(
't1.field_id as id','t2.field_on_t2 as field'
)->join('table_two as t2', function ($join) {
$join->on('t1.field_id ', '=', 't2.field_id');
})->get()
Also note that you can pass an alias as the second parameter of the table method when using the DB facade:
$users = DB::table('really_long_table_name', 'short_name')
->select('short_name.id')
->get();
Not sure if this feature came with a specific version of Laravel or if it has always been baked in.
Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'",
just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')
In the latest version of Laravel 9, you can use alias name for column as:
$events = Booking::whereBetween('sessionDateTime', [$today, $nextMonth])->get(['bookings.sessionDateTime as start']); // start is an alias here

Categories