ahmad
1/2/2014 - 3:05 PM

Laravel BaseModel implementing the JsonSerializable interface (php > 5.4) This way a model can be easily serialized to json directly, usi

Laravel BaseModel implementing the JsonSerializable interface (php > 5.4)

This way a model can be easily serialized to json directly, using the mutated attribute values, if any.

<?php

use Eloquent;
use JsonSerializable;

abstract class BaseModel extends Eloquent implements JsonSerializable
{
    // ...
    
    /**
     * Specify data which should be serialized to JSON
     *
     * @return array The serializable data
     */
    public function jsonSerialize()
    {
        // Return attributes with mutations applied
        return $this->toArray();
    }
}