Mi Mehdi
Mi Mehdi

Reputation: 13

Get request from controller in model - Laravel

In my API I used "with" method to get parent's model relation and everything works fine. I want to add an attribute in my relation and return it in my API but I should use request in my model.

Something like this :

Book.php

protected $appends = ['userState'];
public function getUserStateAttribute () {
   return User::find($request->id); //request not exists here currently
}

I have $request in my controller (api controller)

Controller.php

public function get(Request $request) {
   Post::with('books')->all();
}

I believe using static content to append in array of model is so easy but how about using request's based content ?

Upvotes: 1

Views: 204

Answers (2)

party-ring
party-ring

Reputation: 1871

You want to take request as a parameter here:

public function getUserStateAttribute (Request $request) {
   return User::find($request->id);
}

That way you can access it in the function. You will just need to always pass the Request object whenever you call that function.

e.g. $book->getUserStateAttribute($request);

Alternatively, you could just pass the ID, that way you need not always pass a request, like so:

public function getUserStateAttribute ($id) {
   return User::find($id);
}

Which you would call like:

e.g. $book->getUserStateAttribute($request->id);

Upvotes: 0

Vincent Decaux
Vincent Decaux

Reputation: 10714

I guess you can use request() helper :

public function getUserStateAttribute () {
   return User::find(request()->get('id'));
}

Sure this is not really MVC pattern, but it can work

Upvotes: 1

Related Questions