Laravel Query Builder - where clause equals anything programmatically - mysql

I'm using Laravel 5.6 - Query Builder.
Is it possible to make a query builder where statement that a value equals everything programmatically?
Let's say that I have this code:
$foo = 1;
DB::table('users')
->select('*')
->where('status', '=', $foo)
->get();
If $foo = 1 then it's straightforward. The query will select everything with the status of 1.
Q: Is it possible to assign something to the $foo variable so the select query returns every record regardless of the status from the DB?
Of course, I can make it happen with 2 query statements like this:
$foo = 1;
if ($foo === null) {
DB::table('users')
->select('*')
->get();
} else {
DB::table('users')
->select('*')
->where('status', '=', $foo)
->get();
}
However, I'm looking for a shorter / more effective solution. Is it possible somehow - without using raw code inside the Where statement?

You may try something like this:
$query = DB::table('users')->select('*');
// $foo = 'get it...';
if ($foo) {
$query->where('status', $foo);
}
$result = $query->get();
Or even more laravel-ish:
$result = DB::table('users')->select('*')
->when($foo, function ($query) use ($foo) {
return $query->where('status', $foo);
})
->get();
Check more here.

Related

how to add conditional where clause in sql

Looking for improved answer
In Laravel, I am using a raw query. My question is how to add where clause depending on variable value
i.e. if $cid is present then the query should be
select * from user where aid=2 and cid=1;
If it is not present
select * from user where aid=2;
Ideally, I can do it like this
if($cid) {
$query = DB::select("select * from user where aid=2 and cid=1");
} else {
$query = DB::select("select * from user where aid=2");
}
Is there any way to do this without the above method?
This can be achieved with conditional clauses.
$users = DB::table('users')
->where('aid', 2)
->when($cid, function ($query) {
$query->where('cid', 1);
})
->get();
Please contextualize your question well, we don't know what kind of condition you are talking about, nor in what sense your question is asked.
normally the comment above would be enough but it is necessary to specify
Here are some examples from the documentation
$users = DB::table('users')
->where('votes', '=', 100)
->where('age', '>', 35)
->get();
$users = DB::table('users')->where('votes', 100)->get();
You may also pass an array of conditions to the where function. Each element of the array should be an array containing the three arguments typically passed to the where method:
$users = DB::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();
I encourage you to read the documentation which is very clear on this subject and to come back to me in case of misunderstanding
here

how to make if statement in the laravel query builder

I have the following SQL query
$query
->join('cities','tickets.city_id','=','cities.id')
->select(
'tickets.id',
'tickets.biker_id',
'tickets.picked_up',
'tickets.delivered',
'tickets.service_charge',
'tickets.amount',
'tickets.cancelled',
'tickets.pre_order',
'tickets.created_by',
'tickets.created_at'
)
->whereDay('tickets.created_at',Date('d'))
->orderBy('tickets.created_at','desc')
->get();
my aim is to set the
whereday('tickets.created_at', Date('d'))
to
whereday('tickets.created_at', Date('d', strtotime("-1 day")))
whenever the tickets.pre_order = 1
but when tickets.pre_order = 0 i will stick to the
whereday('tickets.created_at',Date('d'))
is it possible using if statement or is there any better way to solve this?
make it like this
->where(function ($query){
$query->where('tickets.created_at', Carbon::now()->subDays()->format('d'))
->where('tickets.pre_order',1);
})->orWhere(function ($query){ $query->where('tickets.created_at',
Carbon::now()->format('d')) ->where('tickets.pre_order',0); })
->get();
To subtract a day and format it, use Carbon library for DateTime in PHP (as given in comments by #spartyboy )
$query
->join('cities','tickets.city_id','=','cities.id')
->select(
'tickets.id',
'tickets.biker_id',
'tickets.picked_up',
'tickets.delivered',
'tickets.service_charge',
'tickets.amount',
'tickets.cancelled',
'tickets.pre_order',
'tickets.created_by',
'tickets.created_at'
)
->where(function ($query) {
$query
->where('tickets.pre_order', 0)
->whereDay('tickets.created_at', Date('d'));
})
->orWhere(function ($query) {
$query
->where('tickets.pre_order', 1)
->whereDay('tickets.created_at', Carbon::yesterday()->format('d'));
})
->orderBy('tickets.created_at','desc')
->get();
or if you want to subtract multiple days then
instead of yesterday() use now()->subDays($days_count)

Query builder proper sintax for 4 joins + 3 where clauses (Laravel5.7)

I'm trying to get this MySQL query to work in laravel 5.7 query builder.
It works fine in phpmyadmin
SELECT c.Symbol
, s.SectorName
, cprs.strenght
, s.parentid
, ssbpi.Risklevel
, ssbpi.ColumnType
FROM Companies AS c
JOIN Sectors AS s ON s.SectorID = c.SectorID
JOIN Company_PriceRS AS cprs ON cprs.CompanyID = c.CompanyID
JOIN SubSectorsBPIsData AS ssbpi ON ssbpi.subcategoryid = s.parentid
WHERE cprs.PostDate = '2017-05-08'
AND WHERE CompanyPriceRS.strenght = 'strong'
AND WHERE SubSectorsBPIsData.ColumnType = $ColumnType
ColumnType is a variable that comes from a dropdown and it's already being captured and working properly.
I have tried the normal way according to documentation:
$Completequerytry1 = DB::table('Companies')
->join('Sectors', 'Sectors.SectorID', '=', 'Companies.SectorID')
->join('CompanyPriceRS', 'CompanyPriceRS.CompanyID', '=', 'Companies.CompanyID')
->$join('SubSectorsBPIsData ', 'SubSectorsBPIsData.subcategoryid', '=', 'Sectors.parentid')
->where('CompanyPriceRS.strenght', '=', 'strong')
->where('SubSectorsBPIsData.ColumnType', '=', $ColumnType)
->where('CompanyPriceRS.Postdate', '=', '2017-05-08');
->select('Companies.Symbol', 'Sectors.SectorName', 'CompanyPriceRS.strenght', 'Sectors.parentid', 'SubSectorsBPIsData.subcategoryid','SubSectorsBPIsData.ColumnType')
->limit(10);
->select('Companies.Symbol', 'Sectors.SectorName', 'CompanyPriceRS.strenght', 'Sectors.parentid', 'SubSectorsBPIsData.subcategoryid','SubSectorsBPIsData.ColumnType')
->limit(10);
echo '<pre>';
print_r($Completequerytry1);
Error:
Symfony\Component\Debug\Exception\FatalThrowableError thrown with message "syntax error, unexpected '->' (T_OBJECT_OPERATOR)"
Using functions With several nested joins:
$Completequerytry1 = DB::table('Companies')
->join('Sectors', function ($join) use ($ColumnType) {
$join->on('Sectors.SectorID', '=', 'Companies.SectorID')
->join('CompanyPriceRS', function ($join2) {
$join2->on('CompanyPriceRS.CompanyID', '=', 'Companies.CompanyID')
->join('SubSectorsBPIsData', function ($join3) {
$join3->on('SubSectorsBPIsData.subcategoryid', '=', 'Sectors.parentid')
->where(function ($query1) {
$query1->where('CompanyPriceRS.strenght', '=', 'strong') //filter 1
->where('SubSectorsBPIsData.ColumnType', '=', $ColumnType) //filter2
->where('CompanyPriceRS.Postdate', '=', '2017-05-08'); // filter 3
});
});
});
})
->select('Companies.Symbol', 'Sectors.SectorName', 'CompanyPriceRS.strenght', 'Sectors.parentid', 'SubSectorsBPIsData.subcategoryid','SubSectorsBPIsData.ColumnType')
->limit(10);
echo '<pre>';
print_r($Completequerytry1);
Error:
ErrorException (E_NOTICE)
Undefined variable: ColumnType
3: Then tried functions with nested WHERE
$Completequerytry1 = DB::table('Companies')
->join('Sectors', 'Sectors.SectorID', '=', 'Companies.SectorID')
->join('CompanyPriceRS', 'CompanyPriceRS.CompanyID', '=', 'Companies.CompanyID')
->$join('SubSectorsBPIsData ', 'SubSectorsBPIsData.subcategoryid', '=', 'Sectors.parentid') //ERROR IS GIVEN ON THIS LINE
->where(function ($query1) {
$query1->where('CompanyPriceRS.strenght', '=', 'strong')
->where('SubSectorsBPIsData.ColumnType', '=', $ColumnType)
->where('CompanyPriceRS.Postdate', '=', '2017-05-08');
});
->select('Companies.Symbol', 'Sectors.SectorName', 'CompanyPriceRS.strenght', 'Sectors.parentid', 'SubSectorsBPIsData.subcategoryid','SubSectorsBPIsData.ColumnType')
->limit(10);
echo '<pre>';
print_r($Completequerytry1);
Error:
Undefined variable: join
Still don't know what i'm missing.
Should i create functions for the JOINs and the WHEREs ?
Running out of ideas. Thanks in advance for your insights :)
It turns out that the query was being sent to a variable directly from the controller, not to the view.
I was doing this only for testing but it was using too much memory with print_r(); function making impossible to get a result. Even when using dd(); i wasn't getting what i wanted (I think it's because some sintax errors i had).
So i passed the final variable to the view and it works fine since laravel could handle the data differently.
Also i used ->limit(10); to split the results and avoid memory overload.
Here is the final code working:
$Completequerytry1 = DB::table('Companies')
->join('Sectors', 'Sectors.SectorID', '=', 'Companies.SectorID')
->join('Company_PriceRS', 'Company_PriceRS.CompanyID', '=', 'Companies.CompanyID')
->join('SubSectorsBPIsData', 'SubSectorsBPIsData.subcategoryid', '=', 'Sectors.parentid')
->select('Sectors.SectorName', 'Companies.Symbol', 'Company_PriceRS.strenght', 'Sectors.parentid', 'SubSectorsBPIsData.Risklevel','SubSectorsBPIsData.ColumnType')
->where('Company_PriceRS.strenght', '=', 'strong')
->where('SubSectorsBPIsData.ColumnType', '=','X')
->where('Company_PriceRS.Postdate', '=', '2017-05-08')
->limit(10)
->get();
return view('besttrades2', array('Completequerytry1' => $Completequerytry1)); //sending my query variable to the view
Then in the view only used:
<?= $Completequerytry1; ?>
or show it in whatever way you want.
Sometimes it's better to have another project only for testing separately.

Laravel Condition based sql query

I have three models which are joined. I need to get workspace_members table details only when inventory.status is 1(i.e active).
How can I write that condition in larvel eloquent. Below is my query. Thanks in advance.
$data['inventories'] = Inventory::
Join('category_info','inventory.category_id','=','category_info.category_id')
->leftJoin('workspace_member_inventory', 'inventory.inventory_id', '=', 'workspace_member_inventory.inventory_id')
->leftJoin('workspace_members','workspace_member_inventory.member_id','=','workspace_members.member_id')
->where('inventory.workspace_id', '=', $workspace_id)
->select('inventory.*', 'workspace_member_inventory.member_id','workspace_members.*','category_info.category_name', 'inventory.status as status')
->get()
->toArray();
I don't know if I understood but I think that you are looking for Laravel Query Scopes
Write the scope on your Inventory model:
public function scopeIsActive($query,$status = null){
if(!is_null($status)){
if($status == 1){
return $query->leftJoin('workspace_members','workspace_member_inventory.member_id','=','workspace_members.member_id')->where('inventory.status',1);
}else{
return $query->where('inventory.status',0);
}
}else{
return $query;
}
}
Then add it to your query:
$data['inventories'] = Inventory::
Join('category_info','inventory.category_id','=','category_info.category_id')
->leftJoin('workspace_member_inventory', 'inventory.inventory_id', '=', 'workspace_member_inventory.inventory_id')
->where('inventory.workspace_id', '=', $workspace_id)
->isActive(1)
->select('inventory.*', 'workspace_member_inventory.member_id','workspace_members.*','category_info.category_name', 'inventory.status as status')
->get()->toArray();

Laravel SUBSTRING on Eloquent query

Question
How do I put a limit on one of the rows in an Eloquent result?
Scenario
I need to retrieve only around 100 characters from one of the fields in my result. Currently I'm using a join statement so multiple results are being returned. I basically need only the first 100 characters from post.content
Code
public function getAll()
{
return Post::select('posts.id', 'posts.title', 'posts.content', 'posts.views', 'posts.comments', 'posts.tags', 'posts.date_created', 'users.image_url', 'users.username', 'users.toxick')
->join('users', 'posts.user_id', '=', 'users.id')
->get();
}
I'm not sure how to go about putting a filter on the query to only return 100 characters. I've looked around briefly but I've not found anything useful, not to my specific scenario at least.
Cant test this at the moment (sorry) but what about:
public function getAll(){
$query = Post::select('posts.id', 'posts.title', 'posts.content','posts.views', 'posts.comments', 'posts.tags', 'posts.date_created', 'users.image_url', 'users.username', 'users.toxick')
->join('users', 'posts.user_id', '=', 'users.id')
->get();
foreach($query as $entries){
$entries->content = substr($entries->content, 1, 100);
}
return $query;
}