laravel API is a great place to search.
Is there a way to see what Laravel is expecting for the magic behind the scenes?
I have two models, Event and Interactive Level. Event belongs to Interactive Level and Interactive Level can have many events. In my migration I have
Schema::create('interactive_levels', function (Blueprint $table)
so in my event model I created
$table->foreignId('interactive_level_id')->nullable();
I assumed this would connect the two in the back end with Laravel's magic but it doesn't work. If I do
dd($event->interactivelevel);
nothing happens. However if I add my own foreign key like so
public function interactivelevel()
{
return $this->belongsTo(InteractiveLevel::class, 'interactive_level_id');
}
it works. Is there a way for me to see what Laravel is looking for as a foreign key?? Sorta like Route:list but for foreign keys.
I don't understand what you're asking by "naming things correctly." Doesn't the debug bar show the same query as it does when enabling query logging?
I assumed this would connect the two in the back end with Laravel's magic but it doesn't work.
The magic comes in when you manually add the foreign key relationship like you did, which instructs laravel about it. There isn't anything that I'm aware of that will tell you that unless you supply it yourself. If tables are related to each other, there should be a relationship defined.
One thing you can do that will help is to utilize Laravel Eloquent Model Conventions: https://laravel.com/docs/7.x/eloquent#eloquent-model-conventions
You shouldn't need to tell it that interactive_level_id is the foreign key. It can figure that part out if the classnames and everything else follow the naming conventions.
Please or to participate in this conversation.