简体   繁体   中英

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!

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

To check between two dates, you could use this (among other options):

$articles = KhachHang::where('CreateDate', '>=', $start)
                     ->where('CreateDate', '<=', $end)->get();

You have to be sure that the date format is 'Ym-d', or the code will not work.

Old question, but the answer isn't great. Use whereBetween() , which has been around since at least 5.0 docs

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

只需将其添加到您的 Eloquent 查询中即可。

->whereBetween('your_field', [$from, $to])->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM