Search code examples
phplaraveleloquentlaravel-resource

Storing data with Eloquent Model not working, Call to undefined method


I want to make Restful API with Laravel and I want to write a script that is going through the CSV file, and firstly POST Animal, then get Animal ID from response, and POST AnimalDate, but It's not working as I want and I'm getting this following error:

Call to undefined method App\Animal::getAnimalDateAttribute()

I have models like Animal and AnimalDate and I want to show response in json like bellow so I used Eloquent Resources with JsonResource:

{
  "id": 1,
  "name": "Gilda Lynch",
  "country": "MO",
  "description": "Soluta maiores aut dicta repellat voluptas minima vel. Qui omnis assumenda maxime.",
  "image": "http://www.abshire.com/",
  "dates": [
    {
      "id": 6,
      "date_from": "2019-11-25 04:03:44",
      "date_to": "2019-09-30 05:47:28",
      "animal_id": 1,
    },
  ]
}

I think that problem is in a relationship between Animal model and AnimalDate model, but I can't fix it so I'm looking for help.

Relationship between these models: Animal hasMany AnimalDate

class Animal extends Model
{

   public function animalDates()
   {
      return $this->hasMany(AnimalDate::class);
   }
}

and AnimalDate belongsTo Animal

class AnimalDate extends Model
{
    public function animal()
    {
        return $this->belongsTo(Animal::class);
    }
}

I created Resources - AnimalDateResource.php

class AnimalDateResource extends JsonResource
{
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

and AnimalResource:

class AnimalResource extends JsonResource
{
    public function toArray($request)
    {
        // return parent::toArray($request);
        return [
            'id' => $this->id,
            'name' => $this->name,
            'country' => $this->country,
            'description' => $this->description,
            'image' => $this->image_url,
            'dates' => AnimalDateResource::collection($this->animalDates)
        ];
    }
}

In controller I'm just using new AnimalResource($animal) and mehods index and show works perfect.

Is there any solution to POST it like Animal and then AnimalDate, or do I have to POST it first and than show relationship via JsonResouce?


Solution

  • Ok so the problem was in AnimalController@store.

    Before solution:

    public function store(Request $request)
    {
        $data = $request->all();
        $animal = Animal::create($data);
    
        return response()->json($animal, 201);
    }
    

    After problem fixing:

    public function store(Request $request)
    {
        $data = $request->all();
        $animal = Animal::create($data);
    
        // THIS LINE
        return new AnimalResource($animal);
    }