进行显式绑定会引发错误

时间:2019-03-24 13:56:39

标签: laravel

我正在尝试在Providers / RouteServiceProvider.php中进行显式绑定。当我按照文档中的说明进行操作时,显示错误的模型路径会出现错误。但是在我的路径前添加..不起作用,因为它不是字符串,只会增加一个错误。

    public function boot()
    {
        //

        parent::boot();

        Route::model('post', App\Post::class);
    }

我收到错误的模型路径错误:

Class App\Providers\App\Post does not exist

它将尝试在provider文件夹中查找路径。 但是文档示例仅显示了该示例,

public function boot()
{
    parent::boot();

    Route::model('user', App\User::class);
}

我怀疑这是因为它在名称空间App \ Providers中,但不知道该怎么办。谢谢。

这里的整个服务提供商类:

<?php

namespace App\Providers;


use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();

        Route::model('post', \App\Post::class);
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
}

我的Post模型课:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

        /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'content','user_id'
    ];

    protected $casts = [
    'created_at' => 'date',
    'updated_at' => 'date'
];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'id'
    ];


    public function user(){

        return $this->belongsTo('App\User');
    }

}

1 个答案:

答案 0 :(得分:1)

\开头的简短解决方案前缀,以便命名空间从根而不是当前根开始。

Route::model('post', \App\Post::class);

其他解决方案将类导入到顶部:

<?php

use App\Post;

...

    public function boot()
    {
        //

        parent::boot();

        Route::model('post', Post::class);
    }
...