-4

ProductController This is ProductController


API routes This is ProductCollection


Error And here is my route API

I get error:

ErrorException (E_NOTICE) Undefined property: Illuminate\Database\Query\Builder::$name" when i run Laravel app in browser with link :http://127.0.0.1:8000/api/products!

Help me to solved this bug thank you so much (I'm a newbie to learn Laravel, thanks!!!)]

Rwd
  • 34,180
  • 6
  • 64
  • 78
  • share your code. – Kuldeep Mishra Jul 26 '19 at 06:54
  • Hi, you can paste your code snippets by text. Images are extra. Also you can format code with 3 symbols " ` " at the beginning of the code and 3 " ` " at the end. – Bulat Jul 26 '19 at 06:54
  • 1
    [Please do not post images as text or encourage people to post images as text.](https://idownvotedbecau.se/imageofcode) – Adrenaxus Jul 26 '19 at 06:58
  • my Controller with function index : public function index() { return ProductCollection::collection(Product::all()); } – Huy Nguyễn Jul 26 '19 at 06:58
  • and code in ProductCollection : public function toArray($request) { return [ 'name' => $this->name, 'totalPrice' => round( (1- ($this->discount/100))*$this->price,2), 'rating' => $this->reviews->count()> 0 ?round($this ->reviews->sum('star')/$this->reviews->count(),2) :'No rating yet', 'href' => [ 'link' => route('products.show',$this->id) ] ]; } – Huy Nguyễn Jul 26 '19 at 06:59
  • Tks, i try to use stack overflow and my English is low. – Huy Nguyễn Jul 26 '19 at 07:01
  • Please can you add the code for you `ProductCollection` to your question i.e. edit the question and copy and paste the code into it. (please do not add it as a comment or add an image). – Rwd Jul 26 '19 at 07:27

1 Answers1

0

You are accessing your data in the wrong way, like $this->name in your ProductCollection.

As stated here in the Laravel Documentation, you have to access your properties via the $this->collection property which is populated with the mapping of each item of the collection.

Try using:

$this->collection->name and you should be fine.

OMR
  • 11,736
  • 5
  • 20
  • 35
  • Tks but my errors still appear the same.Undefined property: Illuminate\Database\Query\Builder::$name – Huy Nguyễn Jul 26 '19 at 07:12
  • Is there any other way to use resources instead of collections in laravel?when to use resources and when to use collections in laravel? Tks! – Huy Nguyễn Jul 26 '19 at 07:29
  • Thanks for your suggestion Andrea Campana. I have found some suggestions from Laravel's homepage!Then I tried with : $this->collection->get() and everything looks good; but i still search andI will try to find a way to use it correctly.If you have a great standard and explanation about this, please share with me, thank you very much – Huy Nguyễn Jul 27 '19 at 06:26
  • i find a post here : https://stackoverflow.com/questions/46388205/laravel-5-5-api-resources-for-collections-standalone-data. – Huy Nguyễn Jul 27 '19 at 09:16