php – Laravel 5 and Eloquent between two dates from database-ThrowExceptions

Exception or error:

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!

How to solve:

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

Answer:

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 ‘Y-m-d’, or the code will not work.

Answer:

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();

Answer:

Simply do this in your laravel query.

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

Leave a Reply

Your email address will not be published. Required fields are marked *