0

I have a controller that I want to do some logic on a variable and send it to resource to show it in api so here is my controller :

public function index()
{
    $data = Accommodation::with('accommodationFacilities')->paginate();
    $x = Accommodation::with('cities')->get(1);

    return new AccommodationResource($data);
}

and here is the resource : and now in the resource I want to show the $x in my Api

public function toArray($request)
{
    return parent::toArray($request);
}

EDIT If I want to show the $x data nexto a $data model how can i do it like below :

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

cause right now it gives me the below error :

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id and when i remove the pagination this error apear :
Call to undefined method Illuminate\Database\Eloquent\Builder::all()

as I tried $x replaces the $data and I can't use the data any more.

2
  • Is ->get(1) meant to be ->find(1)?? Commented May 1, 2019 at 17:50
  • yes sorry for that mistake its find Commented May 1, 2019 at 18:51

1 Answer 1

2

to accept additional data to resource, override the constructor of the resource.

AccommodationResource

public $x;

public function __construct($resource, $x)
{
    parent::__construct($resource);
    $this->x = $x;
}

public function toArray($request)
{
    // you can use '$this->x' here.

    return [
        'id' => $this->resource->id,
        'x' => $this->x,
    ];
}

Controller

return new AccommodationResource($data, $x);
Sign up to request clarification or add additional context in comments.

5 Comments

what if i wana show it next to other elements as i can see now it puts the $x variable to $resource and i cant use Accomodation in detail check my edited question please
You can access $data as $this->resource. I updated the answer.
nope again same error i can access it and dd that in contruct but no in toArray($request)
Now I notice that your $data is actually a collection not a single object. So you can't access id from a collection. So I have no idea what you are trying to do. If you provide us what is your expected output is, I can help you with your own code. To be honest 'How to send additional data from controller to resource in laravel' has already answered.
To be Honest yes you are right :) i want to show all accommodations and along side that in each of them show a custom value thats all

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.