PHP code example of borisnedovis / eloquent-presenter

1. Go to this page and download the library: Download borisnedovis/eloquent-presenter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

borisnedovis / eloquent-presenter example snippets


namespace App\Presenters;

use BorisNedovis\EloquentPresenter\AbstractPresenter;

class UserPresenter extends AbstractPresenter
{
    /**
     * @var \App\Models\User
     */
    protected $model;
    
    protected $attributes = [
        'first_name',
        'last_name'
    ];
}

protected $attributes = [
    'first_name',
    'last_name',
    'full_name', // <- a virtual key, that model doesnt contain
];

// Get virtual value. Just studly case your key and surround it with 'get' and 'Attribute'.
public function getFullNameAttribute()
{
    return "{$this->model->first_name} {$this->model->last_name}";
}

use BorisNedovis\EloquentPresenter\Presenter;

class User
{
    use Presenter;
    // ...

    protected $presenter = \App\Presenters\UserPresenter::class;

}

class User
{
    use Presenter;
    // ...

    public function getPresenterClass()
    {
        if ($this->isBlocked()) {
            return \App\Presenters\BlockedUserPresenter::class;
        }

        return \App\Presenters\UserPresenter::class;
    }

}

$user = User::first();

return response()->json(compact('user'));