Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MThomas's avatar

Access method in user model inside the presenter

In my User model I have a rolesList method, this returns an array of the roles assigned to the user. This method is invoked to check if a user is authorized to view a certain page or perform an action.

I also extended this User model with laracasts Presenter (for example to display the users fullname composed of the first and last name properties of the user model).

Now I also like to use the presenter to display all the roles assigned to a user as a string, but with the code below I get the following error:Call to undefined method App\Presenters\UserPresenter::rolesArray() so I get that the methods in the User model are not accessible the way I imagined, how do I do it correctly?

<?php namespace App;

use App\Presenters\UserPresenter;
use Illuminate\Database\Eloquent\Model;
use Laracasts\Presenter\PresentableTrait;

class User extends Model {

 use PresentableTrait;

 /**
  * The user presenter.
  *
  * @var class
  */
 protected $presenter = UserPresenter::class;

 /**
  * User Roles
  *
  * @return object
  */
 public function roles()
 {
    return $this->hasMany(UserRole::class);
 }

 /**
  * Get the user roles in an array.
  *
  * @return \Illuminate\Http\Response
  */
 public function rolesArray()
 {
    return array_map(function($item) 
    {
   return $item['role'];
    },
    $this->roles->toArray());
 }
}
<?php namespace App\Presenters;

use Laracasts\Presenter\Presenter;

class UserPresenter extends Presenter {

 public function roles()
 {
    return implode(', ', $this->rolesArray());
 }

}

I removed the unrelated code in the classes above.

0 likes
2 replies
MarkRedeman's avatar
Level 10

Hi Thomas,

The Laracast presenter object only uses the __get() magic method. It therefore will not check if the method you're trying to run may exist on you entity.

You can do the following (haven't tested it though):

 public function roles()
 {
    return implode(', ', $this->entity->rolesArray());
 }

Or if you don't want to use $this->entity, then you can fix it by adding a __call method to the PresentableTrait.

MThomas's avatar

Thanks! That's what I've been looking for!

Please or to participate in this conversation.