Support the ongoing development of Laravel.io →
Requests Eloquent IOC

Hello,

I have this scenario:

Route::group([
    'middleware' => ['reservation'],
    'prefix' => 'booking'
],function(){
    Route::any('details/{tour}', [
        'as' => 'reservation_step_1',
        'uses' => 'ReservationController@step_one'
    ]);
    /* MORE ROUTES */
});

So when I go to myhost/booking/details/tour-to-somewhere I first call the middleware reservation

There, in ReservationMiddleware.php, I create a new reservation related to the visitor, and save it with this code:

$visitor = Visitor::where('etvisitor',session('etvisitor')->first();
Reservation::create([
    'idtour_date' => $tour->dates[0]->idtour_date,
    'booking' => 0,
    'owner_visitor' => $visitor->idvisitor
]);

Then in the controller I get the visitor again and when I try this:

Visitor::get()->reservation->someMethod();

the value of reservation is null and, obviously, I get an error, but in the database the reservation is created and I have to reload the webpage to get the reservation by the relationship method hasOne();

Are the relationship loaded on system initialization or dinamically? because I can't imagine other reasion.

Last updated 2 years ago.
0
Solution

I solved it by calling the visitor relation as function:

Visitor::get()->reservation()->someMethod();

It may be because the relationships are cached on system startup and when the function is called it is reloaded.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

jsertx jsertx Joined 28 Sep 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.