Laravel Maatwebsite excel - laravel

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

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.

DOMPDF - Laravel - Email PDF with Attachment

I am getting this error what would be the reason for this
"Undefined variable: quotation"
QuotationController.php
public function update(Request $request, Quotation $quotation)
{
{
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->save();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
}
public function edit(Quotation $quotation)
{
return view('employees.quotations.edit', compact('quotation'));
//return view('employees.quotations.edit')->with('quotation');
}
......................................................................
routes look like this
Route::post('/quotation', 'Employee\QuotationController#store')->name('employee.quotation.store');
Route::get('/quotation', 'Employee\QuotationController#index')->name('employee.quotation.index');
Route::get('/quotation/create', 'Employee\QuotationController#create')->name('employee.quotation.create');
Route::put('/quotation/{quotation}', 'Employee\QuotationController#update')->name('employee.quotation.update');
Route::get('/quotation/{quotation}', 'Employee\QuotationController#show')->name('employee.quotation.show');
Route::delete('/quotation/{quotation}', 'Employee\QuotationController#destroy')->name('employee.quotation.destroy');
Route::get('/quotation/{quotation}/edit', 'Employee\QuotationController#edit')->name('employee.quotation.edit');
employees.quotations.edit.blade.php looks like this
#section('left-menu')
#endsection
#section('right-menu')
#endsection
#section('content')
<h1>Update a Quotation</h1>
<br><br>
<form action="{{ route('employee.quotation.update',$quotation->id) }}" method="post">
#method('PUT')
#csrf
<div class="form-group">
<label for="inputJobDescription">Description</label>
<textarea class="form-control" rows="2" id="inputQuoteDescription" name="description" placeholder="Description">{{$quotation->description}}
</textarea>
</div>
<div class="form-group row">
<label for="inputQty" class="col-2 col-form-label">Qty</label>
<div class="col-10">
<input type="text" class="form-control" id="inputQty" name="qty" value="{{$quotation->qty}}" oninput="quotation_calculate()" onchange="quotation_calculate()">
</div>
</div>
<div class="form-group row">
<label for="inputEachPrice" class="col-2 col-form-label">Each Price</label>
<div class="col-10">
<input type="text" class="form-control" id="inputEachPrice" name="each_price" value="{{$quotation->each_price}}" oninput="quotation_calculate()" onchange="quotation_calculate()">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
#endsection
#section('pagescript')
#stop
What am i missing here ? I am already passing $quotation to the edit view
You are obviously not passing the $quotation variable through your route. You are also using the $quotation as an object; that tells me you don't intend passing it through the route. Try the following code:
public function update(Request $request, $quotation_id)
{
$quotation = Quotation::findOrFail($quotation_id);
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->update();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message) use ($quotation){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
This should work.
Why are you using double brackets to declare a function ? Why not:
public function update(Request $request, Quotation $quotation)
{
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->save();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
I think you need to pass $quotation into the closure:
Mail::send(['text' => 'mail'], $info, function ($message) use ($quotation) {
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com', 'John Doe')->subject('Quotation');
$message->from('from#gmail.com', 'The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});

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

Laravel user input form to query database

been trying to create a laravel form with several fields that the user can enter text/number into a field and it takes the field with data and performs a database query. Now the form works with just one field but when i add more fields it only returns data for the final query, not for the other two.
perfumes controller
class perfumescontroller extends Controller
{
public function index()
{
$pstoreNum = request('pstoreNum');
$result = perfumes::where('StoreNumber','=',$pstoreNum)
->get();
return view('perfumes',compact('result'));
}
public function perfWeekSearch()
{
$weekNum = request('perfWeekNum');
$result = perfumes::where('WeekNumber','=',$weekNum)
->get();
return view('perfumes',compact('result'));
}
}
Route::get('/perfumes', 'perfumescontroller#index');
Route::get('/perfumes', 'perfumescontroller#perfWeekSearch');
Blade:
<form action="perfumes" method="get">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="perfWeekNum" placeholder="Type in Store Number">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
Do i need to use some sort of check if not null method? or is there an easier way??
Thanks
I think this would be work below is your perfumes controller
class perfumescontroller extends Controller
{
public function index()
{
$data = $request->all();
if(!empty($data['pstoreNum'])){
$pstoreNum = $data['pstoreNum'];
$result = DB::table('perfumes')->where('StoreNumber','=',$pstoreNum)
->get();
return view('perfumes',compact('result'));
} else if(!empty($data['perfWeekNum'])){
$weekNum = $data['perfWeekNum'];
$result = DB::table('perfumes')->where('WeekNumber','=',$weekNum)
->get();
return view('perfumes',compact('result'));
}
}
}
and you use any with route like below:
Route::any('/perfumes', 'perfumescontroller#index');

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