您是否可以使用Laravel 5填充Eloquent模型而无需在数据库中创建条目

时间:2015-05-26 15:09:21

标签: php laravel eloquent laravel-5

当我在数据库表网站中添加或编辑条目时,我会加载要修改的网站实例(或用于创建网站的空白实例)。这很好用,这是我的控制器:

<?php namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Request;
use App\Models\User;
use App\Models\Status;
use App\Models\Website;

class WebsitesController extends Controller {

    /**
     * Show / Process the create website form to the user.
     *
     * @return Response
     */
    public function create()
    {
        $statuses = Status::all();
        $users = User::all();
        $website = Website::find(0);
        return view('admin/websites/create', [
            'statuses' => $statuses,
            'users' => $users,
            'website' => $website
        ]);
    }

    public function update($id)
    {
        $statuses = Status::all();
        $users = User::all();
        $website = Website::findOrFail($id);
        return view('admin/websites/update', [
            'statuses' => $statuses,
            'users' => $users,
            'website' => $website
        ]);
    }

}

问题是我提交表单时出错了。用户返回到页面并显示错误。我还传回用户输入,以便我可以用他们输入的内容重新填充表单。但是如果在没有实际保存到数据库的情况下,如何使用输入中的值替换网站中的值?我一整天都在玩这个,但找不到合适的解决方案。

我的创建方法是:

public function postCreate(Request $request)
{
    $v = Validator::make($request->all(), Website::rules());
    if ($v->fails())
    {
        return redirect()->back()->withInput()->withErrors($v);
    }
    $website = Website::create($request->all());
    return redirect()->action('Admin\HomeController@index')->with('messages', [['text' => 'Website created', 'class' => 'alert-success']]);
}

我将输入传递回原始表单,但表单从网站Eloquent模型中填充其值。 **如何将$request->all()的输入转换为$website

我已尝试使用fill(),但在创建函数中使用它时我得到Call to a member function fill() on null

1 个答案:

答案 0 :(得分:11)

create方法尝试将记录插入数据库,如果成功则返回模型的实例。如果将create()与无效值一起使用,则插入将失败。我认为这就是为什么有一个null而不是模型的实例,这会导致你的错误:

  

调用null

上的成员函数fill()

而不是使用create()您可以使用

创建没有数据库插入的网站模型
$website = new Website;
$website->fill($request->all());

在运行验证之前。如果验证通过,那么您可以使用$website->save();插入数据库,否则它将不会尝试保存,但该模型应该可供您在表单中使用。