0
votes

i want to make two different functions on resource so that i can get a two different response .i.e i want the resource to return data without image and with image.

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'area_code' => $this->area_code
        ];
    }


    public function toArrayWithImages($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'area_code' => $this->area_code,
            'image' => $this->image
        ];
    }

this is what i tried but dont know how to point to the second function 'toArrayWithImages' . can someone explain me this ? This is my controller ..

  public function getAllBusinessAreas()
    {
        try {
            $areas = Area::orderBy('id', 'desc')->get();
            return BusinessAreaResource::collection($areas);
        } catch (Exception $e) {
            return sendErrorResponse('Error fetching Business Areas', true, 500);
        }
    }

what it does is by default it hits the toArray function i want to be specific which function to hit from controller. is it possible to do it ?

1
How will you know when to call toArrayWithImages method and when to follow the default pattern?Pusparaj
@Pusparaj thats what i want to be specific from controller but i am not sure how i can achieve this .Ravi Sigdel
The question is not how to call different methods, but when to call. How will you determine which method to call after accepting a request?Pusparaj
Isn't it possible to just create two different resources for one model? That is kind of how Laravel designed the logic behind resources. 2 different presentations of the data of the same model means 2 different resource classes.Mark Walet
@MarkWalet thats what i came with too . i made two different resource for it and i call/point the resource which i want from controller.Ravi Sigdel

1 Answers

0
votes

So basically what i am doing is adding an additional parameter to your request, you can use a flash session variable as well if it is not possible to attach extra params to your request, to filter weather it goes to the function which returns image or data without image.

public function toArray($request)
    {
        if($request->with_image)
        {
           this::toArrayWithImages($request->except('with_image'));
        }
        else
        {
          this::toArrayWithoutImages($request->except('with_image'));
        }
   }


    public function toArrayWithoutImages($request)
    {
         return [
        'id' => $this->id,
        'name' => $this->name,
        'area_code' => $this->area_code
        ];
    }
    public function toArrayWithImages($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'area_code' => $this->area_code,
            'image' => $this->image
        ];
    }