Skip to content

Commit

Permalink
Handle toJson properly on json resources (#30801)
Browse files Browse the repository at this point in the history
At the moment when you call toJson on a Json resource it skips the `toArray` method and directly calls toJson on the Eloquent model because of the ForwardsCalls trait. This seems unwanted because if you're formatting the resource in a specific way through the toArray method you'd expect it to be honered when calling toJson I believe. toJson isn't documented on the Json Resources documentation but I still believe that this should be honered.

This is technically a breaking change so I'm targeting the next release.
  • Loading branch information
driesvints authored and taylorotwell committed Dec 10, 2019
1 parent 2634282 commit 79706c8
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Eloquent/JsonEncodingException.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,20 @@ public static function forModel($model, $message)
return new static('Error encoding model ['.get_class($model).'] with ID ['.$model->getKey().'] to JSON: '.$message);
}

/**
* Create a new JSON encoding exception for the resource.
*
* @param \Illuminate\Http\Resources\Json\JsonResource $resource
* @param string $message
* @return static
*/
public static function forResource($resource, $message)
{
$model = $resource->resource;

return new static('Error encoding resource ['.get_class($resource).'] with model ['.get_class($model).'] with ID ['.$model->getKey().'] to JSON: '.$message);
}

/**
* Create a new JSON encoding exception for an attribute.
*
Expand Down

0 comments on commit 79706c8

Please sign in to comment.