Using The Presenter Class

After you create the presenter class, you need to register it on the Model by adding the $presenters protected property:

1use App\Presenters\UserPresenter;
2use Coderflex\LaravelPresenter\Concerns\CanPresent;
3use Coderflex\LaravelPresenter\Concerns\UsesPresenters;
4// ...
5 
6class User extends Authenticatable implements CanPresent
7{
8 use UsesPresenters;
9 
10 protected $presenters = [
11 'default' => UserPresenter,
12 ];
13}

By default, the type of your presenter class is default, but you can use as many of presenters you want, just by identifying the type in $presenters property.

Example

Now, after we generated the presenter class, and we implemented it successfully in our model, we can use it like so:

In your UserPresenter class or any presenter class you generated.

1...
2class UserPresenter extends Presenter
3{
4 public function fullName()
5 {
6 return "{$this->model->first_name} {$this->model->last_name}";
7 }
8}
9...

We add a new method to present the fullName.

In your blade or any place you want, you can do:

1$user->present()->fullName

Your application will show the full name from the method you added.

Join our newsletter

Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

We care about the protection of your data. Read our Privacy Policy.