Cannot get request object - php

Grettings.
I'm trying to call an index view from itself, to look for a person and displaying results to the left.
But when I call the view and send data It always get null, could you please give me a clue. I've even called the store function and request is always null.
It should be a modal window to get the request object? What should I do If I wanted to show the windows as I'm doing it?
My routes
Route::get('registroaccesos/destinationSearchGet/', 'RegistroAccesosController#destinationSearchGet')->name('registroaccesos.destinationSearchGet');
Route::post('registroaccesos/destinationSearchPost/', 'RegistroAccesosController#destinationSearchPost')->name('registroaccesos.destinationSearchPost');
The controller
public function destinationSearchGet(){
$headData = array('pageTitle' => 'Admin Home - View all destinations');
return view('registroaccesos.index', $headData);
}
public function destinationSearchPost(Request $request){
$headData = array('pageTitle' => 'Admin Home - Search results');
$formData = $request->input('strPatron');
dd($formData);
// $data = ParentRegionList::destinationSearch($formData);
return view('registroaccesos.index', $headData);//->with(compact('data'))
}
The view
Part of the code of the view
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Acciones</span>
<a class="d-flex align-items-center text-muted" href="#">
<span data-feather="plus-circle"></span>
</a>
</h6>
<div class="form-group">
<label for="strSearch" class="col-form-label">Patrón de búsqueda</label>
<select name="strSearch" class="form-control">
<option value="1" selected> Código del usuario</option>
<option value="2" > Nombre del usuario</option>
</select>
</div>
<div class="form-group">
<input placeholder="Patrón de búsqueda"
id="strPatron"
required
name="strPatron"
spellcheck="false"
class="form-control"
value="Valor"
/>
</div>
<button class="btn btn-sm btn-outline-secondary"
onclick="
event.preventDefault();
document.getElementById('search-form').submit();
"
>Buscar</button>
<form id="search-form" action="{{ route('registroaccesos.store','el resultado' ) }}" method="POST" style="display: none;">
<!-- <input type="hidden" name="_method" value="delete">-->
{{ csrf_field() }}
</form>
The result

Well your <input> with name="strPatron" is not in your <form> so it will not get submitted when you submit the form. You need to have all the input elements inside the form or they won't get sent with the POST request.
The way you've got it right now only the CSRF field in your form is getting submitted. You can check this by doing a dd($request->all()) in your controller.

Related

How to validate at least one checkbox is checked in a loop in Laravel?

I'm trying to validate my checkbox from a loop, where at least one is checked and displays an error/alert or disable the submit button instead if there is no checkbox checked. I tried putting a required method inside my checkbox, but the checkbox is in a loop that's why it requires all to be checked. That's why I tried the script code below which I found on the internet but that doesn't seem to work for me.
Below is my code in blade form
<form id="contact" action="{{url('/reservation')}}" method="post" enctype="multipart/form-data">
#csrf
<div class="row col-12">
#foreach($data as $data)
<div class="row sm-6 ml-4 mb-1" class="no-gutters" style="height:25px; width: auto;">
<p class='text-dark mr-2'><input type="checkbox" name="prod_name[]" value="{{$data->title}}" class="products product{{$data}}" onClick="checkTest()"/> {{$data->title}}</p>
<p class='text-dark'>Qty:</p><input style="width:80px; height:25px;" type="number" name="prod_qty[{{$data->title}}]" min="1" value="1" class="form-control ml-2">
<input type="hidden" name="product_fee[{{$data->title}}]" value="{{$data->price}}">
<input type="hidden" name="prod_id[{{$data->title}}]" value="{{$data->id}}">
</div>
#endforeach
</div>
<div class=" col-lg-12 mt-5">
<fieldset>
<button name="submit" type="submit" id="form-submit" class="main-button-icon">Make A Reservation</button>
</fieldset>
</div>
</div>
</form>
<script>
var minimumonechecked;
var checkboxes = $('.products').lenght;
function checkTest(xyz){
minimumonechecked = false;
for(i=0;i<checkboxes;i++){
if($('product' + i).is(':checked')){
minimumonechecked = true;
}
}
console.log(minimumonechecked)
};
</script>
This is also the code in my controller, other data such as names are also part of the form but I cut it out by focusing on the checkbox
public function reservation(Request $request)
{
if(Auth::id()){
$user_id=Auth::id();
$products = '';
$reserved_qty=0;
$product_fee=0;
$prod_id=0;
$checked_array = $request->input('prod_name', []);
$quantities = $request->input('prod_qty', []);
$fees = $request->input('product_fee', []);
$productid = $request->input('prod_id', []);
foreach($checked_array as $value){
$data = new reservation;
$data->user_id=$user_id;
$data->name=$request->name;
$data->email=$request->email;
$data->phone=$request->phone;
$data->address=$request->address;
$data->date=$request->date;
$data->time=$request->time;
$data->status="pending";
$data->productz=$request->products="{$value}";
$data->reserved_qty=$request->$reserved_qty="{$quantities[$value]}";
$data->product_fee=$request->$product_fee=$fees[$value]*$quantities[$value];
$data->prod_id=$request->$prod_id=$productid[$value];
$data->save();
}
return redirect()->back();
}else{
return redirect('/login');
}
There are a many ways to achieve your desired result, how I would approach it is as follows (note this is not exhaustive, it's a functional example).
On the client, use JavaScript to select all your product checkboxes, iterate over any found and attach event handlers to each of them which listen for the changed event (i.e. checked and unchecked). When the state of a checkbox is checked, add it to a Set so that we can track how many are selected. Based on the number of checked checkboxes, enable/disable form submission.
That theory out of the way, some code:
HTML:
<script src="https://cdn.tailwindcss.com"></script>
<div class="flex flex-col place-content-center items-center h-screen space-y-4">
<div class="flex align-items-center space-x-2">
<h1 class="underline font-bold decoration-orange-500 decoration-2">
<a href="https://stackoverflow.com/questions/73834200/how-to-validate-at-least-one-checkbox-is-checked-in-a-loop-in-laravel">
How to validate at least one checkbox is checked in a loop in Laravel?
</a>
</h1>
</div>
<div class="flex align-items-center space-x-2">
<input type="checkbox" class="products" name="products[]" id="product-a" />
<label for="product-a" class="text-sm">Product A</label>
</div>
<div class="flex align-items-center space-x-2">
<input type="checkbox" class="products" name="products[]" id="product-b" />
<label for="product-b" class="text-sm">Product B</label>
</div>
<div class="flex align-items-center space-x-2">
<input type="checkbox" class="products" name="products[]" id="product-c" />
<label for="product-c" class="text-sm">Product C</label>
</div>
<div class="flex align-items-center space-x-2">
<button class="px-4 py-2 rounded bg-orange-600 hover:bg-orange-700 text-white text-sm" id="form-submit">Submit</button>
</div>
</div>
JavaScript:
window.addEventListener('DOMContentLoaded', function () {
// get all the product checkbox elements
var productCheckboxes = document.querySelectorAll('.products');
// holder for the checked products
var checkedProducts = new Set();
// pointer to the form submit button
var formSubmitButton = document.querySelector('#form-submit');
// attach change event handlers to each of the checkboxes
productCheckboxes.forEach((checkbox) => {
checkbox.addEventListener('change', function (e) {
e.target.checked
? checkedProducts.add(e.target.id)
: checkedProducts.delete(e.target.id);
});
});
//
formSubmitButton.addEventListener('click', function (e) {
handleClientSideValidation();
});
// do some client side validation (do not rely on this alone!)
function handleClientSideValidation() {
if (checkedProducts.size == 0) {
alert('Ugh-oh, something is foobar Captain. You need to select at least 1 product.');
return;
}
alert('Validating ...');
}
})
Example CodePen
Now lets apply the above to a Laravel example using #foreach and Eloquent models. I am going to assume you already have a Product model, migration and some data seeded.
Form HTML:
<form action="{{ route('reservation') }}" method="POST" id="products-form">
<div class="flex flex-col place-content-center items-center h-screen space-y-4">
#csrf
<div class="flex align-items-center space-x-2">
<h1 class="underline font-bold decoration-orange-500 decoration-2">
<a href="https://stackoverflow.com/questions/73834200/how-to-validate-at-least-one-checkbox-is-checked-in-a-loop-in-laravel">
How to validate at least one checkbox is checked in a loop in Laravel?
</a>
</h1>
</div>
#if ($errors->any())
<div class="px-4 py-2 bg-red-500 text-white text-sm rounded-sm">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#foreach($products as $product)
<div class="flex align-items-center space-x-2">
<input type="checkbox" class="products" name="products[]" id="product-{{ $product->id }}" value="{{ $product->id }}" />
<label for="product-{{ $product->id }}" class="text-sm">{{ $product->title }}</label>
</div>
#endforeach
<div class="flex align-items-center space-x-2">
<button type="submit" class="px-4 py-2 rounded bg-orange-600 hover:bg-orange-700 text-white text-sm" id="form-submit">Submit</button>
</div>
</div>
</form>
As we all know you shouldn't rely soley upon client side validation, so you'll want to do some server side validation too. Once you've validated your request data, you can do whatever you want with it (I just get the products from the database in this example). I have put the code directly in a Route within web.php as I am lazy, you'd obviously use it in your ProductController function.
routes/web.php:
Route::post('/', function (Request $request) {
// perform some validation
// $validate will contain all the data that passed validation
$validated = $request->validate([
// products must be present in the request AND an array
'products' => ['required', 'array'],
// each of the products in the request, must have an ID present in the database
'products.*' => ['exists:products,id']
]);
// if we get here, validation was successfull
// do whatever you want with the $validated data
// I am just getting the Products as an example
$products = \App\Models\Product::whereIn('id', $validated['products'])->get();
// dump the Products
dd($products->all());
})->name('reservation');
Example PHP Sandbox
Quite a lot to taken in but hopefully that makes sense.
When you tick on checkbox, you need to count all checkboxes that have been checked before.
If at least checkbox is checked , you'll set disabled property on submit button is true and vice verse
<script>
$('.products').on('change', function() {
$('#form-submit').prop('disabled', $('.products:checked').length > 0);
});
</script>

Submitting data in a Livewire child view using its <form> in the parent view

I have a parent view edit.blade.php which has a form. The form has a #livewire() for edit-step.blade.php, the child component.
edit-step.blade.php has a foreach loop that renders the input fields. At one point, foreach will loop three input fields. The submit button is in the parent view edit.blade.php. On submitting, data from the last input field is the only one being submitted. How do I make data from all the input fields be submitted ?
edit.blade.php file:
<form method="post" action="{{route('todo.update', $todo->id)}}" class="py-5">
#csrf
#method('patch')
<div class="py-1"><input type="text" name="title" value="{{$todo->title}}" class="py-2 px-2 border rounded" placeholder="Title" /></div>
<div class="py-1">
<textarea name="description" class="p-2 rounded border" placeholder="Description">{{$todo->description}}</textarea>
</div>
<div class="py-2">
#livewire('edit-step', ['steps' => $todo->steps])
</div>
<div class="py-1"><input type="submit" value="Update" class="p-2 border rounded" /></div>
</form>
edit-step.blade.php file:
#foreach($steps as $step)
<div class="flex justify-center py-2" wire:key="{{$loop->index}}" >
<input type="text" name="step_" class="py-1 px-2 border rounded" placeholder="{{ 'Describe Step '.($loop->index + 1) }}" #if ( is_object($step) ) value="{{ $step->name }}" #endif />
<span class="fas fa-times text-red-400 p-2" wire:click="remove({{$loop->index}})"/>
</div>
#endforeach
Here is an example from my recent project. I have managed this with a single livewire component.
In Livewire Component;
public $entries = [];
public $date;
public function mount()
{
$this->date = now()->format('Y-m-d');
$this->entries=[
[
'name'=>'',
'amount'=>'',
],
[
'name'=>'',
'amount'=>'',
]
}
Now, in edit.blade.php ;
<input type="date" wire:model="date">
#foreach($entries as $key=>$entry)
<div wire:key="{{'entry'.$key}}">
<div>
<input type="text" wire:model="entries.{{$key}}.name">
</div>
<div>
<input type="number" wire:model="entries.{{$key}}.amount">
</div>
</div>
#endforeach
Now, again in livewire component for saving;
public function save()
{
foreach($this->entries as $entry){
Transaction::create([
'name'=>$entry['name'],
'amount'=>$entry['amount']
)];
}
//Notify User
}
However, if for any reason you need two livewire component to manage a same form, you can emit from a component and listen in another component.
For example in emitting component;
public function save(){
$this->emit('entryMade', $amount);
}
Now in listening component;
protected $listeners = ['entryMade'];
public function entryMade($amount)
{
// Do anything with $amount
}

updating the data in pivot table laravel 5

i have a many to many realtionship and a pivot table now i want to update the pivot table data with a form that users sends. here for example is assign a client to a sellman . here is my code :
in route :
Route::get('admin/client/assign','ClientController#assignsellman');
controller :
public function assignsellman(Request $request){
$user = User::all();
$client_list = Client::all();
$client = Client::with('sellmanlist')->firstOrFail();
$sellman = $request->input('sellman');
$client->sellmanlist()->attach($sellman);
return view('admin.client.assign',compact('client_list','user'));
}
and finally here is the form of view file that i want to get 2 variables one the id of the client and the secound the id of sell man
<form action="/admin/client/" method="post">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<label for="client">مشتری</label>
<select class="select-search select2-hidden-accessible" tabindex="-1" aria-hidden="true"
name="client">
#foreach($client_list as $client_lists)
<option value="">{{$client_lists->title}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-4 text-center">
<i class="icon-arrow-left7 mr-3 icon-3x" style="font-size: 130px"></i>
<h4>ارجاع به</h4>
</div>
<div class="col-xs-4">
<div class="form-group">
<div class="form-group">
<label for="sellman">کارشناس فروش</label>
<select class="select-search select2-hidden-accessible" tabindex="-1"
aria-hidden="true" name="sellman">
#foreach($user as $users)
<option value="1">{{$users->name}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<button type="submit" class="btn btn-primary">تایید</button>
</form>
with this code i get this error
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
thanks for help
Edit your route
Route::post('admin/client/','ClientController#assignsellman');
That is because the route you've created is HTTP GET, and in your form you're using HTTP Post.
<form action="/admin/client/" method="post">
Try switching to a GET method and it should work
<form action="/admin/client/" method="get">
or switch your route to
Route::post('admin/client/assign','ClientController#assignsellman');
Please take a look at the different HTTP Verbs and apply them to your needs.
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

Laravel - Form Action to Controller Function

I'm trying to create a situation where a user can load a page, select a timesheet number, and then have the system delete all records associated with that timesheet number. This function loads the form page:
public function deletetimesheetLoad()
{
$timesheets = collect(DB::select("SELECT dbo.TIME.Source AS Source
FROM dbo.TIME
GROUP BY dbo.TIME.Source
ORDER BY dbo.TIME.Source ASC"));
return view('utilities/deletetimesheet',['timesheets' => $timesheets]);
}
This is the actual blade template:
<form method="post"
action="{{url('/time/deletetimesheet/process')}}"
enctype="multipart/form-data"
<div class="form-group">
<label class="col-md-12 control-label" for="TIMESHEETNUMBER">Timesheet Number</label>
<div class="col-md-12">
<select required id="TIMESHEETNUMBER" name="TIMESHEETNUMBER" class="form-control select2_field">
<option value=""></option>
#foreach ($timesheets as $row)
<option value="{{ $row->Source }}">{{ $row->Source }}</option>
#endforeach
</select>
</div>
</div>
<div id="saveActions" class="form-group">
<input type="hidden" name="save_action" value="Submit">
<div class="btn-group">
<button type="submit" class="btn btn-success">
<span class="fa fa-save"></span>
<span data-value="Submit">Submit</span>
</button>
</div>
<span class="fa fa-ban"></span> Cancel
</div>
This is the function that the form action is pointing to:
public function deletetimesheetProcess(TimesheetRequest $request)
{
DB::table('TIME')->where('Source', $request->get('TIMESHEETNUMBER'))->delete();
\Alert::success(trans('yay'))->flash();
return view('details/customershow',[]);
}
Here are the defined routes for the two functions:
Route::get('/time/deletetimesheet', 'Admin\TimeCrudController#deletetimesheetLoad');
Route::post('/time/deletetimesheet/process', 'Admin\TimeCrudController#deletetimesheetProcess');
Currently the blade template loads correctly, and does not throw an error on submit - just reloads the current page. What am I doing wrong?

Laravel resource store method is being redirected to destroy method

I have a resource route
Route::resource('climb-excluded','CexcludedController',['only'=>['store','update','destroy']]);
And my code in view to save data
<div class="col-lg-4">
<form class="form" method="POST" action="{{ route('climb-excluded.store') }}">
{{ csrf_field() }}
<div class="card">
<div class="card-head style-primary">
<header>Add item</header>
</div>
<div class="card-body floating-label">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name">
<label for="name">Name</label>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<button type="submit"
class="btn btn-block btn-success ink-reaction">
Add
</button>
</div>
</div>
</div>
</div>
A button to destroy data:
{!! Form::open( array('route'=>array('climb-excluded.destroy', $excluded->id),
'method'=>'DELETE')) !!}
<button type="submit"
class="btn ink-reaction btn-floating-action btn-sm btn-danger "
rel="tooltip"
title="Delete">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button
{!! Form::close() !!}
Store method form controller:
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|max:255'
]);
$excluded = new Cexcluded;
$excluded -> name = $request->name;
$excluded->save();
//redirect to
Session::flash('success','New item sucessfully added !');
return back()->withInput(['tabs'=>'second4']);
}
Destroy method form controller:
public function destroy($id)
{
$trekExcluded = Cexcluded::find($id);
$trekExcluded->tours()->detach();
$trekExcluded ->delete();
Session::flash('success','Item sucessfully deleted !');
return back()->withInput(['tabs'=>'second4']);
}
The trouble/bug that I'm facing is I can insert first row into table successfully. But when I go for the second one, the store method is somehow redirected to destroy method and deletes the first inserted row also. While I've clearly declared store method in action attribute of the form.
FYI: Both routes exists in same view/page. Destroy method in col-md-8with foreach loop while store method in col-md-4
Its quite obvious, that your form don't have a unique name or id, so that's why the second method is redirected to destroy method. Do something like this:
cex-store-1
cex-destroy-1

Categories