Reputation: 73
Basically i am creating an application where one event can have multiple date ranges like below and i want to show these events on jQuery calendar.
Event Table
ID Name
1 Test Event
Event Date Table
ID Event_ID Start Date End Date
1 1 2018-04-22 2018-04-22
2 1 2018-04-25 2018-04-27
3 1 2018-05-01 2018-05-10
There is Event model but Event date doesn't have any model So how can i do this with laravel eloquent relationship?
And how do i check particular event is available in specific date range while retrieving events from database.
Thanks in advance!
Upvotes: 1
Views: 708
Reputation: 1494
You can make a model for "Event Date Table" and then reference it in event model with has many relation. first of all, you must make a model in command prompt with this line:
php artisan make:model EventDate
and then you must set $table property in EvebtDate model:
protected $table='Event Date Table';
and belong to relation to event model:
public function event(){
return $this->belongsTo(Event::class,'Event_ID' );
}
after that in your Event model you must set hasmany relation to EventDate model:
public function eventDates(){
return $this->hasMany(EventDate::class,'Event_ID' );
}
after that you can retrieve all records from Event Date table from Event with that relationship. if you use carbon to insert data to date colums you can do somthing like this:
$eventDates = EventDate::whereBetween('Start Date', [$dateStart->format('Y-m-d'), $dateE->format('Y-m-d')])
->whereBetween('End Date', [$dateStart->format('Y-m-d'), $dateE->format('Y-m-d')])
->get();
then you must do a foreach loop to get the events and put them into an array:
$events = [];
foreach($eventDates as $date){
$events[] = eventDates->event()->first();
}
this way you can retrieve all the events available in a specific date range.
Hope this would help!
Upvotes: 2