We sometimes require to use MySQL pre-define function like sum(), date_format(), year(), month(), group_concat() etc. But laravel query builder not provide to directly use with select statement. However, we can use all the pre-define function of Mysql using DB::raw().
So, In this post i am going to share with you how to use date_format() in Laravel 5 Query Builder. date_formt() help us to change date format. We may sometimes require to change date format using mysql date_format().
In this example i have simple "users" table and there are some dummy users with created_at row with current time.....
Sometimes we require to make subquery inside the select statement in Laravel. At that time we are thinking how to select from subquery using in Laravel Query Builder.
In this post i will give you example of subquery in select statement in Laravel 5 application from scratch. For subquery in select statement we are going to use <strong class="path">DB::raw()</strong>. DB raw function through we can simply make suquery join in Laravel Eloquent Query Builder.
Here as bellow full example, i have three tables as listed bellow:
If you require to get all the records of current year using mysql query. for example you have one table "items" and columns are id, title, description, created_at and update_at, Now you want to get all records of this year. so you can fetch fields value using DATE_SUB and INTERVAL of mysql. In following example you can see how to select data of current year.
SELECT * FROM items WHERE created_at > DATE_SUB(NOW(), INTERVAL 1 YEAR);
Sometimes, we require to get age from birthdate using mysql select query, we can do it in programming like php,.net and etc framework but if we can do it using mysql query. In bellow example mysql query you can learn how to get age from date field. We can get age value from using mysql DATEDIFF(). So, let's see bellow query.
(DATEDIFF(CURRENT_DATE, STR_TO_DATE(born_date, '%Y-%m-%d'))/365) as age