How to select min and max in laravel - laravel

I want to convert this code in laravel.
SELECT MAX(date_start) AS DateStart,MIN(date_end) AS DateEnd FROM DBTest
And I try this code
$data = DB::table('DBTest')
->select(max('date_start'), min('date_end')))
->get();
Return Error: max(): When only one parameter is given, it must be an array
I am using laravel 5.2, and SQLyog as database
I am confuse in syntax please help me

You can't use functions in select statement, but you can use raw SQL :
$data = DB::table('DBTest')
->select(\DB::raw('MIN(date_start) AS DateStart, MAX(date_end) AS DateEnd'));
->get();

You can do it like this:
For the max start date:
max = DB::table('DBTest')->select('date_start')->orderBy('date_start', 'desc')->first();
For min end date:
min = DB::table('DBTest')->select('date_end')->orderBy('date_end', 'asc')->first();

You have to use something called selectRaw method in Laravel in order to achieve this result. Chaining method like ->max('columnA')->min('columnB') will not work. So, here is the solution:
$data = DB::table('DBTest')
->selectRaw('MAX(date_start) AS DateStart, MIN(date_end) AS DateEnd')->get();

Try MIN() and MAX() functions in the sql query.
$data = DB::table('DBTest')
->select(\DB::raw('MIN(date_start) AS startDate, MAX(date_end) AS endDate'));
->get();

Related

db::raw adding is null in query

I am trying to use laravel query builder like:-
$users = DB::table('baid_collection')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->where(DB::raw("assigned_user_id = '$userId' and DATE(date_entered)=CURDATE()"))
->groupBy('assigned_user_id')
->get();
This query should be like
select sum(total) as total_collect,collection_limit_c from `baid_collections` inner join `users_cstm` on `baid_collections`.`assigned_user_id` = `users_cstm`.`id_c` where assigned_user_id = '15426608-3ea5-f299-7a80-601bd06be2d9' and DATE(date_entered)=CURDATE() group by `assigned_user_id`
But last run query showing me
select sum(total) as total_collect,collection_limit_c from `baid_collection` inner join `users_cstm` on `baid_collections`.`assigned_user_id` = `users_cstm`.`id_c` where assigned_user_id = '15426608-3ea5-f299-7a80-601bd06be2d9' and DATE(date_entered)=CURDATE() is null group by `assigned_user_id`
In query is null giving problem i dont want is null in query
Use whereRaw instead of where like
$users = DB::table('baid_collections')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->whereRaw("assigned_user_id = '{$userId}' and DATE(date_entered)=CURDATE()")
->groupBy('assigned_user_id')
->get();
It's creating a problem due to where needs atleast two parameters and you are just passing one parameter
Check this if it helps, write whereDate instead of add date in raw query.
if you are not using Carbon, you can also use php date("Y-m-d"), method to get date
DB::table('baid_collection')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->where(DB::raw("assigned_user_id = '$userId'"))
->whereDate("date_entered", "=", Carbon::now()->toDateString())
->groupBy('assigned_user_id')->get();
You can try this
$users = DB::table('baid_collection')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->where(DB::raw("assigned_user_id = '$userId' and DATE(date_entered) = '".date('Y-m-d')."'"))
->groupBy('assigned_user_id')
->get();

How to use search value contain in array field using eloquent in Laravel

I'm working on laravel array serialize. Below is serialize in controller.
public function CreateSave(CreateTestTopicRequest $request){
...code..
$testtopic->class_room_id = $request->classroom;
$testtopic->roomno = serialize($request->roomno);
...code..
}
Then, roomno will be saved to database like.
a:2:{i:0;s:1:"1";i:1;s:1:"2";}
I would like to get result. For example class_room_id = 1 and roomno only contain in roomno array. I may use command to get all as below.
$testtopics = TestTopic::where('class_room_id',1)->get();
But, I do not know to get record only class_room_id = 1 and roomno contain in array. Any advice or guidance on this would be greatly appreciated, Thanks
You can use like search in json fields
TestTopic::where('class_room_id',1)->where('roomno', 'like', '%"id": 1%')->first()
When checking for an array of values the whereIn method can be used:
$roomno = 'a:2:{i:0;s:1:"1";i:1;s:1:"2";}';
$testtopics = TestTopic::where('class_room_id',1)
->whereIn('roomno', unserialize($roomno))
->get();
Multiple where statements can be combined by passing an array:
$roomno = 'a:2:{i:0;s:1:"1";i:1;s:1:"2";}';
$users = TestTopic::where([
['class_room_id', '=', '1'],
['roomno', '=', $roomno],
])->get();

What is the equivalent query of laravel on this?

This is the native sql:
$sql = "Select count(name) from users Where email = 't#t.com' and user_id = 10";
I have this laravel code:
$checker = Customer::whereEmailAndUserId("t#t.com",10)->count("name");
Is this a correct way to do it in laravel?
You have to use where helper function and pass an array of checks. For example in your code it will be:
$checker = Customer::where([
['email', '=', 't#t.com'],
['user_id' '=', '10']
])->count();
Note: Please use the appropriate column name as it in table.
Assuming Customer model represents table users, you'll get query with eloquent like this:
Customer::where('email', 't#t.com')->where('user_id', 10)->select(\DB::raw('count(name)'))->get();
The option you are trying is incorrect
here is the right option
$users = \App\Customer::where('email','t#t.com')
->where('user_id',10)
->count()
Explanation of above code
App\Customer is the Model class and I am trying to read records where email = 't#t.com you can use various comparison operators like <,> and so on and you can also use the same function to for string pattern matching also
Eg.
$users = \App\Customer::where('email','%t.com')
->where('user_id',10)
->count()
You can use the same where function for Null Value test also
Eg.
$users = \App\Customer::where('email','=', null)
->where('user_id',10)
->count()
The above where clause will be converted to is null test of the SQL
You can read more here

Order by is not working?

I have a problem with order by articles by priority. Where is working. Any suggestion?
$articles = Articles::whereHas('priority',function($query){
$query->orderBy('order','asc');
// $query->where('order','=',1);
})->limit(7)->get();
You have to use join to fetch the articles by the order of related table column as:
Articles::join('priority', 'articles.id', '=', 'priorities.article_id')
->orderBy('priorities.order','asc')
->select('articles.*')
->limit(7)
->get();
You can do the following:
$quotes=Articles::orderBy('priority', 'desc')->limit(7)->get();
Try this code
$articles = Articles::orderBy('order','desc')->limit(7)->get();
and if you want to add a condition you can use somthing like this:
$articles = Articles::join('priorities','articles.id','=','priorities.articale_id')->where('priority',1)->orderBy('order','desc')->limit(7)->get();

Laravel Date comparison not working in Eloquent query

I do not understand why but following query return null resultset.
due_date is Carbon date and $now=Carbon:today();
$subQuery = BillTable::where('busi_id', $business->busi_id)
->where('due_date','>=',$now)
->where('due_date','<',$now->addMonth())
->get();
Also when I use whereBetween it doesn't work.
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[$now, $now->addMonth()])
->get();
But when I just to greater than or lesser than it works
$subQuery = BillTable::where('busi_id', $business->busi_id)
->where('due_date','>',$now->addWeek())
->get();
What am I missing here?
The problem here is that you are using the same instance for both range limits. When you call addMonth you add the month to the instance stored in $now. The two examples below illustrate the issue:
1. Using and modifying the same variable in two separate statements works as you'd expect:
$now = Carbon::now();
dump($now); // prints 2015-12-12 14:50:00.000000
dump($now->addMonth); // prints 2016-01-12 14:50:00.000000
2. Using the same variable and modifying it in the same statement that passes the values to a method, will work differently, because it will be evaluated before being passed to the method. Meaning that both parameters will be equal because they both contain the same instance from the $now variable, which after getting evaluated will contain the DateTime of one month from now.
$now = Carbon::now();
// Calling `addMonth` will change the value stored in `$now`
dump($now, $now->addMonth());
// The above statement prints two identical DateTime values a month from now:
// 2016-01-12 14:50:00.000000 and 2016-01-12 14:50:00.000000
This means that your current code was checking if the entries were due only exactly one month from now.
To fix it you need to use two instances in two separate variables:
$from = Carbon::now();
$to = Carbon::now()->addMonth();
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[$from, $to])
->get();
It looks like it is because I used '$now' in the query.
Like is said before the query I did $now=Carbon::today(); and use $now in the query.
But then I got rid of that and changed the query to use Carbon::today() it worked.
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[Carbon::today(), Carbon::today()->addMonth())
->get();
It is weird.
Thanks,
K

Resources