php - Laravel - multiple controllers in single view
I'm trying to code a simple event page. This page should display a particular event and it's features (including other info not relevant for the problem).
I've tried a couple different approaches with no luck, this is the approach I feel like I might be closet to success with, any suggestions?
I can provide other extracts of code if you think the problem lies elsewhere but I think my problem lies within these 7 files.
The current error I have is "Property [features] does not exist on this collection instance." and point to the EventController show() function.. if anyone could help I'd greatly appreciate it.
web.php
Route::get('cards/{id}', 'CardController@show');
Route::get('event/{id}', 'EventController@show');
event.blade.php
<h1 class="big-title">
</h1>
<section id="events">
@each('partials.event', $event, 'event')
</section>
(partials) event.blade.php
<header>
<h2 class="event-name fsb">
{{ $event->name }}
</h2>
</header>
<p class="event-description pdl1em">
{{ $event->description }}
</p>
<ul class="event-dates pdl1em">
<ul>
@each('partials.features', $event_features, 'feature')
</ul>
</ul>
Event.php
class Event extends Authenticatable
{
public function features() {
return $this->hasMany('App\Models\EventFeature');
}
}
EventFeature.php
class EventFeature extends Authenticatable
{
public function event() {
return $this->belongsTo('App\Models\Event');
}
}
EventController
class EventController extends Controller
{
public function show($id)
{
$event = DB::table('event')->where('id', $id)->get();
return view('pages.event', ['event' => $event, 'features' => $event->features]);
}
}
EventFeatureController
class EventFeatureController extends Controller
{
public function show($id)
{
$event_features = DB::table('event_features')->where('id', $id)->get();
return view('pages.event', ['event' => $event_features->eventClass, 'features' => $event_features]);
}
public function list($event_id)
{
if (!Auth::check()) return redirect('/login');
$event_features = DB::table('event_features')->where('event_id', $event_id)->orderBy('id')->get();
return view('pages.event', ['event_features' => $event_features]);
}
}
Answer
Solution:
When you want to retrieve a single item, use find($id)
or first()
to retrieve an instance of the model. When you call get()
you get a collection of an array with the instances inside it.
When using DB::table('events')
you dont get as a result an instance of the model, you get a generic object instance => you can't use Model class defined methods like relations and such. use the model directly instead Event::where(...
Change your method to
class EventController extends Controller
{
public function show($id)
{
$event = Event::findOrFail($id);
return view('pages.event', ['event' => $event, 'features' => $event->features]);
}
}
Source