Created
June 10, 2019 00:35
-
-
Save tobz-nz/3e8a24787d4ae233235ce2c4c8fc0c0e to your computer and use it in GitHub Desktop.
A small base class taking on some of the basic foundations of an Eloquent Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Models; | |
| use ArrayAccess; | |
| use Illuminate\Contracts\Support\Arrayable; | |
| use Illuminate\Contracts\Support\Jsonable; | |
| use Illuminate\Database\Eloquent\Concerns\HasAttributes; | |
| use Illuminate\Database\Eloquent\Concerns\HasTimestamps; | |
| use Illuminate\Database\Eloquent\JsonEncodingException; | |
| use JsonSerializable; | |
| abstract class Base implements ArrayAccess, Arrayable, Jsonable, JsonSerializable | |
| { | |
| use HasAttributes; | |
| use HasTimestamps; | |
| /** | |
| * Convert the model instance to an array. | |
| * | |
| * @return array | |
| */ | |
| public function toArray() | |
| { | |
| return array_merge($this->attributesToArray(), $this->relationsToArray()); | |
| } | |
| /** | |
| * Convert the model instance to JSON. | |
| * | |
| * @param int $options | |
| * @return string | |
| * | |
| * @throws \Illuminate\Database\Eloquent\JsonEncodingException | |
| */ | |
| public function toJson($options = 0) | |
| { | |
| $json = json_encode($this->jsonSerialize(), $options); | |
| if (JSON_ERROR_NONE !== json_last_error()) { | |
| throw JsonEncodingException::forModel($this, json_last_error_msg()); | |
| } | |
| return $json; | |
| } | |
| /** | |
| * Convert the object into something JSON serializable. | |
| * | |
| * @return array | |
| */ | |
| public function jsonSerialize() | |
| { | |
| return $this->toArray(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment