1

I have two models related to each other with a one-to-one relationship.

Model A belongs to model B and when an instance of model B is returned to the frontend, the Resource of the model B includes the data of the modal A like this example.

use Illuminate\Http\Resources\Json\JsonResource;

class B extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'prop1' => $this->prop1,

            'modelA' => $this->model_a,
            // ...

Issue

However, I'm having problems when the Model A instance that would be included in a response is soft deleted. I can retrieve the soft deleted model B using ModelB::withTrashed()->get(), but the model B resource doesn't include its related soft deleted model A.

I tried "manually" selecting modelA in the following ways, but it didn't work.

use Illuminate\Http\Resources\Json\JsonResource;

class B extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'prop1' => $this->prop1,

            'modelA' => ModelAResource::make($this->resource->modalARelation()->withTrashed()->get()),
            'modelA' => ModelAResource::make($this->modalARelation()->withTrashed()->get()),
            'modelA' => ModelA::withTrashed()->where('model_b', $this->id)->get(),
            // ...

1 Answer 1

0

It's actually simpler, as I just found out.

use Illuminate\Http\Resources\Json\JsonResource;

class B extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'prop1' => $this->prop1,

            'modelA' => $this->modelARelation()->withTrashed()->get()->first(),
            // ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.