Laravel简单表单不设置错误和会话变量

时间:2016-04-02 11:28:32

标签: laravel-5.2

我是Laravel的新手,我正在尝试创建一个简单的表单,将记录添加到数据库表(包含2个字段:ID和名称)。

这是我到目前为止的代码:

routes.php文件

Route::group(['middleware' => ['web']], function () {
    Route::get('/banks/add', 'BanksController@add');
    Route::post('/banks/add', 'BanksController@store');
});

BanksController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\BankFormRequest;
use App\Bank;

class BanksController extends Controller
{

    public function add() {
        return view('banks.add');
    }

    public function store(BankFormRequest $request) {

        $bank = new Bank(array(
            'name' => $request->get('name'),
        ));
        $bank->save();

        return redirect('/banks/add')->with('status', 'Your bank has been created! Its name is: '.$request->get('name'));
    }

}

BankFormRequest.php

<?php

namespace App\Http\Requests;
use App\Http\Requests\Request;

class BankFormRequest extends Request
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|unique:banks|max:255',
        ];
    }

}

Bank.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Bank extends Model
{
    public $timestamps = false;
    protected $guarded = ['id'];
}

银行/ add.php

<form id="registerForm" role="form" method="post">
    <pre><?=var_dump($errors)?></pre>
    <pre>
        <?php if (session()->has('status')): ?>
            <?=session('status')?>
        <?php endif; ?>
    </pre>

    <?php if (isset($errors) && $errors->any()): ?>
        <?php foreach ($errors->all() as $error): ?>
            <p class="alert alert-danger"><?=$erorr?></p>
        <?php endforeach; ?>
    <?php endif; ?>

    <input type="hidden" name="_token" value="<?=csrf_token()?>">
    <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" placeholder="Bank name" name="name">
    </div>
    <button type="submit" class="btn btn-primary">Add</button>
</form>

银行表

CREATE TABLE `banks` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

在banks / add视图中,我有$ errors和session(&#39; status&#39;)变量的格式和2个var_dump,但它们总是NULL。否则,表单验证器工作正常,如果它传递了我定义的规则,它会将我的输入插入到数据库中。

任何人都知道是什么导致我的错误无法显示?

2 个答案:

答案 0 :(得分:1)

在你的银行/ add.php

<p class="alert alert-danger"><?=$erorr?></p>

$ erorr 错误

答案 1 :(得分:0)

如果您正在使用laravel 5.2尝试删除路由组上的Web中间件,这将解决您的问题。为什么?因为RouteServiceProvider类会为你添加它。

第53-60行,截至撰写本文时。

  protected function mapWebRoutes(Router $router)
    {
        $router->group([
            'namespace' => $this->namespace, 'middleware' => 'web',
        ], function ($router) {
            require app_path('Http/routes.php');
        });
    }