Home » Php » php – Laravel Pluck items onto new table rows

php – Laravel Pluck items onto new table rows

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a table for trips and a table for events. One trip can have many events.
When editing a trip i want to display a table showing the event name, start date end date.

I have been using pluck to get data: –

<table class="table table-striped table-bordered table-hover">
    <thead class="thead">
        <tr class="warning">
            <th> Trip ID </th>
            <th> Event ID </th>
            <th> Event Name </th>
            <th> Start Date </th>
            <th> End Date </th>
        </tr>
    </thead>
    @foreach($trip->events as $trip->event)
    <tr>
        <td>{{ implode(',', $trip->events()->pluck('trip_id')->toArray()) }}</td>
        <td>{{ implode(', ', $trip->events()->pluck('trip_id')->toArray()) }}</td>
        <td>{{ implode(', ', $trip->events()->pluck('event_name')->toArray()) }}</td>
        <td>{{ implode(', ', $trip->events()->pluck('start_date')->toArray()) }}</td>
        <td>{{ implode(', ', $trip->events()->pluck('end_date')->toArray()) }}</td>
    </tr>
    @endforeach
</thead>
</table>

However my table is displaying as three rows which is correct but each row contains all the data.
I want a new table row for each event created for the trip.
Current table view

How to&Answers:

Is what you’re after something like this perhaps?

<table class="table table-striped table-bordered table-hover">
    <thead class="thead">
        <tr class="warning">
            <th>Trip ID</th>
            <th>Event ID</th>
            <th>Event Name</th>
            <th>Start Date</th>
            <th>End Date</th>
        </tr>
    </thead>
    <tbody>
    @foreach($trip->events as $event)
        <tr>
            <td>{{ $event->trip->id }}</td>
            <td>{{ $event->id }}</td>
            <td>{{ $event->event_name }}</td>
            <td>{{ $event->start_date }}</td>
            <td>{{ $event->end_date }}</td>
        </tr>
    @endforeach
    </tbody>
</table>