Eloquent + Object carrying itself

Asked

Viewed 289 times

0

I’ve always used Eloquent very well with static methods. Yesterday, when creating a new concept of session registration for a new project, I came across a question that I could not clarify.

I have a "Session" template that points to a table with the same name in the database. It turns out that the moment the user passes the token, an object of the class "Sessao" is created and its constructor tries to fetch the record related to that token in the database. Usually I would use:

$sessao = Sessao::where('token',Input::get('token'))->get();

Or something like that:

$this->where('token',Input::get('token'))->get();

But in this case, I need to load the result into the object that performed the query itself. Something like this:

$this = $sessao[0];

Of course this is out of the question. : ) Another option would be:

$this->id     = $sessao[0]->id;
$this->token  = $sessao[0]->token;

And so on. Maybe I didn’t quite understand how Eloquent works internally on the object. It is possible to perform this loading dynamically?

  • 1

    @Actually it is not necessary to return the object. When making the query can happen two things: the session can be found (then the data is loaded into the same object ), or the session can not be found (and the object remains without loading). To know if the session is valid or not, I created a public method within the Sessao class that checks whether or not the upload occurred and answers a boolean value.

  • Every query you make using Eloquent returns either a Collection or an instance of the model itself. I believe that the most appropriate solution is to create a static method that returns the first occurrence with this token.

  • Right @Vagnerdocarmo. The way you suggested was what I used to use. If there is no solution I will go back to doing so.

1 answer

1

You want to return the object that has the result of the query after having made the query ? if that’s why you do not create a method within the model:

public function SessionByToken($token){
 return Sessao::where('token',$token)->first();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.