Reputation: 471
First of all, I want to say that I've already search this problem before ask this question. My problem is, I am writing restful controller in Laravel 5.1. Below is my code:
1- Here is 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- Here form of 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- Here route that I declaire in my route.php
Route::resource('hocsinh', 'HocSinhController');
Actually In "HocSinhController.php" I already import the model "HocSinh" like this: "use App\HocSinh;" But it's still appear the error. When I type the url: "http://localhost/hocsinh/create", the "add.blade.php" form will be show, after I enter all information and click "Thêm" button, It's will appear error: "creating default object from empty value".
Please help me to check it out.
Thanks you so much
Upvotes: 0
Views: 84
Reputation: 1345
This is how you get
the values from your form using the $request
variable:
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();
}
You need to use $request
's get()
method.
Upvotes: 0