Retrieve data between dates in laravel - laravel

I am using an eloquent query to retrieve data from a table. The table columns look like this:
id started_at finished_at
1 06/02/2019 06/15/2019
2 06/05/2019 06/11/2019
What I want to do is, given a $date (ex: 06/08/2019 ) and get the data of the row, that the $date between started at and finished_at columns.

DB::table('table_name')->whereBetween('started_at', [$date1, $date2])
->orWhereBetween('finished_at', [$date1, $date2])->get();

$date = date('Y-m-d',strtotime($started_at));
$data = Model::where('started_at', '>', $date)->where('finished_at', '<', $date)->first();

Try this
$data = Model::where('started_at', '<', $date)->where('finished_at', '>', $date)->first();

Related

Data is not coming in laravel 5.4 after using timestamp in query

Data is not coming when comparing current time between 2 times to fetch data in Laravel. Both times are saved in the database as timestamp and in query also I am using timestamp. Below is the code i wrote:-
$current_date = strtotime(date('d-m-Y H:i:s'));
$bookings = MachineBooking::with('userDetail')->where('machine_id', $machine_id)->where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)->get();
"time_from" and "time_to" both timestamps are saved in bigint format in database. I entered timestamp using search option in direct database also still data did not come. Can someone please tell me where i am making mistake.
I think you should swap the time_from to <= and time_to to >, and try
$bookings = MachineBooking::with('userDetail')
->where('machine_id', $machine_id)
->where('time_from', '<=', $current_date) # changed
->where('time_to', '>', $current_date) # changed
->get();
You not describe what database you use. But maybe you can change to Y-m-d H:i:s format:
$current_date = strtotime(date('Y-m-d H:i:s'));
but strtotime is return int not bigint.
I hope I will help you
firstly You must cast the date in Model MachineBooking
protected $casts = ['time_from' => 'datetime:Y-m-d H:i:s',time_to =>'datetime:Y-m-d H:i:s'];
secondly
cast current date with same format of time_from and time_to
$current_date = strtotime(date('Y-m-d H:i:s'));
Please change your code with:
$current_date = strtotime(date('Y-m-d H:i:s'));
time_from and time_to are formatted date not a int . But your $current_date is int with using strtotime method
Just take strtotime method:
$current_date =date('d-m-Y H:i:s');
$bookings = MachineBooking::with('userDetail')->where('machine_id', $machine_id)->where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)->get()

Laravel gives me a duplicate collection data

I want to sort my data by created date with this code :
$comments = Instacomment::where('postid',$query->post['id'])->orderBy('comment.created_at', 'ASC')->paginate(10);
These are the results and Laravel gives me duplicate data! I don't know what to do !
please try join table
$comments = Instacomment::join('comments', 'instacomment.id', '=', 'comments.postid')->where('postid',$query->post['id'])->orderBy('comment.created_at', 'ASC')->paginate(10);

Laravel 5.6: how to create a subquery using Query Builder

I would like to reproduce following mySQL query using Laravel query builder:
*SELECT SUM(scores) FROM (SELECT scores FROM player_games WHERE player_id = 1 ORDER BY id DESC LIMIT 2) scores
Any suggestions?
Here the solution:
$sub = playerGame::where('player_id',1)->where('scores','>',0)->limit(2)->orderBy('id','desc');
$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
->mergeBindings($sub->getQuery())
->sum('scores');
return $count;
Use fromSub():
$sub = playerGame::select('scores')
->where('player_id', 1)
->where('scores', '>', 0)
->limit(2)
->orderBy('id','desc');
$sum = DB::query()->fromSub($sub, 'scores')->sum('scores');
$responce= DB::table('player_games')->where('player_id',1)->sum('amount');
dd(collect($responce)->sortByDesc('id')->take(2));
please cheack this one.....i try it's work....and add use DB;in the top of controller....

Counting columns with if conidition in query

Counting only columns in which, Buy_Rate is more than Sell_Rate.
My query is not resulting as per expected, it is resulting me wrong.
$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->where('buy_rate', '<', 'sell_rate')->get()->count();
Inverse: If sell_rate is more than buy_rate then only, count the columns.
You can use whereColumn
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)
->whereColumn('buy_rate', '<', 'sell_rate')
->count();
Also there is no need to call get() when you need count() from query builder
laravel eloquent where don't support comparing columns. so you need use raw SQL in order to compair two columns. you can do something like,
$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->whereRaw('buy_rate < sell_rate')->get()->count();
hope this helps!

Counting years in y/m/d format in laravel

I have these as a sample of records
2016/01/13, 2016/01/15, 2016/01/25, 2015/01/14, 2015/01/17, 2015/01/28 and so on.
Any suggestions on how to only count (yyyy) where the month of January appears so that I get 2.(2016,2015)
$stocks = DB::table('inventories')
->select('inventories.*',DB::raw('count(*) as count,date_sold'))
->whereMonth('complete_sold','=', Carbon::today()->month)
->groupBy('inventories.drug_id')
->get();
Option 1:
If you only need the count number and not the records from the database do this:
$stocks = DB::table('inventories')
->whereMonth('complete_sold','=', Carbon::today()->month)
->groupBy('inventories.drug_id')
->count();
This way $stock will equal to number of records found (example: 2). The count will be performed on SQL level (example: SELECT count(*) ....).
Option 2:
If you will need the records later on, you could do it like this:
$stocks = DB::table('inventories')
->whereMonth('complete_sold','=', Carbon::today()->month)
->groupBy('inventories.drug_id')
->get();
$stockCount = $stock->count();
This way $stock will have the results of the query saved (the records from the database). And $stockCount will be a number of records. The count will be performed on collection (php).
Option 1: If you only want count
$stocks = DB::table('inventories')
->whereMonth('complete_sold','=', Carbon::today()->month)
->distinct()->count("year(complete_sold)");
Option 2: If you need the records of the years
$stocks = DB::table('inventories')
->whereMonth('complete_sold','=', Carbon::today()->month)
->select(DB::raw("year(complete_sold)"))
->groupBy(DB::raw("year(complete_sold)"))->get();

Resources