Reputation: 45
I'm trying to save multiple table rows to the database. And when I try run my code, nothing saves to the database. Here's my code for the blade template:
<form action="{{ action('BorrowBookController@store') }}" method="POST">
@csrf
<div class="form-group">
<select class="form-control" name="student[]">
@foreach( $students as $row )
<option value="{{ $row->id }}">{{ $row->FirstName }} {{ $row->LastName }}</option>
@endforeach
</select>
</div>
<h2>List of Books Borrowed</h2>
<div class="table-responsive">
<table id="books-detail-table" class="table table-striped table-bordered" style="width: 100%;">
<thead>
<tr>
<th>Title</th>
<th>Quantity</th>
<th>
<button id="addBtn" type="button" class="btn btn-sm btn-outline-success">
<span data-feather="plus"></span>
</button>
</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>
<div class="form-group">
<select class="form-control" name="book[]">
@foreach( $books as $row )
<option value="{{ $row->id }}">{{ $row->title}}</option>
@endforeach
</select>
</div>
</td>
<td>
<div class="form-group">
<input type="number" class="form-control form-control-sm" name="quantity[]" placeholder="Qty" required>
</div>
</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group mr-2">
<button type="submit" class="btn btn-success">
<span data-feather="save"></span>
Submit
</button>
</div>
</div>
</form>
And here's my controller for reference:
BorrowBookController@store
public function store(Request $request)
{
$timeToday = Carbon::now();
$this->validate($request, [
'student_id' => 'required',
'book_id' => 'required',
'quantity' => 'required',
]);
$student_id = $request->input('student[]');
$book_id = $request->input('book[]');
$quantity = $request->input('quantity[]');
$date_borrowed = $timeToday->toDateTimeString();
$return_date = 0;
$status = "ACTIVE";
for ($i = 0; $i < count($student_id); $i++) {
$data = [
'student_id' => $student_id[$i],
'book_id' => $book_id[$i],
'quantity' => $quantity[$i],
'date_borrowed' => $date_borrowed[$i],
'return_date' => $return_date[$i],
'status' => $status,
];
BorrowBook::create($data);
}
return redirect('/borrow_books')->with('success', 'Successfully borrowed a book.');
}
I don't really know where my problem is. It's either on the controller or the blade template. How can I achieve in solving this kind of issue? I hope everyone can help me with this. Thank you.
Upvotes: 0
Views: 1092
Reputation: 115
check the model class BorrowBook and set the fillable property without the column name inside fillable you can not add data through create method
<?php
class BorrowBook extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'student_id' ,
'book_id',
'quantity' ,
'date_borrowed' ,
'return_date' ,
'status'];
}
Upvotes: 1