laravel, get data by id using foreach - laravel

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;

Related

Problem with Laravel CRUD (Edit Function)

Good day everyone. I'm quite new to new to Laravel and was doing some basic CRUD coding, I was able to code the add and view function, but I'm having a hard time with the edit and delete function.
I have 4 files, the master blade file, the web.php (routing), the blade file and the Form Controller.
This is the promo.blade.php file:
<table class="table table-striped" id="table1" >
<thead>
<tr>
<th class="text-center">ACTION</th>
<th class="text-center">Offer ID</th>
<th class="text-center">Promo Name</th>
<th class="text-center">Promo Price</th>
<th class="text-center">Status</th>
</tr>
</thead>
<tbody>
#foreach ($data as $key => $item)
<tr>
<td class="text-center">
<a href="#" data-bs-toggle="modal" data-bs-target="#show" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-success"><i class="bi bi-eye-fill"></i></span>
</a>
<a href="#" data-bs-toggle="modal" data-bs-target="#edit" data-mainid="{{$item->id}}" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-primary"><i class="bi bi-pencil-square"></i></span>
</a>
<a href="#" data-bs-toggle="modal" data-bs-target="#delete" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-danger"><i class="bi bi-trash"></i></span>
</a>
</td>
<td class="date text-center">{{ $item->offerId }}</td>
<td class="date text-center">{{ $item->promoName }}</td>
<td class="number text-center">{{ $item->promoPrice}}</td>
<td class="number text-center">{{ $item->isActive }}</td>
</tr>
#endforeach
</tbody>
</table>
<!--Start Modal Edit -->
<div class="modal fade text-left" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel160" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header bg-primary">
<h5 class="modal-title white" id="add">
Edit Promo
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('promo.edit') }}" method="POST">
#csrf
<div class="form-group">
<label for="">ID</label>
<input type="text" class="form-control" name="id" id="id" value="">
<span style="color:red">#error('id'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Offer ID</label>
<input type="text" class="form-control" name="offerId" id="offerId" value="">
<span style="color:red">#error('offerId'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Promo Name</label>
<input type="text" class="form-control" name="promoName" id="promoName" value="">
<span style="color:red">#error('promoName'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Promo Price</label>
<input type="number" class="form-control" name="promoPrice" id="promoPrice" value="">
<span style="color:red">#error('promoPrice'){{$message}} #enderror</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light-secondary" data-bs-dismiss="modal">
<i class="bx bx-x d-block d-sm-none"></i>
<span class="d-none d-sm-block">CANCEL</span>
</button>
<button type="submit" class="btn btn-primary ml-1">
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">SAVE</span>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- End Modal Edit-->
Then this is the web.php file, for the routing:
Route::get('promo.promo', [App\Http\Controllers\FormControllerPromo::class, 'viewRecord'])->middleware('auth')->name('promo.promo');
Route::post('promo.add', [App\Http\Controllers\FormControllerPromo::class, 'addPromo'])->name('promo.add');
Route::post('promo.delete/{id}', [App\Http\Controllers\FormControllerPromo::class, 'viewDelete'])->middleware('auth');
Route::get('promo.edit', [App\Http\Controllers\FormControllerPromo::class, 'viewRecord'])->middleware('auth')->name('promo.edit');
Route::get('promo.edit/{id}', [App\Http\Controllers\FormControllerPromo::class, 'viewDetail'])->middleware('auth');
Route::post('promo.edit', [App\Http\Controllers\FormControllerPromo::class, 'edit'])->name('promo.edit');
This is the master.blade.php file:
<!--Start Modal edit for Promo-->
<script type="text/javascript">
$('#edit').on('show.bs.modal', function (event){
var button = $(event.relatedTarget)
var mainid = button.data('mainid')
var id = button.data('myofferid')
var title = button.data('mytitle')
var price = button.data('myprice')
var modal = $(this)
modal.find('.modal-body #id').val(mainid);
modal.find('.modal-body #offerId').val(id);
modal.find('.modal-body #promoName').val(title);
modal.find('.modal-body #promoPrice').val(price);
})
</script>
<!--End Modal edit for Promo-->
I think this is the part where the code wont execute properly.
This is the FormControllerPromo.php file:
// view form
public function index()
{
return view('promo.promo');
}
// view record
public function viewRecord()
{
$data = DB::table('promo')->get();
return view('promo.promo',compact('data'));
}
// view detail
public function viewDetail($id)
{
$data = DB::table('promo')->where('id',$id)->get();
return view('promo.promo',compact('data'));
}
// edit promo
public function edit(Request $request){
$id = $request->input('id');
$offerId = $request->input('offerId');
$promoName = $request->input('promoName');
$promoPrice = $request->input('promoPrice');
DB::table('promo')
->where('id', $id) // find your user by their email
->limit(1) // optional - to ensure only one record is updated.
->update(array('offerId' => $offerId, 'promoName' => $promoName, 'promoPrice' => $promoPrice)); // update the record in the DB.
$data = DB::table('promo');
return view('promo.promo',compact('data'));
}
I've been trying to code this for almost a week now with no success, any help is highly appreciated. :)
the update seems right, should work. but when you pass the $data variable to your view, you should call ->get(), because otherwise you return a query builder instance, that later raises the Undefined property error when trying to access {{$item->offerId}}.
change second last line in your example
//from this:
$data = DB::table('promo');
//to this:
$data = DB::table('promo')->get();
//or to this if you want to show only one record:
$data = DB::table('promo')->where('id', $id)->get();

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'));
}

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

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();
}

how to handle dynamically created forms laravel 5.4

I want to know how to fetch name of checkboxes from dynamically created form. First I am displaying each records of data in a separate form then If records need to be deleted we will be able to delete. I am able to give different name as somename+id. But how do I know which name is going in the controller. As It is not clear that which name is going in the controller, I am not able to delete the record. I am doing it in laravel 5.4. Here is my code -
#if (isset($allcolors))
#foreach ($allcolors as $color)
<tr>
<form method="post" action="/delete">
{{csrf_field()}}
<input type="hidden" name="_method" value="DELETE">
<td>
<span class=""><input type="checkbox" name="deletecolor[{{$color->id}}]" value="{{$color->id}}"></span>
</td>
<td>
<div style="background:{{$color->web_color}}">a</div>
</td>
<td>{{$color->color_name}}</td>
<td>
<button type="submit" class="btn btn-danger">
Delete
</button>
</td>
</form>
</tr>
#endforeach
#endif
then on form submission I want to fetch which I am doing like this -
public function destroy(Request $request)
{
//
$id = $request->input('deletecolor');
$affected = DB::update("DELETE FROM vehicle_color where id = ?", [$id]);
//echo $affected==1?"Successfully Deleted":"Delete Fail";
}
I see you have $color->id. Why not delete them based on that?
#if (isset($allcolors))
#foreach ($allcolors as $color)
<tr>
<form method="post" action="/delete">
{{csrf_field()}}
<input type="hidden" name="_method" value="DELETE">
<td><span class=""><input type="checkbox" name="deletecolor[{{ $color->id }}]" value="{{$color->id}}"></span></td>
<td><div style="background:{{$color->web_color}}">a</div></td>
<td>{{$color->color_name}}</td>
<td><button type="submit" class="btn btn-danger" data-toggle="modal" data-target="#colorDelPopup">Delete</button></td>
</form>
</tr>
#endforeach
#endif
And in your controller:
public function destroy(Request $request)
{
$ids = $request->input('deletecolor');
// Instead of raw SQL, you can use the query builder to make your life a bit easier
$affected = DB::table('vehicle_color')->whereIn('id', $ids)->delete();
//echo $affected==1?"Successfully Deleted":"Delete Fail";
}
This should do the trick.

handling multiple array in view sent by controller function in laravel

How to send multiple arrays in different controller functions in Laravel 5 and how to handle them in view?
I am getting errors on variable:
variable not defined
which I am using to retrieve array.
public function index()
{
$users = user::all();
return view('employee')->with('users',$users);
}
this is my index, i am sending another array with different function like
public function goempedit($id)
{
$emp = Employee::where('id', $id)->first();
return view('employee')->with('emp', $emp);
}
So at the view I am using foreach loop to print the values but it is not working... $emp in foreach showing error as:
not defined variable
Please somebody help.
Just put a simple check like:
if(isset($emp)) {
//do foreach($emp ...
}
if(isset($users)) {
//do $users ($users...
}
Edit
//link to call model
//model
<div class="modal fade edit-items" style="z-index: 2000">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Edit Items</h4>
</div>
<div class="modal-body">
#if(isset($row))
<form action="{{action('ProductController#edit')}}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="col-sm-12">
<h1 style="text-align:center;">Edit Items</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Category</th>
<th>Item</th>
<th>Price</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<input type="hidden" name="item_id" value="{{ $row->item_id}}">
<td>{{ $row->item_id}}</td>
<td>{{ $row->cat_name}}</td>
<td><input class="form-control" name="item_name" value="{{$row->item_name}}" /></td>
<td><input class="form-control" name="item_price" value="{{$row->item_price}}" /></td>
<td><input class="btn btn-primary btn-block btn-flat" type="submit" value="Edit"></td>
</tr>
</tbody>
</table>
</div>
</form>
#endif
</div>
</div>
</div>
</div>
You're not passing the variable to the view that way; you're actually passing it to the session() if you use ->with().
This is what you need (pass the params as an array, and it has to be the 2nd parameter of the view():
return view('employee', ['emp' => $emp]);

Resources