Laravel - Form Action to Controller Function - php

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?

Related

How to store an array as single row for each value in my database

the whole idea is that when a user click on checkbox and save, the form should be submitted with an array containing the checked values, and save them in the database as single row for each value. i don't know if this is possible but i'm sure you guys have a solution or can help me?
and here's my form:
<div class="">
<form style="width: 70%" method="POST" action="{{ URL('/admin/projects/services/save') }}"
enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" id="id" value="{{ #$id }}">
<input type="hidden" name="projectid" id="projectid" value="{{ #$projectid }}">
<div class="row topSpacer">
<div class="col-3">
<p class="bold">Selected Services: <span class="red">*</span></p>
</div>
<div class="col-9">
<input type="text" id="selectedServices" name="selectedServices" value="" readonly>
</div>
</div>
<div class="row topSpacer">
<div class="col-3">
<p class="bold">Select a service: <span class="red">*</span></p>
</div>
<div class="col-9">
#foreach ($services as $service)
<input type="checkbox" name="service" value="<?php echo stripslashes($service->id); ?>">
<label for="service"><?php echo stripslashes($service->name); ?></label>
<br>
<hr>
#endforeach
#error('service')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
</div>
<div class="row topSpacerHuge">
<div class="col-12 textRight">
<button type="button"
onclick="window.location='{{ url('admin/projects/services/index/'.$projectid) }}'"
class="goBackBtn">Cancel</button>
<input class="saveBtn" id="saveBtn" type="submit" value="Save">
</div>
</div>
</form>
</div>
and my script to get checkboxes value:
<script>
$(function() {
$("input:checkbox[name='service']").click(function() {
$value = [];
$.each($("input:checkbox[name='service']:checked"), function() {
$value.push($(this).val());
$array = $value.join();
});
// console.log(value.join(", "));
$("#selectedServices").val($array);
})
});
</script>
for implementing checked values I recommend to use the select tag
and you can give A name attribute with [] and it will collect all of your data
for example , look at my project's file which I'm trying to collect name of some users :
<select name="users[]" id="example-with-maxHeight" class="multiselect-group" multiple >
#foreach($users as $user)
<option #if($user->average < $averageParticipate )class="alert-danger" #endif value="{{$user->id}}">{{$user->name}} - {{$user->average}}</option>
#endforeach
</select>
have attention to users[] in name attribute
now in your request you can access all of your checked items .
if we look at your code ,can be some thing like this :
<label for="service"><?php echo stripslashes($service->name); ?></label>
<select name="services[]" id="" class="multiselect-group" multiple >
#foreach($users as $user)
<option value = "{{$sevice->id}}"> <?php echo stripslashes($service->name); ?></option>
#endforeach
</select>
now in your controllers you can access them :
request->get('services');
it will give you back an array of selected items .
Notice that id attribute helps me to interact with my java script code
you can rename it to yourselves .

Problem passing data from the controller to the view Laravel 8

I'm getting an error when I try to pass data from the controller to the view and I spent a lot of time trying to solve it. The error is "Undefined Variable $instEntNacs". There is other form this view, because depending on the rol, it will show the first or the second one.
Here's the controller "ConvenioController":
public function create()
{
$instEntNacs = DB::table('inst_ent_nacs')->select('id', 'nombre')->get();
return view('convenios.create', ['instEntNacs' => $instEntNacs]);
}
And the view:
#if (auth()->user()->rol_id == "2")
<form method="POST" class="form-conv-nac border border-2 rounded-3 shadow-lg" action="{{ route('convenios.store_nac') }}" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="offset-1 col-10 mt-4">
<select class="form-control border border-dark" id="con_instEntNac" name="con_instEntNac">
<option selected value="">-- Institución o Entidad --</option>
#foreach ($instEntNacs as $item)
<option value="{{ $item->id }}"> {{ $item->nombre }}</option>
#endforeach
</select>
</div>
</div>
<div class="row mt-4 mb-5">
<div class="offset-1 col-2">
Regresar
</div>
<div class="offset-2 col-3">
<button type="submit" class="w-100 btn_2 btn-danger rounded-pill border border-dark">Cancelar</button>
</div>
<div class="col-3">
<button type="submit" class="w-100 btn_1 btn-primary rounded-pill border border-dark">Registrar</button>
</div>
</div>
</form>
#endif
Have you tried this?
$data['instEntNacs'] = DB::table('inst_ent_nacs')->select('id', 'nombre')->get();
return view('convenios.create')->with($data);
You can try compact('instEntNacs') with return view('convenios.create').
return view('convenios.create', compact('istEntNacs'));

Laravel form validation doesn't work when in my controller declaring more databases

I declare a variable containing the database so that the blade can select, but when doing so, the validation does not work. Please help me. Thank you very much.
this is the variable I call in the database to use select in the blade.
public function new_department(){
//return view('admin.new-department');
$manage_faculties=DB::table('faculties')->orderBy('id','asc')->get();
$all_manage_faculties=view('admin.new-department')->with('manage_faculties', $manage_faculties);
return view('layouts.master')->with('admin.new-department', $all_manage_faculties);
}
Here is the validation I use in the insert information and database.
public function save_new_department(Request $request){
$data = [];
$data['department_name'] = $request->input('department_name');
$data['description'] = $request->input('description');
$data['faculty_id'] = $request->input('faculty_name');
if($request->isMethod('post')){
$validator = Validator::make($request->all(), [
'department_name' => 'required|min:3|max:100|unique:departments',
'description' => 'required|max:500',
]);
if ($validator->fails()) {
return back()->with('toast_error', $validator->messages()->all()[0])->withInput();
}
DB::table('departments')->insert($data);
return redirect('/admin/departments/new')->withSuccess('Post Created Successfully!');
}
}
display it in the blade
After entering data whether it is true or false, it is not possible to report an error on the screen.After entering data whether it is true or false, it is not possible to report an error on the screen.
<form class="mt-3"method="post" action="{{ url('admin/department/new-department') }}">
{{csrf_field()}}
<div class="modal-content">
<div class="modal-header bg-primary">
<h5 class="modal-title">Create a Department</h5>
</div>
<!--end of modal head-->
<div class="modal-body">
<div class="form-group row align-items-center" {{ $errors->get('name') ? 'has-error' : '' }}>
<label class="col-2">Department</label>
<input class="form-control col" type="text" placeholder="Department name" name="department_name" required/>
#foreach($errors->get('name') as $error)
<span class="help-block">{{ $error }}</span>
#endforeach
</div>
<div class="form-group row align-items-center">
<label class="col-2">Faculty</label>
<select name="faculty_name" class="form-control col" required>
<option value="" selected>Select a Faculty</option>
#foreach($manage_faculties as $key => $cate_pro)
<option value="{{$cate_pro->id}}">{{$cate_pro->faculty_name}}</option>
#endforeach
</select>
</div>
<div class="form-group row">
<label class="col-2">Description</label>
<textarea class="form-control col" rows="10" placeholder="Write something here..." name="description" required ></textarea>
</div>
</div>
<!--end of modal body-->
<div class="modal-footer">
<button role="button" class="btn btn-primary" type="submit">
Post
</button>
</div>
</div>
</form>
You can look here for displaying errors in Laravel.
Why did you put :
{{ $errors->get('name') ? 'has-error' : '' }}
inside a "div" like a attribute ?

Cannot get request object

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.

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

Categories