Raw query to Laravel Query - mysql

Raw query to Laravel Query
SELECT * FROM plans_subscriptions WHERE starts_on BETWEEN "2019-07-30" AND "2019-07-26" or expires_on BETWEEN "2019-07-20" AND "2019-07-22"

If you want object response then use this :
PlansSubscriptions::whereBetween('starts_on', ["2019-07-30", "2019-07-26"]);
->orWhereBetween('expires_on', ["2019-07-20", "2019-07-22"]);
->get();
If you want array response then use this :
PlansSubscriptions::whereBetween('starts_on', ["2019-07-30", "2019-07-26"]);
->orWhereBetween('expires_on', ["2019-07-20", "2019-07-22"]);
->get()->toArray();
We can format the date like this :
$start = date("Y-m-d",strtotime($request->input('from_date')));
$end = date("Y-m-d",strtotime($request->input('to_date')));
and use that variable in query like this:
PlansSubscriptions::whereBetween('starts_on', [$start, $end]);
->orWhereBetween('expires_on', ["2019-07-20", "2019-07-22"]);
->get()->toArray();

PlansSubscriptions::whereBetween('starts_on', ["2019-07-30", "2019-07-26"]);
->orWhereBetween('expires_on', ["2019-07-20", "2019-07-22"]);
->get();

Check this,
$users = DB::table('plans_subscriptions')
->where(function ($query){
$query->whereBetween('starts_on', ['2019-07-30', '2019-07-26'])
->orWhereBetween('starts_on', ['2019-07-20', '2019-07-22']);
})
->get();

Related

Laravel 8: Call to database function

I'm using a Laravel 8 for website developement, and on the next part of code, I execute a query:
$assig = DB::table('table')
->where('table.column', '=', "oneValue")
->select('anfunctionOnDatabase(2,table.columDesc)')
->get();
but it no works.
How I need call to database function on laravel?
Thanks
Use selectRaw()
like this;
$assig = DB::table('table')
->where('table.column', '=', "oneValue")
->selectRaw('anfunctionOnDatabase(2,table.columDesc)')
->get();
Use : DB::raw :
$assig = DB::table('table')
->where('table.column', '=', "oneValue")
->select(DB::raw("anfunctionOnDatabase(2,table.columDesc)"))
->get();

Laravel Eloquent model JSON output format

my problem is about the JSON format I recieve when sending a query to the database.
The output I want:
[{"errors":[{"something":"something"}],"created_at":"2020-10-20 10:10:10","name":"something","id":99}]
I get :
[{"id":99,"name":"something","device_results":[{"devices_id":99,"created_at":"2020-10-20 10:10:10","errors":[{"something":"something"}]}]}]
Which I get with:
public function errors()
{
$errors = DB::table('devices')
->join('device_results', 'devices.id', '=', 'device_results.devices_id')
->select('errors', 'created_at', 'name', 'device_results.id')
->orderBy('created_at', 'desc')
->whereJsonLength('errors', '>', 0)
->get();
return $errors;
}
I would like to get the same results with using my model because if I do this:
public function errors()
{
$devices = Devices::with(['device_results' => function($query) {
$query->select('device_results.devices_id','created_at','errors')
->whereJsonLength('errors', '>', 0)
->orderBy('created_at', 'desc')
->get();
}])->get();
return $devices;
}
Is it always in this format or can I use the model and get the same format as with the DB class? I am using Vue for the front end and would like to avoid nesting.
Thank you
Have you tried to create a Resource ?
The doc : https://laravel.com/docs/8.x/eloquent-resources

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)

orWhere with multiple conditions in Eloquent

I am looking to write the following query in eloquent:
select * from stocks where (symbol like '%$str%' AND symbol != '$str' ) OR name like '$str%'
Without the last condition, it's simple:
$stocks = Stock::live()
->where('symbol','like','%'.$str.'%')
->where('symbol','!=',$str)
->get();
But adding orWhere('name','like',$str.'%') after the two wheres returns incorrect results. Basically I am wondering how to emulate what I accomplished by using the (condition1 AND condition2) OR condition3 syntax in the raw query above.
Try
$stocks = Stock::live()
->where('name', 'like' , '%'.$str.'%')
->orWhere(function($query) use($str) {
$query->where('symbol','like','%'.$str.'%')
->where('symbol','!=',$str); // corrected syntax
})->get();
Try
$stocks = Stock::live()->where('name', 'like' , '%'.$str.'%')
->orWhere(function($query) use($str) {
$query->where('symbol','like','%'.$str.'%')
->where('symbol','!=',$str)
})->get();
I didn't test this, so sorry if it doesn't work. But I think one of these solutions could work.
$stocks = Stock::live()
->where([
['symbol','like','%'.$str.'%'],
['symbol', '!=', $str],
])
->orWhere('name','like', $str.'%')
->get();
and
->where(function ($query) use ($str) {
$query->where([
['symbol','like','%'.$str.'%'],
['symbol', '!=', $str],
]);
})
->orWhere(function ($query) use ($str) {
$query->where('name','like', $str.'%');
});

Laravel Query Builder - where clause equals anything programmatically

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.