how to solve this error in laravel: ErrorException (E_WARNING) Invalid argument supplied for foreach() - laravel

I am creating a medicine shop invoice system . So at that process, I am creating a invoice form where customer information and invoicing information store in a two different model Customer model and Invoice model.
My invoice form view code below;
<form action="{{url('/invoice')}}" method="post">
{{csrf_field()}}
<div class="form-row">
<div class="col-md-4 col-md-offset-2">
<label for="customerName">Customer Name:</label>
<input type="text" id="customerName" name="customerName" class="form-control"><br>
<label for="address"> Address:</label>
<input type="text" id="address" name="address" class="form-control"><br>
<label for="mobile"> Mobile No.:</label>
<input type="text" id="mobile" name="mobileNumber" class="form-control"><br>
</div>
<div class="col-md-4">
<label for="invoiceNo"> Invoice No.:</label>
<input type="text" id="invoiceNo" name="invoiceNum" class="form-control"><br>
<label for="date"> Date:</label>
<input type="date" id="date" name="date" class="form-control"><br>
</div>
</div>
<hr>
<table class="table table-bordered" cellpadding="10px" cellspacing="5px">
<thead>
<th>Meidicine Name:.</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
<th style="text-align: center"><i class="fas fa-plus-square plus "></i></th>
</thead>
<tbody>
<tr>
<td>
<select name="medicineName" id="" class="form-control-sm medicineName" >
#foreach($data as $item)
<option value="{{$item->id}}">{{$item->medicineName}}</option>
#endforeach
</select>
</td>
<td><input type="number" class="form-control-sm quantity" name="quantity"></td>
<td><input type="number" class="form-control-sm price" name="price"></td>
<td><input type="number" class="form-control-sm totalAmount" name="totalAmount"></td>
<td style="text-align: center"><i class="fas fa-times"></i></td>
</tr>
<tr><td><input type="submit" class="btn btn-info btn-sm" value="ADD"></td></tr>
</tbody>
</table>
</form>
In this invoice form medicine name came from another model Medicine using laravel eloquent relationship
my InvoiceController store method code below
public function store(Request $request)
{
$customer = new Customer();
$customer->fill($request->all());
if($customer->save()){
$id = $customer->id;
foreach($request->medicineName as $value => $key) --->error occurs
this line
{
$data = array(
'customer_id' => $id,
'medicine_id' => $value,
'invoiceNum' => $request->invoiceNum[$key],
'date' =>$request->date[$key],
'quantity' =>$request->quantity[$key],
'price' =>$request->price[$key],
'totalAmount'=> $request->totalAmount[$key]
);
Invoice::insert($data);
}
}
return back();
}
when I click ADD button to submit data two different model Customer & Invoice browser can show error look like
"ErrorException (E_WARNING)
Invalid argument supplied for foreach()"
How to solve this type of error, pls anyone can help me..

it's because $request->medicineName is just one element and not an array or collection, try it like this :
public function store(Request $request)
{
$customer = new Customer();
$customer->fill($request->all());
if($customer->save()){
$id = $customer->id;
$data = array(
'customer_id' => $id,
'medicine_id' => $request->medicineName,
'invoiceNum' => $request->invoiceNum,
'date' =>$request->date,
'quantity' =>$request->quantity,
'price' =>$request->price,
'totalAmount'=> $request->totalAmount
);
Invoice::insert($data);
}
return back();
}

Related

laravel store combined data as object in a single field

I am trying to store repeater data in database Using laravel. But for that I need to combine some data with different values.
my form looks like this--
<div v-for="(tab, tabIndex) in tabs" :key="tab.id">
<div class="col-md-4 offset-md-4 d-flex">
<label>HouseAreaTypes</label>
</div>
<div class="col-md-4 offset-md-4 d-flex">
<select
v-model="tab.selectedHouseType"
#change="getDecor(tabIndex)"
name="houseAreaTypeId">
<option v-for="houseType in houseTypes" :key="houseType.id" :value="houseType.id">{{ houseType.name }}</option>
</select>
<div class="col-md-4">
<button #click="addTab">
<i class="fa fa-plus"></i>
</button>
<button v-if="tabIndex > 0" class="btn btn-danger btn-sm mt-2 ml-2" #click="removeTab(tabIndex, tab)">
<i class="fa fa-minus"></i>
</button>
</div>
</div>
<div v-for="(row, rowIndex) in tab.rows" :key="row.id">
<table class="table table-borderless col-md-12">
<thead>
<th>DecorationType</th>
<th>Description</th>
<th class="col-md-2">Rate</th>
<th>Quantity</th>
<th class="col-md-2">TotalAmount</th>
<th class="col-md-2"></th>
</thead>
<tbody>
<td>
<select
v-model="row.selectedDecor"
#change="getDescription(tabIndex,rowIndex) "name="decId">
<option v-for="decorType in tab.decorTypes" :key="decorType.id" :value="decorType.id">
{{ decorType.name }}
</option>
</select>
</td>
<td class="col-md-3">
<input type="text" name="des" v-model="row.selectedDes"/>
</td>
<td class="col-md-2">
<input type="number" name="rate" v-model="row.selectedRate" #change="calculateLineTotal(tabIndex,rowIndex)"
/>
</td>
<td class="col-md-1">
<input type="number" min="0" name="qty" v-model="row.selectedQty" #change="calculateLineTotal(tabIndex,rowIndex)"
/>
</td>
<td class="col-md-3">
<input
type="number" name="totalAmount" v-model="row.line_total"/>
</td>
<td>
<button v-if="rowIndex == Object.keys(tab.rows).length -1" type="button" class="btn btn-success btn-sm mt-2 ml-2" #click="addRow(tabIndex)">
<i class="fa fa-plus"></i>
</button>
<button type="button"
#click="removeRow(rowIndex, row,tabIndex)">
<i class="fa fa-minus"></i>
</button>
</td>
</tbody>
</table>
<hr />
</div>
</div>
my migration looks like this--
Schema::create('house_area_carts', function (Blueprint $table) {
$table->id();
$table->integer('houseAreaTypeId')->nullable();
$table->text('houseAreaCartInfo')->nullable()->comment('Object (decorationTypeId, descriptionOfDecoration, qty, rate, totalAmount)');
$table->timestamps();
});
I already have done the frontend part using vue. Here I need to store multiple houseAreaTypeId but in the houseAreaCartInfo I need to commbine decorationTypeId, descriptionOfDecoration, qty, rate, totalAmount these datas. I am attaching an image so you understand well
Iamge to understand the topic
updates
in my controller --
public function createCart(Request $request, $id)
{
$cart = HouseAreaCart::create([
'houseAreaTypeId' => $request->houseAreaTypeId,
'houseAreaCartInfo' => $request->get('houseAreaCartInfo'),
'houseAreaCartInfo' =>[
'rate' => $request->rate,
'qty' => $request->qty,
'decId' => $request->decId,
'des' => $request->des,
'totalAmount' => $request->totalAmount
]
]);
dd($cart);
return response()->json($cart);
}
I am getting this after dd.
"houseAreaTypeId" => "2"
"houseAreaCartInfo" => "{"rate":["11","2"],"qty":["8","1"],"decId":["2","3"],"des":["Nostrum dolorem qui","Veniam architecto l"],"totalAmount":["88.00","2.00"]}"
But when I add another houseAreaTypeId it's showing only the last houseAreaTypeId I added.
Now how do I process multiple houseAreaTypeId in my controller and save it in the database?
The easieast way will be attribute casting to json or array:
// add to the model:
protected $casts = [
'houseAreaCartInfo' => 'array',
];
https://laravel.com/docs/9.x/eloquent-mutators#array-and-json-casting
In the controller you would simply assign to the model an array from your request (or use update method on the model - will work the same):
$cartModel->houseAreaCartInfo = $request->get('houseAreaCartInfo');
then whenever you get that value it will come as an array (same as in the request):
$cartModel->houseAreaCartInfo
[
'des' => ...,
'qty' => ...,
...
]
In your request I suggest validation to make sure this value comes as an array and is stored properly
https://laravel.com/docs/9.x/validation#validating-arrays
Your migration should like,
$table->text('houseAreaCartInfo')->nullable()
anf then, Make sure your request is something like the following,
$request = [
'houseAreaTypeId' => 'required|int', //or array as your choice
'houseAreaCartInfo' => 'required|array',
'houseAreaCartInfo.*.decerationType' => 'required|array', //or int as your choice
'houseAreaCartInfo.*.description' => 'required|string',
'houseAreaCartInfo.*.rate' => 'required|int',
'houseAreaCartInfo.*.quantity' => 'required|int',
];
Then in your model, cast the column as array,
protected $cast = [
'houseAreaCartInfo' => 'array'
];
Finally, you can create model by using eloquent, There should be no error.

laravel, get data by id using foreach

how do I fetch the data based on the insurance_id on the companion db? the insurance_id is dependent on another table called "insurances" if that helps. the db is this:
and the view looks like this:
here's the view:
<table class="table" id="companions_table">
<thead>
<tr>
<th>Name</th>
<th>Date of Birth</th>
<th>IC No</th>
<th>Relationship</th>
</tr>
</thead>
<tbody>
#foreach (old('companions', $companions->count() ? $companions : ['']) as $companion)
<tr id="companion{{ $loop->index }}">
<td>
<input type="text" name="companion_name[]" id="companion_name[]" class="form-control" value="{{ old('companion_name', $companion->companion_name) }}" />
</td>
<td>
<div class="input-group date" data-provide="datepicker" data-date-format="dd-mm-yyyy" data-date-today-highlight="true" data-date-end-date="0d">
<input class="form-control" type="text" name="dob[]" id="dob[]" value="{{ old('dob', $companion->dob) }}">
<div class="input-group-addon">
<span class="fa fa-calendar"></span>
</div>
</div>
</td>
<td>
<input type="text" name="ic[]" id="ic[]" class="form-control" value="{{ old('ic', $companion->ic) }}" />
</td>
<td>
<input type="text" name="relationship[]" id="relationship[]" class="form-control" value="{{ old('relationship', $companion->relationship) }}" />
</td>
</tr>
#endforeach
<tr id="companion{{ count(old('companions', $companions->count() ? $companions : [''])) }}"></tr>
/tbody>
</table>
<div class="row">
<div class="col-md-12">
<button id="add_row" class="btn btn-default pull-left">+ Add Row</button>
<button id='delete_row' class="pull-right btn btn-danger">- Delete Row</button>
</div>
my controller:
public function edit(Insurance $insurance)
{
abort_if(Gate::denies('insurance_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');
$customers = CustomerProfile::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');
$products = Product::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');
$sales_2s = User::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');
$companions = Companion::all();
$insurance->load('customer', 'product', 'sales_2', 'team', 'companions');
$approvers = Role::findOrFail(3)->users()->get();
return view('admin.insurances.edit', compact('customers', 'products', 'sales_2s', 'insurance', 'approvers', 'companions'));
}
it keeps fetching all the data on the table, basically disregarding the insurance_id. how do I fix this?
All of the companions are being fetched, regardless of the insurance_id, because of the following line:
$companions = Companion::all();
If you only want companions with the current insurance_id, the quickest way would be to replace the previously mentioned line with:
$companions = Companion::where('insurance_id', $insurance->id)->get();
This should work, however the conventional way to handle this relationship in Laravel would be by adding the following function to your Insurance model:
use App\Models\Companion; // or wherever your model happens to be located
public function companions()
{
return $this->hasMany(Companion::class);
}
And replacing the line mentioned at the beginning with:
$companions = $insurance->companions;

Laravel - Dynamic input form duplicates record during update

I am trying to create Dynamic input form array using Laravel-5.8
I have these two models:
class HrLeaveType extends Model
{
protected $table = 'hr_leave_types';
protected $fillable = [
'company_id',
'leave_type_name',
'no_of_days',
'leave_type_code',
];
}
class HrLeaveTypeDetail extends Model
{
protected $table = 'hr_leave_type_details';
protected $fillable = [
'id',
'leave_type_id',
'company_id',
'employment_type_code',
'no_of_days',
];
public function leavetype()
{
return $this->belongsTo('App\Models\Hr\HrLeaveType', 'leave_type_id', 'id');
}
public function employmenttype()
{
return $this->belongsTo('App\Models\Hr\HrEmploymentType', 'employment_type_code', 'employment_type_code' );
}
}
Request Rules:
class UpdateLeaveTypeRequest extends FormRequest
{
public function rules()
{
'leave_type_name' =>
[
'required',
Rule::unique('hr_leave_types')->where(function ($query) {
return $query
->where('leave_type_name', 1)
->where('company_id', 1);
})->ignore($this->leave_type)
],
'leave_type_code' => [
'nullable',
'string',
'max:10',
],
'no_of_days' => 'required|array',
'no_of_days.*' => [
'required',
'numeric',
'max:120'
],
'employment_type_code' => 'required|array',
'employment_type_code.*' => [
'required',
],
];
}
}
And then the Controller:
public function edit($id)
{
$userCompany = Auth::user()->company_id;
$leavetype = HrLeaveType::findOrFail($id);
$employmenttypes = HrEmploymentType::where('company_id', $userCompany)->get();
$leavetypedetails = HrLeaveTypeDetail::where('leave_type_id', $id)->get();
return view('leave.leave_types.edit')
->with('leavetype', $leavetype)
->with('leavetypedetails', $leavetypedetails)
->with('employmenttypes', $employmenttypes);
}
public function update(UpdateLeaveTypeRequest $request, $id)
{
DB::beginTransaction();
try {
$leavetype = HrLeaveType::findOrFail($id);
$leavetype = new HrLeaveType();
$leavetype->leave_type_name = $request->leave_type_name;
$leavetype->leave_type_code = $request->leave_type_code;
$leavetype->description = $request->description;
$leavetype->save();
HrLeaveTypeDetail::where('leave_type_id', $id)->delete();
foreach ( $request->employment_type_code as $key => $employment_type_code){
$leavetypedetail = new HrLeaveTypeDetail();
$leavetypedetail->no_of_days = $request->no_of_days[$key];
$leavetypedetail->employment_type_code = $request->employment_type_code[$key];
$leavetypedetail->leave_type_id = $leavetype->id;
$leavetypedetail->save();
}
DB::commit();
Session::flash('success', 'Leave Type is updated successfully');
return redirect()->route('leave.leave_types.index');
}
catch (\Illuminate\Database\QueryException $e){
DB::rollback();
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
Session::flash('error', 'Duplicate Entry! Please try again');
}
return back();
}
catch (Exception $exception) {
DB::rollback();
Session::flash('error', 'Leave Type update failed!');
return redirect()->route('leave.leave_types.index');
}
}
view blade
<form action="{{route('leave.leave_types.update', ['id'=>$leavetype->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Leave Type Name:<span style="color:red;">*</span></label>
<input type="text" name="leave_type_name" placeholder="Enter leave type name here" class="form-control" value="{{old('leave_type_name',$leavetype->leave_type_name)}}">
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Leave Type Code:</label>
<input type="text" name="leave_type_code" placeholder="Enter leave type code here" class="form-control" value="{{old('leave_type_code',$leavetype->leave_type_code)}}">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Description</label>
<textarea rows="2" name="description" class="form-control" placeholder="Enter Description here ..." value="{{old('description',$leavetype->description)}}">{{old('description',$leavetype->description)}}</textarea>
</div>
</div>
<div class="col-sm-12">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Employment Type<span style="color:red;">*</span></th>
<th scope="col">Leave Days<span style="color:red;">*</span></th>
<th scope="col"><a class="btn btn-info addRow"><i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
#foreach($leavetypedetails as $leavetypedetail)
<tr>
<td width="60%">
<select class="form-control select2bs4" data-placeholder="Select Employment Type" tabindex="1" name="employment_type_code[]">
<option name="employment_type_code[]" value="{{$leavetypedetail->employmenttype->employment_type_code}}">{{$leavetypedetail->employmenttype->employment_type_name}}</option>
#foreach($employmenttypes as $employmenttype)
<option name="employment_type_code[]" value="{{$employmenttype->employment_type_code}}">{{$employmenttype->employment_type_name}}</option>
#endforeach
</select>
</td>
<td width="35%"><input value="{{$leavetypedetail->no_of_days}}" type="text" name="no_of_days[]" class="form-control" max="120"></td>
<td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.update') }}</button>
<button type="button" onclick="window.location.href='{{route('leave.leave_types.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.addRow').on('click', function () {
addRow();
});
function addRow() {
var addRow = '<tr>\n' +
' <td width="60%"><select class="form-control select2bs4" data-placeholder="Choose Employment Type" tabindex="1" name="employment_type_code[]">\n' +
' <option value="0" selected="true" disabled="true">Select Employment Type</option>\n' +
' #if($employmenttypes->count() > 0 )\n' +
' #foreach($employmenttypes as $employmenttype)\n' +
' <option value="{{$employmenttype->employment_type_code}}">{{$employmenttype->employment_type_name}}</option>\n' +
' #endforeach\n' +
' #endif\n' +
' </select></td>\n' +
' <td width="35%"><input type="number" name="no_of_days[]" placeholder="Enter leave days here" class="form-control no_of_days" max="120"></td>\n' +
' <td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>\n' +
' </tr>';
$('tbody').append(addRow);
addRemoveListener();
};
addRemoveListener();
});
When I submitted the form for update,
I observed that the application save another data (duplicated) the model HrLeaveType into the database.
It replace the value of employment_type_code in the HrLeaveTypeDetail model with the latest row in HrLeaveType.
Why am I having these issues and how do I resolve it?
Thanks

adding data in table show me error when i add the relation ships

I am a beginner in laravel I made a relationship one to many between the table of father and the table of eleve after that when i try to add a a new student he shows this error
SQLSTATE[HY000]: General error: 1364 Field 'father_id' doesn't have a default value (SQL: insert into eleves (nom, prenom, adresse, date_naiss, sexe, nationnalite, niveau_scolaire, updated_at, created_at) values (mohamed, ferchichi, tunis, 2018-07-22, Un garçon, tunisen, 1, 2019-05-13 10:56:28, 2019-05-13 10:56:28))
how I can correct this problem i need your help
this is the table of eleve
public function up()
{
Schema::create('eleves', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('father_id');
$table->string('nom');
$table->string('prenom');
$table->date('date_naiss');
$table->string('sexe');
$table->string('nationnalite');
$table->string('niveau_scolaire');
$table->string('adresse');
$table->foreign('father_id')->references('id')->on('fathers')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
}
the model of eleve
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Eleve extends Model
{
protected $fillable = ['nom', 'father_id', 'prenom', 'date_naiss', 'sexe', 'nationnalite', 'niveau_scolaire', 'adresse'];
public function father()
{
return $this->belongsTo('App\Father');
}
}
the model of father
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Father extends Model
{
protected $fillable = ['nom', 'prenom', 'adresse', 'num_tel', 'email', 'login', 'date_naissance ', 'password'];
public function user()
{
return $this->belongsTo(User::class);
}
public function eleve()
{
return $this->hasMany('App\Eleve');
}
and the blade of eleve
<section id="no-more-tables">
<table class="table table-bordered table-striped table-condensed cf">
<thead class="cf">
<tr>
<th>id-eleve</th>
<th>Nom</th>
<th>Prenom</th>
<th>Adresse</th>
<th>Age</th>
<th>Sexe</th>
<th>Nationnalité</th>
<th>Niveau scolaire </th>
<th>les actions</th>
</tr>
</thead>
<tbody>
#foreach($eleves as $eleve)
<tr>
<td class="numeric" data-title="id-parent">{{$eleve->id}}</td>
<td class="numeric" data-title="Nom">{{$eleve->nom}}</td>
<td class="numeric" data-title="Prenom">{{$eleve->prenom}}</td>
<td class="numeric" data-title="Adresse">{{$eleve->adresse}}</td>
<td class="numeric" data-title="Numéro telephone">{{$eleve->date_naiss}}</td>
<td class="numeric" data-title="Email">{{$eleve->sexe}}</td>
<td class="numeric" data-title="Login">{{$eleve->nationnalite}}</td>
<td class="numeric" data-title="Password">{{$eleve->niveau_scolaire}}</td>
<td>
<button href="#editEmployeeModal" class="btn btn-theme" data-target="#editEmployeeModal "
data-mytitle="{{$eleve->nom}}" data-myprenom="{{$eleve->prenom}}"
data-myadresse="{{$eleve->adresse}}" data-myage="{{$eleve->date_naiss}}"
data-mysexe="{{$eleve->sexe}}" data-mynationalite="{{$eleve->nationnalite}}"
data-myniveau="{{$eleve->niveau_scolaire}}" data-catid={{$eleve->id}} class="edit"
data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit"></i>
</button>
<button href="#deleteEmployeeModal" class="btn btn-theme" data-target="#deleteEmployeeModal"
data-catid={{$eleve->id}} class="delete" data-toggle="modal"> <i class="material-icons"
data-toggle="tooltip" title="Delete"></i> </button>
</td>
</tr>
</tbody>
#endforeach
</table>
<div class="text-center">
{{ $eleves->links() }}
</div>
<div class="clearfix">
<div class="hint-text">Affichage de <b>5</b> sur <b>25</b> entrées</div>
<div id="addEmployeeModal" href="create" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{route('eleves.store')}}" method="post">
{{csrf_field()}}
<div class="modal-header">
<h4 class="modal-title">Ajouter un éléve</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>nom</label>
<input type="text" id="nom" name="nom" class="form-control" required>
</div>
<div class="form-group">
<label>prenom</label>
<input type="text" id="prenom" name="prenom" class="form-control" required>
</div>
<div class="form-group">
<label>adresse</label>
<textarea name="adresse" id="adresse" class="form-control" required></textarea>
</div>
<div class="form-group">
<label for="start">Date Naissance</label>
<input type="date" id="date_naiss" name="date_naiss" value="2018-07-22" min="2018-01-01"
max="2030-12-31">
<!-- <label>Date Naissance</label>
<input type="text" name=" date_naiss" id="date_naiss" class="form-control" required>
</div> -->
</div>
<div class="form-group">
<div>
<input type="radio" id="sexe" name="sexe" value="une fille" checked>
<label for="sexe">une fille</label>
</div>
<div>
<input type="radio" id="sexe" name="sexe" value="Un garçon">
<label for="sexe">Un garçon</label>
</div>
</div>
<div class="form-group">
<label>Nationnalité</label>
<input type="text" name="nationnalite" id="nationnalite" class="form-control" required>
</div>
<div class="form-group">
<label>Niveau Scolaire</label>
<input type="text" name="niveau_scolaire" id="niveau_scolaire" class="form-control"
required>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Annuler">
<input type="submit" class="btn btn-success" value="Ajouter">
</div>
</form>
</div>
</div>
</div>
</div>
</section>
the controller of student
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Eleve;
class EleveController extends Controller
{
public function index()
{
$eleves = Eleve::paginate(5);
return view('admin.eleves',compact('eleves'));
}
public function store(Request $request)
{
Eleve::create($request->all());
session()->flash('success',' Cet nouvel éléve a été enregistré avec succés');
return redirect()->back();
}
public function update(Request $request, $id)
{
$eleve = Eleve::findOrFail($request->eleve_id);
$eleve->update($request->all());
session()->flash('success','Cet éléve a été modifié avec succés');
return redirect()->back();
}
public function destroy(Request $request)
{
$eleve = Eleve::findOrFail($request->eleve_id);
$eleve->delete();
session()->flash('success','Cet éleve a été supprimé avec succés');
return redirect()->back();
}
}
The father_id field in the eleves table is required. You either have to make it optional or, more likely, add it to your form.
To make the field optional replace this line
$table->unsignedBigInteger('father_id');
with
$table->unsignedBigInteger('father_id')->nullable();
To add it to the form you would probably use a <select>, something like:
<form ...>
<select name="father_id">
#foreach(\App\Father::all() as $father)
<option name="{{ $father->id }}">{{ $father->nom }}</option>
#endforeach
</select>
Note: It's bad practice to call the database inside a view file. A better approach would be to load the Fathers inside the controller and pass it to the view:
public function create()
{
$fathers = Father::all();
return view('...', ['fathers' => $fathers]);
}
and in the view:
<form ...>
<select name="father_id">
#foreach($fathers as $father)
<option name="{{ $father->id }}">{{ $father->nom }}</option>
#endforeach
</select>
in the EleveController i add use App\Father; and i add this function
public function create()
{
$fathers= Father::all();
return view('admin.eleves',compact('fathers'));
}
and in the eleve blade.php i add this
<select name="father_id">
#foreach($fathers as $father)
<option name="{{ $father->id }}">{{ $father->nom }}</option>
#endforeach
</select>
the problem is that shows me the same error "Undefined variable: fathers "

How do I pass values from views to controller

In a view, When we route a button to a function inside the controller, how can we pass two or more values from present during that view.
I was practicing creating a result management system of students. In the view routed from index of ResultController, we have link options to view mark sheet of class ..or individual student. When we click on select class, it redirects to a view where there is two dropdowns to choose the class and batch of students. When we choose respected class and batch, the values class_id and batch_id is routed to function result inside ResultControler, we select students from that class and batch.. and respected subjects and return a view. In that view, we show the marksheet of students(if theres one), and below I have included a button to add marks/create marksheet.
But, I am so confused how I can pass those class_id and batch_id to create function inside ResultController, from the button.
public function index()
{
return view('resultmainpage');
}
public function choose()
{
$classes= Sclass::all();
$batches= Batch::all();
return view('chooseclassbatchresult',compact('classes','batches'));
}
public function result(Request $request)
{
$classid = $request->class;
$batchid = $request->batch;
//dd($batchid);
$students =Student::where('sclass_id',$classid)
->where('batch_id', $batchid)
->whereHas('subject')
->get();
$class= Sclass::findOrFail($classid);
return view('showstudentresult',compact('students','class','classid','batchid'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
// I need class_id and batch_id here
// dd($classidd);
$students = Student::where('sclass_id',$classid)
->where('batch_id',$batchid)
->whereDoesntHave('subject')
->get();
//dd($students);
Route:
Route::get('/rms','MainPageController#index')->name('rms');
Route::get('results/choose','ResultController#choose')->name('chooseresult');
Route::post('/showstudentresult','ResultController#result')->name('showstudentresult');
Route::resource('results','ResultController');
chooseclassbatchresult.blade.php
#extends('layout')
#section('content')
<h1>Please Choose the Class and Respected Batch Of Student For Result</h1>
</br>
</br>
<form action="{{route('showstudentresult')}}" method="post">
#csrf
<p>
<label>Class Name</label>
<select name='class'>
#foreach($classes as $class)
<option value="{{$class->id}}">{{$class->name}}</option>
#endforeach
</select>
</br>
</p>
<p>
<label>Batch</label>
<select name='batch'>
#foreach($batches as $batch)
<option value="{{$batch->id}}">{{$batch->batch}}</option>
#endforeach
</select>
</p>
</br>
<input type="submit" value="View">
</form>
</br>
</br>
</br>
<h1>OR</h1>
<h3>
<button><a href={{route('students.create')}}>Add New Student</a></button>
</h3>
#endsection
Showstudentresult.blade.php
#extends('layout')
#section('content')
<table border=1>
<thead>
<tr>
<th>S.N</th>
<th>Name</th>
<th>Roll NO</th>
#foreach($class->subjects as $subject)
<th>{{$subject->name}}</th>
#endforeach
<th>Total Mark</th>
<th>Percentage</th>
<th>Division</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php $id = 1; ?>
#foreach($students as $student)
<tr>
<td><?php echo $id;?></td>
<td>{{$student->name}}</td>
<td>{{$student->roll}}</td>
#foreach($student->subjects as $subject)
<th>{{$subject->pivot->mark}}</th>
#endforeach
<td>{{$student->result->total_mark}}</td>
<td>{{$student->result->percentage}}</td>
<td>{{$student->result->division}}</td>
<td>
<table>
<tr>
<td>
<button>Edit</button>
</td>
<td>
<form action="{{route('students.destroy',$student->id)}}" method="post">
#csrf
#method('DELETE')
<input type="submit" value="Delete"
onclick="return confirm('Are you sure you want to delete the student?')">
</form>
</td>
</tr>
</table>
</td>
</tr>
<?php $id++ ?>
#endforeach
</tbody>
</table>
</br>
</br>
<button><a href={{results.create}}>Create New</a></button>
#endsection
As Ross Wilson suggested in comment
I would suggest creating a separate page similar to
chooseclassbatchresult with a form that submits the data to create
Add a route in your routes files like:
Route::post('/createPage', 'ResultController#createPage')->name('createPage');
In ResultController add the following function:
public function createPage(Request $request)
{
// Get your required ids here
$classid = $request->class;
$batchid = $request->batch;
//dd($classid);
//dd($batchid );
}
In your chooseclassbatchresult view add another form like below
<form action="{{ route('createPage') }}" method="post">
#csrf
<p>
<label>Class Name</label>
<select name='class'>
#foreach($classes as $class)
<option value="{{$class->id}}">{{$class->name}}</option>
#endforeach
</select>
</br>
</p>
<p>
<label>Batch</label>
<select name='batch'>
#foreach($batches as $batch)
<option value="{{$batch->id}}">{{$batch->batch}}</option>
#endforeach
</select>
</p>
</br>
<input type="submit" value="View">
</form>
Thank you for your response. I got a way around my question. I learned that you can use input type="hidden" to carry those values back to the controller.
Create a route:
Route::post('/create_res', 'ResultController#create_res')->name('results.create_res');
In the View, chooseclassbatchresult.blade.php
<form action="{{route('results.create_res')}}" method="POST">
#csrf
<input type="hidden" name="classid" value="{{$classid}}">
<input type="hidden" name="batchid" value="{{$batchid}}">
<input type="submit" value="Create Mark Sheet">
</form>
In the Result Controller;
public function create_res(Request $request){
$classid = $request->classid;
$batchid = $request->batchid;
$students = Student::where('sclass_id',$classid)
->where('batch_id',$batchid)
->whereDoesntHave('subject')
->get();
$classes= Sclass::findOrFail($classid);
//dd($students);
return view('addmarksheet',compact('students','classes'));
}

Resources