Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 and Eloquent between two dates from database

I am a beginner with Laravel 5. I have a table: users with columns CreateDate, Type and Channel.

I have a list with users and I choose in View: Trans StartDate, Trans EndDate, Type and Channel.

I want to show: Tras StartDate < CreateDate < Trans EndDate with Type and Channel. name="time_start", "time_end", "type", "channel".

My Route:

Route::post('user', 'CSKHController@index');

My Controller:

public function index() {

    $start = Input::get ( 'time_start' );
    $end = Input::get ( 'time_end' );      

    $articles = KhachHang::all()->whereBetween('CreateDate', [$start, $end])->get();

    return view('admin/layouts/test', compact('stt','article'))->withDetails($articles);

}

Help me please!

like image 721
Vũ Hưng Avatar asked Dec 12 '16 12:12

Vũ Hưng


People also ask

How can we get data from database between two dates in Laravel?

Get data betweeen two dates with mysql Raw Query $startDate = '2021-06-01'; $endDate = '2021-06-30'; Post::whereBetween(DB::raw('DATE(created_at)'), [$startDate, $endDate])->get(); So, frinds today you learned more then examples to get data between two dates in laravel application.

Is Laravel eloquent slow?

Laracasts Veteran Sure it is slow, first it fetch all the record in one time, then it instantiate an eloquent object for each lines. It is not made to retrieve 10 000 objects.


1 Answers

Laravel 5.*

This is an example of how i used eloquent between in a laravel 5.6 project.

my-view.blade.php

simplified html form:

<form action="my-route" method="POST">

    {{ csrf_field() }}

    <input type="date" name="from">

    <input type="date" name="to">

    <button type="submit">Submit</button>

</form>

MyController.php

use Illuminate\Support\Carbon;

// ...

$request->validate([

    'from'        => 'required|date',
    'to'          => 'required|date',
]);

$from    = Carbon::parse($request->from)
                 ->startOfDay()        // 2018-09-29 00:00:00.000000
                 ->toDateTimeString(); // 2018-09-29 00:00:00

$to      = Carbon::parse($request->to)
                 ->endOfDay()          // 2018-09-29 23:59:59.000000
                 ->toDateTimeString(); // 2018-09-29 23:59:59

$models  = Model::whereBetween('created_at', [$from, $to])->get();

// do whatever you want with the query results...

Additional resources

Date range with whereBetween

Converting a carbon date to mysql timestamp

like image 134
chebaby Avatar answered Nov 15 '22 04:11

chebaby