gpt4 book ai didi

php - 你能在不使用 Laravel 5 在数据库中创建条目的情况下填充 Eloquent 模型吗

转载 作者:行者123 更新时间:2023-12-02 05:49:01 25 4
gpt4 key购买 nike

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

<?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']]);
}

我将输入传回原始表单,但该表单从 Website Eloquent 模型填充其值。 **如何从 $request->all() 获取输入进入$website

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

最佳答案

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

Call to a member function fill() on null

而不是使用 create() 您可以创建网站模型而不使用数据库插入

$website = new Website;
$website->fill($request->all());

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

关于php - 你能在不使用 Laravel 5 在数据库中创建条目的情况下填充 Eloquent 模型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30462397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com