【问题标题】:Error: Creating default object from empty value laravel 5.1错误:从空值 laravel 5.1 创建默认对象
【发布时间】:2015-10-21 20:07:54
【问题描述】:

首先,我想说在问这个问题之前我已经搜索过这个问题。 我的问题是,我在 Laravel 5.1 中编写 restful 控制器。 以下是我的代码:

1- 这里是 HocSinhController.php,

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

public function store(Request $request)
{
    $hocinh = new HocSinh();
    $hocsinh->hoten = $request->txtHoTen;
    $hocsinh->toan = $request->txtToan;
    $hocsinh->ly = $request->txtLy;
    $hocsinh->hoa = $request->txtHoa;
    $hocsinh->save();
}

2- 这里是 add.blade.php 的形式

<form method="POST" action="{!! route('hocsinh.store') !!}" name="frmAdd">
        <input type= "hidden" name="_token" value="{!! csrf_token() !!}" />
        <div class="form-group">
          <label for="lblHoTen">Họ Tên Học Sinh</label>
          <input type="text" class="form-control" name="txtHoTen" />
        </div>
        <div class="form-group">
          <label for="lblToan">Điểm Môn Toán</label>
          <input type="text" class="form-control" name="txtToan" />
        </div>
        <div class="form-group">
          <label for="lblLy">Điểm Môn Lý</label>
          <input type="text" class="form-control" name="txtLy" />
        </div>
        <div class="form-group">
          <label for="lblHoa">Điểm Môn Hóa</label>
          <input type="text" class="form-control" name="txtHoa" />
        </div>
        <button type="submit" class="btn btn-default">Thêm</button>
      </form>

3- 我在 route.php 中声明的路线

Route::resource('hocsinh', 'HocSinhController');

实际上在“HocSinhController.php”中,我已经像这样导入了模型“HocSinh”:“use App\HocSinh;”但它仍然出现错误。当我输入网址:“http://localhost/hocsinh/create”时,将显示“add.blade.php”表单,输入所有信息并单击“Thêm”按钮后,将出现错误:“从空值创建默认对象” .

请帮我看看。

非常感谢

【问题讨论】:

  • $hocinh = new HocSinh(); 更改为$hocsinh = new HocSinh();
  • 天哪,谢谢你,这是我的错 :(

标签: php laravel laravel-5.1


【解决方案1】:

这就是您使用$request 变量get 表单中的值的方式:

public function store(Request $request)
{
    $hocinh = new HocSinh();
    $hocsinh->hoten = $request->get('txtHoTen');
    $hocsinh->toan = $request->get('txtToan');
    $hocsinh->ly = $request->get('txtLy');
    $hocsinh->hoa = $request->get('txtHoa');
    $hocsinh->save();
}

你需要使用$requestget()方法。

【讨论】:

  • 我已经修好了,谢谢。但我的错误在于 $hocsinh 变量。更正此变量后,它就起作用了。我认为 $request->txtHoTen 和 $request->get('txtHoTen') 都可以。
猜你喜欢
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
相关资源
最近更新 更多