找不到“App \ Http \ Controllers \ Restaurant”类

找不到“App \ Http \ Controllers \ Restaurant”类

问题描述:

I am facing this issue which i wanted to insert data into restaurants, but it keep showing error

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\FoodRequest; use App\Http\Controllers\Controller;
   public function store(FoodRequest $request)
    { 
        Restaurant  ::create($request->all());
        return redirect()->back(); 
    }

我正面临这个问题,我想将数据插入餐馆,但它一直显示错误 p> \ n

  namespace App \ Http \ Controllers; 
 
use Illuminate \ Http \ Request; 
use App \ Http \ Requests \ FoodRequest; 使用App \ Http \ Controllers \ Controller; 
公共函数存储(FoodRequest $ request)
 {
 Restaurant :: create($ request-> all()); 
返回redirect() - >返回(  );  
} 
  code>  pre> 
  div>

You are trying to use the Restaurant model. Models are usually under the App namespace.

To use your Restaurant mode, you must write this at the top of your controller:

use App\Restaurant;

PHP automatically looks for classes with the given name in the same namespace if it is not imported. You were looking for a class called Restaurant in App\Http\Controllers, when actually it exists in App

Hope this helps you!

A better solution is to use composer classmap. When composer loads the classmap, all classes in that folder are auto loaded. Just type hint the class name and Laravel will inject a new class instance.

"autoload": {
    "classmap": [
        "database",
        "app/models" 
    ],
    "psr-4": {
        "App\\": "app/",
    }
},

Run composer dump-autoload

To inject a new class instance of your model, you have 2 options.

Inject at teh class level. The model is available to use for all methods within the class like this :

use Restaurant;

or at the method level, the model is only available to that method like this :

public function store(FoodRequest $request)
{ 
    \Restaurant::create($request->all());
    return redirect()->back(); 
}

Hope this help.