Reputation: 51
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!
Upvotes: 5
Views: 35389
Reputation: 1696
Simply add this to your Eloquent query.
->whereBetween('your_field', [$from, $to])->get();
Upvotes: 2
Reputation: 7730
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
Converting a carbon date to mysql timestamp
Upvotes: 6
Reputation: 531
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();
Upvotes: 2
Reputation: 7083
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.
Upvotes: 3