简体   繁体   中英

Laravel name spacing issue

I am using the IoC container in Laravel, I am trying to grab all the data from my database

<?php namespace API;

class ProductRepository implements ProductRepositoryInterface {

  public function getProducts()
  {
    return Product::all();
  }

}

When I run this I get this error

Symfony \ Component \ Debug \ Exception \ FatalErrorException
Class 'API\Product' not found

I am guessing it is trying to find the Product model in the API folder which I have namespaced. My question is how do I get my application to know that Product:all() should use the Product model. Is my name spacing correct? ProductRespository is sitting inside a folder called API.

When in a namespace, always prepend a \\ to any class in the root namespace:

public function getProducts()
{
     return \Product::all();
}

Alternatively, you can use the class in your file:

<?php namespace API;

use Product;

class ProductRepository implements ProductRepositoryInterface {

    public function getProducts()
    {
        return Product::all();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM