Home > Software design >  Passing a new variable to Resource from Controller | Laravel
Passing a new variable to Resource from Controller | Laravel

Time:08-21

I have an API resources in my code,

what i wanted to do is to pass a new data to be return in Resource Collection

Controller:

public function index(Request $request)
{
    // @TODO implement
    $books = Book::with('authors')->paginate(5);
    $pass = 1;

    return BookResource::collection($books, $pass, 200);
}

my Resources:

public function toArray($request)
{
    return [
        // @TODO implement
        'id' => $this->id,
        'isbn' => $this->isbn,
        'title' => $this->title,
        'description' => $this->description,
        'published_year' => $this->published_year,
        'authors'    => AuthorResource::collection($this->authors),
        'review'    => BookReviewResource::collection($this->reviews),
        'pass'    => $this->pass
    ];
}

Returned Data

I want the $pass, can be returned in Resources,

how do i achieve that?

CodePudding user response:

Try adding metadata to the collection using additional:

return BookResource::collection($books)->additional([
    ‘pass’ => $pass,
]);

CodePudding user response:

BookResource

class BookResource extends Resource {

    protected $pass;

    public function pass($value){
        $this->pass = $value;
        return $this;
    }

    public function toArray($request){
        return [
            'id' => $this->id,
            'isbn' => $this->isbn,
            'title' => $this->title,
            'description' => $this->description,
            'published_year' => $this->published_year,
            'authors' => AuthorResource::collection($this->authors),
            'review' => BookReviewResource::collection($this->reviews),
            'pass' => $this->pass
         ];
    }

    public static function collection($resource){
        return new BookResourceCollection($resource);
    }
}

BookResourceCollection

class BookResourceCollection extends ResourceCollection {

    protected $pass;

    public function pass($value){
        $this->pass = $value;
        return $this;
    }

    public function toArray($request){
        return $this->collection->map(function(BookResource $resource) use($request){
            return $resource->pass($this->pass)->toArray($request);
    })->all();
}

Pass params

BookResource::collection($books)->pass(1);

Or using this:

http://localhost:3000/api/books?pass=1

public function toArray($request) {
   $pass = $request->pass;

   return [
      'id' => $this->id,
      'isbn' => $this->isbn,
      'title' => $this->title,
      'description' => $this->description,
      'published_year' => $this->published_year,
      'authors' => AuthorResource::collection($this->authors),
      'review' => BookReviewResource::collection($this->reviews),
      'pass' => $pass
   ];
}
  • Related