I want return an array
to show it in a datatable
and also in callendar5
, but it gives me an error:
Trying to get property 'id' of non-object (View: D:\wamp\www\agendab\resources\views\index .blade.php).
I filled array
$events
with $bookings
returned in controller
, and I want it show in index.blade.php
when I do dd($events) it returns array, see image:
EventController.php
$events = array();
$bookings = Event::all();
foreach($bookings as $booking) {
$color = null;
$events[] = [
'id' => $booking->id,
'titre' => $booking->name,
'start' => $booking->datee,
'comment' => $booking->comment,
'color' => $color
];
}
$users = User::all();
return view('index')->with([
'events' => $events,
'users' => $users,
]);
index.blade.php
<tbody>
@foreach($events as $event)
<tr id="{{$event->id}}">
<td><input type="checkbox" name="customer_id[]" value="{{$event->id}}" /></td>
<td>{{ $event->id }}</td>
<td>{{ $event->datee }}</td>
<td>{{ $event->name }}</td>
<td>
{{ $event->comment }}
<a href="#" target='_blank' > <i ></i>
</a>
</td>
<th scope="col">{{ Str::upper( $event->user->name) }}</th>
<td>
<span >{{ $event->status }}</span>
</td>
</tr>
@endforeach
</tbody>
CodePudding user response:
Trying to get property 'id' of non-object (View: D:\wamp\www\agendab\resources\views\index.blade.php).
Exception messages are pretty handy for locating problems, the one you're seeing (above) is telling you which file the exception originates from. In this case it is it your index.blade.php
view file.
Within that file you're iterating (looping) over your $events
:
@foreach($events as $event)
{{-- doing stuff here --}}
@endforeach
The problem occurs because of how you're trying to access data within the iterated $event
variable. You're accessing data as if $event
is an object
using the object operator (->
) however, in your Controller
you're populating $events
as an array:
$events[] = [
'id' => $booking->id,
'titre' => $booking->name,
'start' => $booking->datee,
'comment' => $booking->comment,
'color' => $color
];
So in your index.blade.php
view, you need to access the data of $events
using the array
syntax:
<tbody>
@foreach($events as $event)
<tr id="{{ $event['id'] }}">
<td><input type="checkbox" name="customer_id[]" value="{{ $event['id'] }}" /></td>
<td>{{ $event['id'] }}</td>
<td>{{ $event['start'] }}</td>
<td>{{ $event['name'] }}</td>
{{-- etc. --}}
</tr>
@endforeach
</tbody>
Note that you will still need to sort out other errors in your code. For example you're not adding a name
element to your $events[]
array in your controller but you're trying to access it in your view.
There are other errors that you will need to resolve too, but the above will fix the immediate issue you've asked about.