Laravel - Undefined variable: request in multiple submit button - laravel

In my Laravel-5.8 application, I have two submit buttons for different purposes:
Controller
public function store(StoreLeaveRequestRequest $request)
{
DB::beginTransaction();
try {
//check which submit was clicked on
if ($request->has('apply')) {
$leaverequest = new HrLeaveRequest;
$leaverequest->authorized_days = $request->authorized_days;
$leaverequest->available_days = $request->available_days;
$leaverequest->no_of_days = $days;
if($employeelinemanagerid == $employeehodid )
{
$leaverequest->line_manager_notified = 1;
$leaverequest->hod_notified = 1;
}else{
$leaverequest->line_manager_notified = 1;
}
$leaverequest->save();
$this->getLineManagerUserId();
} elseif($request->has('draft')) {
$leaverequest = new HrLeaveRequest;
$leaverequest->authorized_days = $request->authorized_days;
$leaverequest->available_days = $request->available_days;
$leaverequest->no_of_days = $days;
$leaverequest->save();
}
DB::commit();
Session::flash('success', 'Leave Request is created successfully');
return redirect()->route('service.leave_requests.index');
}
catch (Exception $exception)
{
dd($exception->getMessage());
DB::rollback();
Session::flash('error', 'Action failed!');
return redirect()->route('service.leave_requests.index');
}
}
view
<form action="{{route('service.leave_requests.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" name="apply" class="btn btn-primary">Submit</button>
<button type="submit" name="draft" class="btn btn-warning">Save as Draft</button>
</div>
</form>
I used name="apply" for
($request->has('apply'))
and name="draft" for
($request->has('draft'))
When I click on any of the submit buttons, I got this error:
"Undefined variable: request"
I tried to check, I don't know where the error is coming from
Where did I get it wrong?
Kindly assist.
Thanks

Related

Eloquent update doesn't work in Laravel 6

I'm trying to update a field after submitting in the following form:
<form action="{{ route("comments.update") }}" method="post">
#csrf
<input type="hidden" name="commentIDToEdit" id="commentID">
<div class="md-form mb-5">
<i class="fas fa-comment"></i>
<label for="toEditComment"></label>
<textarea name="toEditCommentary" id="toEditComment" cols="3" rows="5" style="resize: none"
class="form-control"></textarea>
</div>
<div class="modal-footer d-flex justify-content-center">
<button type="submit" class="btn btn-default">Modificar</button>
</div>
</form>
I have the CommentsController, where I process the data from the form. Here is the code:
public function updateComment()
{
request()->validate([
"toEditCommentary" => "min:10|max:500"
]);
if (Session::has("username") && getWarningCount(User::whereUsername(session("username"))->value("email")) > 0) {
Caveat::where("commentID", request("commentIDtoEdit"))
->update(["updatedComment" => request("toEditCommentary")]);
} else {
die("No se cumple la condición");
}
if (Comment::where("commentID", request("commentIDToEdit"))->exists()) {
Comment::where("commentID", request("commentIDToEdit"))
->update(["commentary" => request("toEditCommentary")]);
}
return back();
}
Curiosly, the comment is updated in his table, but not the warning. I was thinking in the fillable property in the model, but I don't have it, instead this, I have the following code:
protected $guarded = [];
const UPDATED_AT = null;
const CREATED_AT = null;
Your hidden input is named commentIDToEdit, but in the Controller you fetch the Caveat using request("commentIDtoEdit") (different case).
What you wrote:
Caveat::where("commentID", request("commentIDtoEdit"))
What you should have done: (note the different casing)
Caveat::where("commentID", request("commentIDToEdit"))
This is because in the view, the input name is commentIDToEdit, not commentIDtoEdit.

I want to update image using laravel

I am trying to update the image into database but unfortunately, the image is not updating into the database how to fix it. please help me thanks.
Controller
public function updateslider(Request $request, $id)
{
$this->validate($request, [
'select_image' => 'required'
]);
$image = $request->file('select_image');
$extension = $image->getClientOriginalExtension();
Storage::disk('cms')->put(
$image->getFilename() . '.' . $extension,
File::get($image)
);
$content = new Sliders;
if ($request->file('select_image')) {
$content->slider_image = $image->getFilename() . '.' . $extension;;
$updaterecord = sliders::where(['id' => $content->id])->update(['slider_image' =>
$content]);
return back()->with('success', 'Image Updated Successfully')->with('path', $updaterecord);
}
}
HTML view
<form method="post" action="
{{route('update.action',$myslider->id)}}"
enctype="multipart/form-data" >
#csrf
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="header-title">Image Upload</h4>
<input type="file" name="select_image" value="
{{config('e_soft.file_url').$myslider->slider_image}}"
class="dropify" data-height="300" />
</div> <!-- end card-body-->
</div> <!-- end card-->
<div class="page-title-right">
<button type="submit" id="update" class="btn btn-danger
waves-effect waves-light col-lg-1">Update</button>
</div>
</div>
<!-- end row -->
</form>
Ok so I think your problem is that you want to set default value for <input type="file"> which is not possible. for security reasons you can't set default value for <input type="file"> so in your case you can check if there is a new image file you put the new one otherwise you just reassign previous slider image here is an example:
$slider = Sliders::findOrFail($id);
if (! empty($request->file('select_image'))) {
$content->slider_image = $image->getFilename().'.'.$extension;;
} else {
$content->slider_image = $slider->slider_image;
}
So as you can see first we check if there is a new file if so we assign new one otherwise we use the old one.

Laravel Maatwebsite excel

I need your help. I don't know how to import the excel file. I mean I don't understand where to put this users.xlsx and how to get its directory
public function import()
{
Excel::import(new UsersImport, 'users.xlsx');
return redirect('/')->with('success', 'All good!');
}
its simple on mattwebsite you need a controller like below :
public function importExcel(Request $request)
{
if ($request->hasFile('import_file')) {
Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
foreach ($reader->toArray() as $key => $row) {
// note that these fields are completely different for you as your database fields and excel fields so replace them with your own database fields
$data['title'] = $row['title'];
$data['description'] = $row['description'];
$data['fax'] = $row['fax'];
$data['adrress1'] = $row['adrress1'];
$data['telephone1'] = $row['telephone1'];
$data['client_type'] = $row['client_type'];
if (!empty($data)) {
DB::table('clients')->insert($data);
}
}
});
}
Session::put('success on import');
return back();
}
and a view like this :
<form
action="{{ URL::to('admin/client/importExcel') }}" class="form-horizontal" method="post"
enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label class="control-label col-lg-2">excel import</label>
<div class="col-lg-10">
<div class="uploader"><input type="file" name="import_file" class="file-styled"><span class="action btn btn-default legitRipple" style="user-select: none;">choose file</span></div>
</div>
</div>
<button class="btn btn-primary">submit</button>
</form>
and finally a route like below :
Route::post('admin/client/importExcel', 'ClientController#importExcel');

Undefined index error in importing excel

I'm trying to import my excel to my database but the problem is that theres an error saying "Undefined index: title" referring to the title in the controller.
So this is my code for my controller
public function importExcel()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader){
})->get();
if(!empty($insert)){
foreach ($data as $key => $value) {
$insert[] = ['title' => $value->title, 'description' => $value->description];
}
if(!empty($insert)){
DB::table('items')->insert($insert);
print_r('Insert Record succesfully');
}
}
}
return back();
}
And this is for my view blade:
#extends('layouts.app')
#section('content')
<div class="container">
<button class="btn btn-success">Download Excel xls</button>
<button class="btn btn-success">Download Excel xlsx</button>
<button class="btn btn-success">Download CSV</button>
<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="import_file" />
<button class="btn btn-primary">Import File</button>
</form>
</div>
#endsection
Here is the image of the excel i want to upload to my database. It's an xlsx that i want to upload.
See picture for reference
But the error says like this Error message screenshot
You can insert the sheet data directly by calling the toArray method of the Maatwebsite\Excel\Readers\LaravelExcelReader.
$loadedFile = Excel::load($path);
$inserts = $loadedFile->toArray();
if (!empty($insert)) {
DB::table('items')->insert($insert);
print_r('Inserted Record successfully');
}
However, going by your implementation it should be noted that when a callback is specified for the reader, $reader->all() or $reader->get() returns a Maatwebsite\Excel\Collections\RowCollection or Maatwebsite\Excel\Collections\SheetCollection depending on the amount of sheets the file has.
For your sample where there is a single sheet, you can rightly expect a Maatwebsite\Excel\Collections\RowCollection. Therefore you have
$inserts = [];
Excel::load($path, function($reader) use (&$inserts) {
foreach ($reader->get() as $row) {
$inserts[] = ['title' => $row->title, 'description' => $row->description];
}
});
if (!empty($inserts)) {
DB::table('items')->insert($inserts);
print_r('Inserted Record successfully');
}

search with ajax laravel

I need my project to have a search form, I tried with this code, but when I execute console it says:
POST http://localhost:8000/buscar 500 (Internal Server Error)
then here is my view
<div id="qnimate" class="off">
<div id="search" class="open">
<button data-widget="remove" id="removeClass" class="closeSearch" type="button">×</button>
<input type="text" placeholder="Buscar Noticias - Articulos - Reviews" id="buscar" onkeydown="keydownFunction()" onkeyup="keyupFunction()">
<button class="btn btn-lg btn-site" type="submit"><span class="glyphicon glyphicon-search"></span> Buscar</button>
<div id="resultadoBusqueda" class="col-md-12"></div>
</div>
</div>
here is my controller
public function buscar()
{
$keywords = Input::get('keywords');
$reviews = Reviews::where('estado','1')->take();
$buscarReviews = new \Illuminate\Database\Eloquent\Collection();
foreach ($reviews as $review) {
if(Str::contains(Str::lover($review->nombre), Str::lover($keywords)))
$buscarReviews->add($review);
}
return view::make('busqueda')->with('buscarReviews', $buscarReviews);
}
here is the view which shows the information
#foreach($buscarReviews as $review)
<div id="reviews" class="col-md-12">
<div class="col-md-4">
<img src="Imagenes/{{$review->logo}}" width="50">
</div>
<div class="col-md-8">
<h2>{{$review->nombre}}</h2>
<div>{!! str_limit($review->descripcion, $limit = 150, $end = '...') !!}</div>
</div>
</div>
#endforeach
here is my js
var timer;
function keydownFunction(){
timer = setTimeout(function(){
var keywords = $('#buscar').val();
if(keywords.length > 0){
$.post('/buscar', {keywords: keywords}, function(markup){
$('#resultadoBusqueda').html(markup);
});
}
}, 500);
}
function keyupFunction(){
clearTimeout(timer);
}
I don't know what is the reason that it doesn't print the information required.
you are sending post request from ajax but in your controller you are trying to get that value using get, try this code
public function buscar(Request $request)
{
$keywords = $request->keywords;
$reviews = Reviews::where('estado','1')->take();
$buscarReviews = new \Illuminate\Database\Eloquent\Collection();
foreach ($reviews as $review) {
if(Str::contains(Str::lover($review->nombre), Str::lover($keywords)))
$buscarReviews->add($review);
}
return view::make('busqueda')->with('buscarReviews', $buscarReviews);
}
also remember to change in route like this.
Route::post('buscar', 'yourController#buscar');

Resources