Miguel Stevens
Miguel Stevens

Reputation: 9201

Laravel Passing an object to other methods

I'm using Laravel to create a complex registration form. Now I want to use the Company Object throughout the whole process.

I'm currently creating a new Company object in the constructor as follows:

public function __construct()
{
    $this->company = new Company();
}

And then I fill the object with data from an API.

But the object is returning null every time I hit a new method or route.

I don't see any other way of going about this? Any idea's? Thanks!

The following is working

return redirect()->route('register.contacts')->with('company', $company);

And in the contacts method

public function contacts()
{

    Session::get('company'));
}

Upvotes: 4

Views: 2019

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152880

Stick with what works, there isn't really a better alternative. You have to realize that PHP applications are request based. After each request, all data in memory is lost. You only keep things that you store in the database, the session or the filesystem in general.

Also when you redirect to another route, you don't call another controller method. You send a response to the client that tells him to what URL the next request should go. The browser then calls that route. Those requests are completely decoupled, so the only way you can pass data is in the URL (that doesn't work that well for full objects) or somehow storing it on the server and loading that data again on the subsequent request.

Just for the sake of completeness, here are two alternatives:

  • Save the not-yet-complete model to the database. Tricky to avoid "dead body records" though
  • Change your register process to be all done client side and sent in one go to the server.

Upvotes: 4

Related Questions