How do I pass values from views to controller - laravel

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

Related

Laravel Livewire uploads file only after second submit / button press

I want to create an almost simple file upload via Laravel/Livewire, but once submitting the form with two inputs and one file input, the form fields focus and standstill. However, after pressing the submit button again, it uploads as anticipated with a success message. How can this be achieved with the first button submit?
Livewire component
namespace App\Http\Livewire\Files;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\File;
class FilesForm extends Component
{
use WithFileUploads;
public $file;
public $name;
public $doctype;
public $doctypes;
public $doctypeparent;
public $docs;
public function mount($id)
{
$this->doctypeparent = $id;
}
public function save()
{
$validatedData = $this->validate([
'doctype' => 'required',
'file' => 'required|image|mimes:jpg,jpeg,png,svg,gif|max:10240',
]);
$filename = $this->file->store('files','public');
$validatedData['content_type_id'] = $this->doctype;
$validatedData['name'] = $this->name;
$validatedData['file'] = $filename;
$validatedData['user_id'] = Auth::id();
$validatedData['slug'] = uniqid();
File::create($validatedData);
session()->flash('message', 'Datei erfolgreich gespeichert.');
$this->doctype="";
$this->name="";
$this->file="";
$this->render();
//return redirect()->to('/fileupload');
}
public function render()
{
$this->doctypes = DB::table('content_type')
->select('content_type.id', 'content_type.strTitleDe')
->where('content_type.fkintContentGroup', '=', $this->doctypeparent)
->orderBy('content_type.intPriority')
->get();
$this->docs = File::all();
//dd($this->docs);
return view('livewire.files.files-form');
}
}
Livewire blade
<div class="file-form">
<form wire:submit.prevent="save">
#if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
<div class="form-group">
<label for="name">Typ</label>
<select class="form-control" id="doctype" name="doctype" wire:model="doctype">
<option value="">- - -</option>
#foreach ($doctypes as $doctype)
<option value="{{ $doctype->id }}">{{ $doctype->strTitleDe }}</option>
#endforeach
</select>
#error('doctype') <span class="error">{{ $message }}</span> #enderror
</div>
<div class="form-group">
<label for="name">Bezeichnung</label>
<input type="text" class="form-control" max="255" id="name" placeholder="" wire:model="name">
#error('name') <span class="text-danger">{{ $message }}</span> #enderror
</div>
<div class="form-group">
<div class="custom-file">
<label for="file">Datei:</label>
<input type="file" class="form-control" id="file" wire:model="file">
#error('name') <span class="error">{{ $message }}</span> #enderror
</div>
</div>
<button type="submit" class="btn btn-primary">Speichern</button>
</form>
<p></p>
<h3>Dokumente</h3>
<table>
<thead>
<tr>
<td>Typ</td>
<td>Title</td>
</tr>
</thead>
<tbody>
#foreach($docs as $doc)
<tr>
<td>Typ</td>
<td>{{ $doc->name}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
Not sure if this helps but.....While it looks like this could work, I never do actual form submits when using livewire - all of the data is bound with wire:model. There's no need to use a form at all. I just use buttons with wire:click and call whatever function saves the file.
Doing it that way I've had zero problems with file uploads.

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;

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