错误:类在Laravel中不存在

时间:2016-07-22 10:48:35

标签: php laravel laravel-4 laravel-5 laravel-5.1

我遇到以下错误

InvalidArgumentException第39行中的

FormBuilder.php: 名称为App\Http\Controllers\App\Forms\SongForm的表单类不存在。

在Laravel上,

SongsController.php类

<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;
use Kris\LaravelFormBuilder\FormBuilder;

class SongsController extends BaseController {

    public function create(FormBuilder $formBuilder)
    {
        $form = $formBuilder->create(App\Forms\SongForm::class, [
            'method' => 'POST',
            'url' => route('song.store')
        ]);

        return view('song.create', compact('form'));
    }

    public function store(FormBuilder $formBuilder)
    {
        $form = $formBuilder->create(App\Forms\SongForm::class);

        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }

        // Do saving and other things...
    }
}

SongForm.php

<?php

namespace App\Forms;

use Kris\LaravelFormBuilder\Form;

class SongForm extends Form
{
    public function buildForm()
    {
        $this
            ->add('name', 'text', [
                'rules' => 'required|min:5'
            ])
            ->add('lyrics', 'textarea', [
                'rules' => 'max:5000'
            ])
            ->add('publish', 'checkbox');
    }
}

routes.php文件

Route::get('songs/create', [
    'uses' => 'SongsController@create',
    'as' => 'song.create'
]);

Route::post('songs', [
    'uses' => 'SongsController@store',
    'as' => 'song.store'
]);

我不知道问题出在哪里,因为该文件存在于项目文件夹中。

1 个答案:

答案 0 :(得分:2)

错误说明

下面:

$form = $formBuilder->create(App\Forms\SongForm::class, [
        'method' => 'POST',
        'url' => route('song.store')
   ]);

您使用相对于当前命名空间的命名空间指定类名:

App\Forms\SongForm::class

完整的类名将相对于当前的命名空间构建:

namespace App\Http\Controllers;

因此,您作为参数传递的类变为:

App\Http\Controllers\App\Forms\SongForm::class

该类不存在,因此您收到错误

如何解决

要解决此问题,您可以指定绝对命名空间。改变这个:

App\Forms\SongForm::class

到此:

\App\Forms\SongForm::class

它应该有效