Reputation: 85
I am following a tutorial that shows how to connect to MySql using laravel, but while trying to update the values I ran into an error, I did try to find something similar but failed at that. The answers I found said that the object must be empty, but if I'm updating an existing values it's not empty. A tutorial I am following https://www.webslesson.info/2018/01/insert-update-delete-in-mysql-table-laravel-tutorial.html
So I have a form that displays the data from database in a file index.blade.php with a edit, a form that displays specific user data in a fine edit.blade.php and the methods in StudentController.php file.
They look like this:
Table of the user data and the edit button index.blade.php
<table class="table table-bordered">
<tr>
<th>First name</th>
<th>Last name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
@foreach($students as $row)
<tr>
<th>{{$row['name']}}</th>
<th>{{$row['surname']}}</th>
<th><a href="{{action('StudentController@edit', $row['id'])}}" class="btn btn-primary">Edit</a></th>
<th></th>
</tr>
@endforeach
</table>
Form in the edit.blade.php file
<form action="{{action('StudentController@update','$id')}}" method="post">
{{csrf_field()}}
<input type="hidden" name="_method" value="PATCH">
<div class="form-group">
<input type="text" name="name" class="form-control" value="{{$student->name}}" placeholder="Enter first name">
</div>
<div class="form-group">
<input type="text" name="surname" class="form-control" value="{{$student->surname}}" placeholder="Enter last surname">
</div>
<div>
<input type="submit" class="btn btn-primary" value="Edit">
</div>
</form>
And the methods in the Student.Controller.php file
public function update(Request $request, $id)
{
$this->validate($request, [
'name'=> 'required',
'surname'=> 'required'
]);
$student = Student::find($id);
$student->name=$request->get('name');
$student->surname=$request->get('surname');
$student->save();
return redirect()->route('students.index')->with('success', 'Data Updated');
}
I get the error in StudentController.php file in the line: $student->name=$request->get('name');
Upvotes: 0
Views: 665
Reputation: 35337
You aren't verifying that a student was actually found. If there is no record found, find will return null.
A common practice is to use findOrFail and let Laravel throw an exception if a record with $id is not found.
$student = Student::findOrFail($id);
Or you can handle it yourself:
$student = Student::find($id);
if (!$student) {
return response(['error' => 'No student found']);
}
Upvotes: 3