【问题标题】:Form Model Binding - Not populating form field value表单模型绑定 - 不填充表单字段值
【发布时间】:2015-05-13 11:42:10
【问题描述】:

我是 Laravel 的新手,但可以使用它。我遇到了表单模型绑定问题,我已将表单模型设置为绑定并在我的数据库中设置数据,但该字段未填充以匹配。

我怀疑,我错过了一些明显的东西,虽然不确定。

我当前的代码是:

路线

Route::get('admin/user/bank-details', array('as' => 'bank.edit', function()
{
    $user_id = Auth::id();

    $bank_details = Banks::whereRaw("(user_id = '".$user_id."')")->get();

    // Return Our View...
    return View::make('user.update_bank')
               ->with('bank_details', $bank_details);
}));

查看

{ Form::model($bank_details, array('route' => 'bank.edit')) }}
 <div class="form-group">
  <label for="bank_sortcode">Bank Sortcode</label>
  {{ Form::text('bank_sortcode', null, array('class' => 'form-control sortcode', 'placeholder' => 'Bank Sort Code')) }}
 </div><!-- /.form-group -->
{{ Form::close() }}

型号

class Banks extends \Eloquent {

    // Don't forget to fill this array
    protected $fillable = array('bank_sortcode');

    use SoftDeletingTrait;

    protected $dates = ['deleted_at'];

    protected $primaryKey = "bank_id";
}

我的数据库表包含一个名为 bank_sortcode 的字段,其值当前设置为“20-20-20”

谢谢

【问题讨论】:

  • 我注意到了一些事情。你没有控制器。这是你的意图吗?此外,您不需要使用 whereRaw,只需使用 Banks::where('user_id', $user_id)-&gt;get()
  • 嗨@wiesson 我确实有一个控制器,但它只包含处理发布数据的方法。已更改 where 子句以符合您的建议
  • 看看这节课:laracasts.com/series/laravel-5-fundamentals/episodes/18也许这已经解决了你的问题。如果没有,我会帮你解答。
  • @wiesson 我看到 laracast 主要是 Laravel 5。
  • 哦,我想我错了——我想到了路由模型绑定!但是您正在寻找表单模型绑定。 Laracasts 还为 laravel 4.X 提供(免费)课程。

标签: php forms laravel laravel-4


【解决方案1】:

您只能使用单个模型填充表单。所以改变

$bank_details = Banks::whereRaw("(user_id = '".$user_id."')")->get();

到这里

$bank_details = Banks::where('user_id', $user_id)->first();

使用这个函数你只能得到一个记录(不是记录数组)——所以它应该可以工作。

附言你应该只在非常非常非常原始的情况下使用raw 雄辩的查询。否则,您会造成不必要的安全风险。

【讨论】:

  • 嗨@The Shift Exchange 非常感谢您的回答。那成功了。 ->first() 参数是有意义的。我没有意识到您可以将替代值传递给 eloquent 查询而不是 DB Raw 查询。
猜你喜欢
  • 1970-01-01
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
相关资源
最近更新 更多