Search code examples
laravellaravel-encryption

Laravel json response returns encrypted data


I'm using an Encryptable trait to encrypt my data for the a Room model.

RoomController (/rooms) returns the decrypted data but ApiRoomController (/api/rooms) does not. How could I make it returns the decrypted data?

Encryptable Trait

trait Encryptable
{
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);
        if (in_array($key, $this->encryptable) && $value !== '' && $value !== null ) {
            $value = Crypt::decrypt($value);
        }

        return $value;
    }

    public function setAttribute($key, $value)
    {
        if (in_array($key, $this->encryptable)) {
            $value = Crypt::encrypt($value);
        }

        return parent::setAttribute($key, $value);
    }
}

RoomController index function

public function index()
{
    $rooms = Room::select('id', 'name')->get()->sortBy('name')->values()->all();

    return view('rooms.index')->withRooms($rooms);
}

ApiRoomController index function

public function index()
{
    $rooms = Room::select('id', 'name')->get()->sortBy('name')->values()->all();

    return response()->json($rooms);
}

Solution

  • I found a way using API Resources:

    php artisan make:resource Rooms --collection
    

    Then in your app/Http/Resources/Rooms.php file:

    public function toArray($request)
    {
        return [
            'id'   => $this->id,
            'name' => $this->name,
            // more fields here
        ];
    }
    

    Then in your ApiRoomController.php file:

    use App\Http\Resources\Rooms;
    
    
    public function index()
    {
        $rooms = Room::select('id', 'name')->get()->sortBy('name')->values()->all();
    
        return Rooms::collection($rooms);
    }