Export to excel a table from laravel - php

I'm so confused why i can't export this to excel. Please help me. Theres an error where it can't read "all".
Here's my code in my UsersController
public function userExport()
{
Excel::create('data_function',function($excel){
$excel->sheet('mysheet', function($sheet){
$sheet->loadView('user.list');
});
})->download('xls');
}
Then here is it in my user/list.blade
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">
Employees
<small>#lang('app.list_of_registered_users') - {{ $all }}</small>
</h1>
</div>
</div>
#include('partials.messages')
<form method="GET" action="" accept-charset="UTF-8" id="users-form">
<div class="row tab-search">
<div class="col-md-2">
<div class="form-group-sm">
<select class="form-control form-control-sm" id="company" name="company">
<option selected disabled>Company</option>
#foreach ($companies as $company)
#if (($company->id)=="1")
<option>All</option>
#else
<option value="{{ $company->id }}">{{ $company->name }}</option>
#endif
#endforeach
</select>
</div>
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-warning btn-sm btn-block" id="filter-user">
<i class="glyphicon glyphicon-filter"></i>
Filter Employee
</button>
</div>
<div class="col-md-1">
<a href="{{ route('user.export') }}" class="btn btn-sm btn-success btn-block">
<i class="fa fa-file-excel-o"></i>
Excel
</a>
</div>
<div class="col-md-2">
<a href="{{ route('user.create') }}" class="btn btn-primary btn-sm btn-block" id="add-user">
<i class="glyphicon glyphicon-plus"></i>
Add
Employee
</a>
</div>
</div>
<div class="row tab-search"> <div class="col-md-2">
<div class="form-group-sm">
<select class="form-control form-control-sm" id="benefit" name="benefit">
<option selected disabled>Benefits</option>
#foreach ($benefits as $benefit)
#if (($benefit->id)=="1")
<option>All</option>
#else
<option value="{{ $benefit->id }}">{{ $benefit->name }}</option>
#endif
#endforeach
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group-sm">
<div class="input-group custom-search-form-sm">
<input type="text" class="form-control form-control-sm" name="search" value="{{ Input::get('search') }}" placeholder="Search Name">
<span class="input-group-btn">
<button class="btn btn-default btn-sm" type="submit" id="search-users-btn">
<span class="glyphicon glyphicon-search"></span>
</button>
#if (Input::has('search') && Input::get('search') != '')
<a href="{{ route('user.list') }}" class="btn btn-danger btn-sm" type="button" >
<span class="glyphicon glyphicon-remove"></span>
</a>
#endif
</span>
</div>
</div>
</div>
</div>
</div>
</form>
<div class="table-responsive" id="users-table-wrapper">
<table class="table table-bordered table-striped table-hover table-condensed" id="datatable-default">
<thead>
<th>#lang('app.full_name')</th>
<th>Sex<i type="button" class="fa fa-fw fa-sort"></th>
<th>Birthday<button name="birthday_sort" style="background-color:#ffffff"><i class="fa fa-fw fa-sort"></button></th>
<th>Age<i class="fa fa-fw fa-sort"></th>
<th>Civil<br>Status<i class="fa fa-fw fa-sort"></th>
<th>Company<i class="fa fa-fw fa-sort"></th>
<th>Department<i class="fa fa-fw fa-sort"></th>
<th>Employee<br>Status<i class="fa fa-fw fa-sort"></th>
<th>Level<i class="fa fa-fw fa-sort"></th>
<th>Date<br>Hired<i class="fa fa-fw fa-sort"></th>
<th>Tenure</th>
</thead>
<tbody>
#if (count($users))
#foreach ($users as $user)
<tr class="gradeX">
<td>{{ $user->first_name . ' ' . $user->middle_name . ' ' . $user->last_name }}</td>
<td>{{ $user->gender[0] }}</td>
<td>{{ $user->birthday->format('M j/y') }}</td>
<td>{{ $user->age }}</td>
<td>{{ $user->civil_status }}</td>
<td>#foreach ($user->company as $company)#endforeach{{ $company->name }}</td>
<td>#foreach ($user->department as $department)#endforeach{{ $department->name }}</td>
<td>{{ $user->emp_status }}</td>
<td>{{ $user->level }}</td>
<td>{{ $user->date_hired }}</td>
<td>{{ $user->difference }}</td>
</tr>
#endforeach
#else
<tr class="gradeX">
<td colspan="6"><em>#lang('app.no_records_found')</em></td>
</tr>
#endif
</tbody>
</table>
{!! $users->render() !!}
</div>
The problem is that it says an error like "all","companies", and etc are undefined variables. Also because the companies is another table. How can define it in my excel that it won't be error again?

It seems you need to pass variables to view from controller which you are passing. Please check my code and update.
public function userExport()
{
$companies = $this->companyModel->get();
$all = $this->something->get();
Excel::create('data_function',function($excel) use($all, $companies) {
$excel->sheet('mysheet', function($sheet) use($all, $companies) {
$sheet->loadView('user.list', ['all' => $all, 'companies' => $companies]);
});
})->download('xls');
}
and also pass the other variables with same as I passed to $sheet->loadView() in example.
I think this will help you.

Related

Laravel 9 "Missing required parameter for [Route:"

I'm using Laravel 9 and trying to use CRUD with my model Project which has the following DB table.
When I try to edit a project using the button "edit" on this view:
"projets.index":
#extends('header')
#section('content')
<div class="col-sm-8" style="background: rgba(204, 204, 204,0.5);padding:5%;width:100%">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2 style="text-align: center">Les projets</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('projets.create') }}"> Créée un nouveau projet</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>id du projet</th>
<th>description</th>
<th width="280px">Action</th>
</tr>
#foreach ($projects as $project)
<tr>
<td>{{ $project->id_project }}</td>
<td>{{ $project->description }}</td>
<td>
<form action="{{ route('projets.destroy',$project->id_project) }}" method="Post">
<a class="btn btn-primary" href="{{ route('galleries.index',$project->id_project,'id_project') }}">ajouter</a>
<a class="btn btn-primary" href="{{ route('projets.edit',[$project->id_project]) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $projects->links() !!}
</div>
#endsection
I have the following error:
"Missing required parameter for [Route: projets.update] [URI: projets/{projet}] [Missing parameter: projet]."
"projets.edit":
#extends('header')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit projet</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('projets.index') }}"> Back</a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('projets.update',$project->id_project) }}" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Company Address:</strong>
<input type="text" name="address" value="{{ $project->description }}" class="form-control" placeholder="Company Address">
#error('address')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<button type="submit" class="btn btn-primary ml-3">Submit</button>
</div>
</form>
#endsection
Update function inside the controller (ProjectController):
public function update(Request $request, $id_project)
{
$request->validate([
'description' => 'required',
]);
User::create($request->all());
$project->description = $request->description;
$project->save();
return redirect()->route('projets.index')
->with('success','project Has Been updated successfully');
}
public function edit(Project $project)
{
return view('projets.edit',compact('project'));
}
Project model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $fillable = [
'id_project', 'description'
];
}
Sorry if my questions seems strange English is not my first language

Too few arguments to function App\Http\Controllers\Home\ClientLogoController::EditClientImage() Controller Laravel

I am using Laravel 9 and I am getting this error I tried various methods to fix this issue but I'm stuck on this . Please help me.
Here is my code:
#php($i=1)
#foreach($client_image as $item)
<tr>
<td>{{ $i++ }}</td>
<td>
<img style="width:60px;height:50px;" src="{{ asset($item->client_logo_images) }}"/>
</td>
<td>
<a href="{{ route('edit.client.logoimage',$item->id) }}">
<i class="glyphicon glyphicon-edit"></i>
</a>
<a class="btn btn-danger sm" href="">
<i class="glyphicon glyphicon-trash"></i>
</a>
</td>
</tr>
#endforeach
I have passed Id with the route and capture. Here is the code. :-
Route::get('/edit/client/image/{id}','EditClientImage')->name('edit.client.logoimage');
And this is my controller code .
public function EditClientImage($id) {
$client_logo=ClientLogoImage::findOrFail($id);
return view('admin.home.edit_client',compact('client_logo'));
}
and an error is showing in line 51. This is my line 51. public function EditClientImage($id)
and I am redirecting it to edit_client Here is the code for edit_client 
<form method="post" action="{{ route('update.client.image') }}" enctype="multipart/form-data">
#csrf
<input name="id" type="hidden" value="{{ $client_logo->id }}" >
<div class="card">
<div class="card-header">
<h3 class="card-title">Edit Profile</h3>
</div>
<div class="card-body">
<div class="row">
<div class="form-group">
<label for="formFile" class="form-label mt-0">Profile Image Upload</label>
<input name="client_image" id="image" class="form-control" type="file" >
</div>
</div>
<button class="btn btn-primary" type="submit">Update</button>
</div>
</form>
Thank You
<a href="{{ route('edit.client.logoimage', ['id' => $item->id]) }}">
You need to name it as id...
the problem is with the way you are using name routing:
if you are using routed names you need to pass the parameter the same as the route:
Route::get('/edit/client/image/{id}','EditClientImage')>name('edit.client.logoimage');
in this, you have the id parameter and your link have to be as:
<a href="{{ route('edit.client.logoimage', ['id' => $item->id]) }}">
<i class="glyphicon glyphicon-edit"></i>
</a>
the other way you can use is just use the URL:
<a href="{{ url('/edit/client/image/' . $item->id) }}">
<i class="glyphicon glyphicon-edit"></i>
</a>

Error with my controller and ajax function

I used AJAX to create live search function, but I have meet the error on my controller. I think it's syntax error on the last td #method('DELETE'), I don't know how to fix it, can anyone help me ?
public function search(Request $request)
{
$output = '';
$users = User::where('name','LIKE','%'.$request->keyword.'%')->get();
foreach($users as $user)
{
$output += '<tr>
<td>
<div class="d-flex px-2 py-1">
<div>
<img src="'. asset('storage/users/' . $user->image) .'"
class="avatar avatar-sm me-3 border-radius-lg" alt="user1">
</div>
<div class="d-flex flex-column justify-content-center">
<h6 class="mb-0 text-sm">{{ $user->name }}</h6>
<p class="text-xs text-secondary mb-0">'. $user->email .'</p>
</div>
</div>
</td>
<td>
<p class="text-xs font-weight-bold mb-0">'. $user->date_of_birth .'</p>
<p class="text-xs text-secondary mb-0">'. $user->phone .'</p>
</td>
<td class="align-middle text-center">
<span
class="text-secondary text-xs font-weight-bold">'. $user->address .'</span>
</td>
<td class="align-middle">
<form action="" method="POST">
{{ csrf_field() }}
#method('DELETE')
<button class="btn btn-danger" data-toggle="tooltip"
data-original-title="Delete user" type="submit">Delete</button>
</form>
</td>
</tr>';
}
return response()->json($output);
}
One clean solution to achieve what you need is to render the HTML as blade file using view('')->render() instead of building it on the controller
Create a new view file at resources/views/partials/user-search.blade.php and move your HTML to it
#foreach ($users as $user)
<tr>
<td>
<div class="d-flex px-2 py-1">
<div>
<img src="{{ asset('storage/users/'.$user->image) }}"
class="avatar avatar-sm me-3 border-radius-lg" alt="user1">
</div>
<div class="d-flex flex-column justify-content-center">
<h6 class="mb-0 text-sm">{{ $user->name }}</h6>
<p class="text-xs text-secondary mb-0">{{ $user->email }}</p>
</div>
</div>
</td>
<td>
<p class="text-xs font-weight-bold mb-0">{{ $user->date_of_birth }}</p>
<p class="text-xs text-secondary mb-0">{{ $user->phone }}</p>
</td>
<td class="align-middle text-center">
<span class="text-secondary text-xs font-weight-bold">{{ $user->address }}</span>
</td>
<td class="align-middle">
<form action="" method="POST">
{{ csrf_field() }}
#method('DELETE')
<button class="btn btn-danger" data-toggle="tooltip"
data-original-title="Delete user" type="submit">Delete</button>
</form>
</td>
</tr>
#endforeach
then modify your Controller search method to something like:
public function search(Request $request)
{
$users = User::where('name', 'LIKE', '%'.$request->keyword.'%')->get();
$output = view('partials.user-search')->with(['users' => $users])->render();
return response()->json($output);
}
Before I propose my fixes note that #ferhsom solution is a really a cleaner and better way to achieve what you need. But still the error in your code need to be pin pointed.
Errors
First the litteral string
Everything written between single quotes is considered as a string (literally) so no function call or variable will work.
The following string as HTML will give you this: enter image description here:
'
<td>
<form action="" method="POST">
{{ csrf_field() }}
#method("DELETE")
<button type="submit">Delete</button>
</form>
</td>
'
But what you need is hidden inputs with the keys _method and _token.
Second no Blade rendering
#method and #csrf are a Blade directives which will not make any sense if it doesn't pass through the rendering process.
Solution
Replace #method('DELETE') with:
'<input type="hidden" name="_method" value="DELETE">'
For #csrf or {{ csrf_field() }} do:
'<input type="hidden" name="_token" value="' . csrf_token() . '">'
Or
'' . csrf_field() . ''

How to construct a column table using forelse and if in laravel?

this my source code and I apologize for the messy layout of my code syntax, i want to fill the td like this
<tbody>
#forelse ($kaders as $kader)
<tr>
<td>{{ $kader->username }}</td>
#if($kader->status_user == '1')
<td>Admin</td>
#elseif($kader->status_user == '0')
<td>Ibu / Guest</td>
#endif
#forelse ($surveillances as $surveillance)
#if($kader->username == $surveillance->nik_ortu)
#if($surveillance->status == '1')
<td>Aktif</td>
#elseif($surveillance->status == '0')
<td>NonAKtif</td>
#endif
#endif
<!-- <td>admin</td> -->
#empty
<td>admin</td>
#endforelse
<td class="text-center">
<form onsubmit="return confirm('Apakah Anda Yakin ?');" action="{{ route('kader.destroy', $kader->id) }}" method="POST">
#method('DELETE')
#csrf
<a href="{{ route('kader.edit', $kader->id) }}" class="btn btn-sm btn-primary">
<i class="far fa-edit"></i> EDIT
</a>
<button type="submit" class="btn btn-sm btn-danger">
<i class="far fa-trash-alt"></i> HAPUS
</button>
</form>
</td>
</tr>
#empty
<div class="alert alert-danger">
Data Kader belum Tersedia.
</div>
#endforelse
</tbody>
how can i construct like the pic above ? thank you for advice
You need to set the table cell outside the if-then block so if there's nothing an empty cell will be created instead of no cell. Change this:
#if($kader->status_user == '1')
<td>Admin</td>
#elseif($kader->status_user == '0')
<td>Ibu / Guest</td>
#endif
#forelse ($surveillances as $surveillance)
#if($kader->username == $surveillance->nik_ortu)
#if($surveillance->status == '1')
<td>Aktif</td>
#elseif($surveillance->status == '0')
<td>NonAKtif</td>
#endif
#endif
<!-- <td>admin</td> -->
#empty
<td>admin</td>
#endforelse
to this:
<td>
#if($kader->status_user == '1')
Admin
#elseif($kader->status_user == '0')
Ibu / Guest
#endif
</td>
<td>
#forelse ($surveillances as $surveillance)
#if($kader->username == $surveillance->nik_ortu)
#if($surveillance->status == '1')
Aktif
#elseif($surveillance->status == '0')
NonAKtif
#endif
#endif
<!-- <td>admin</td> -->
#empty
admin
#endforelse
</td>
<tbody>
#forelse ($kaders as $kader)
<tr>
<td>{{ $kader->username }}</td>
<td>
#if($kader->status_user == '1')
Admin
#elseif($kader->status_user == '0')
Ibu / Guest
#endif
</td>
<td>
#forelse ($surveillances as $surveillance)
#if($kader->username == $surveillance->nik_ortu)
#if($surveillance->status == '1')
Aktif
#elseif($surveillance->status == '0')
NonAKtif
#endif
#endif
#empty
admin
#endforelse
</td>
<td class="text-center">
<form onsubmit="return confirm('Apakah Anda Yakin ?');" action="{{ route('kader.destroy', $kader->id) }}" method="POST">
<i class="far fa-edit"></i> EDIT
#csrf
#method('DELETE')
<button type="submit" class="btn btn-sm btn-danger"><i class="far fa-trash-alt"></i> HAPUS</button>
</form>
</td>
</tr>
#empty
<div class="alert alert-danger">
Data Kader belum Tersedia.
</div>
#endforelse
</tbody>

How to show data of current logged user in laravel

I have three tables. First is user which has an 'email' as a username. Second is customer which alos has email column. And third table is shipments. The shipment has relationship with customer table. User can login with email id which is present in User and Customer table. When user is logged in with their email I wamt to show shipments related to respective user, filterdered by email address of current logged in user. Please guide be. below is my index.blade.php
#extends('layouts.app')
#section('content')
<div class="page-titles">
<h2> Vishal {{ $pageTitle }} <small> {{ $pageNote }} </small></h2>
<h4></h4>
</div>
<div class="card">
<div class="card-body">
<div class="toolbar-nav" >
<div class="row">
<div class="col-md-4 col-4">
<div class="input-group ">
<input type="text" class="form-control form-control-sm onsearch" data-target="{{ url($pageModule) }}" aria-label="..." placeholder=" Type And Hit Enter ">
</div>
</div>
<div class="col-md-8 col-8 text-right">
<div class="btn-group">
#if($access['is_add'] ==1)
<a href="{{ url('shipments/create?return='.$return) }}" class="btn btn-sm btn-primary"
title="{{ __('core.btn_create') }}"><i class="fas fa-plus"></i> {{ __('core.btn_create') }}</a>
#endif
<div class="btn-group">
<button type="button" class="btn btn-sm btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-bars"></i> Bulk Action </button>
<ul class="dropdown-menu">
#if($access['is_remove'] ==1)
<li class="nav-item"><a href="javascript://ajax" onclick="SximoDelete();" class="nav-link tips" title="{{ __('core.btn_remove') }}">
Remove Selected </a></li>
#endif
#if($access['is_add'] ==1)
<li class="nav-item"><a href="javascript://ajax" class=" copy nav-link " title="Copy" > Copy selected</a></li>
<div class="dropdown-divider"></div>
<li class="nav-item"> Import CSV</li>
#endif
<div class="dropdown-divider"></div>
#if($access['is_excel'] ==1)
<li class="nav-item"> Export Excel </li>
#endif
#if($access['is_csv'] ==1)
<li class="nav-item"> Export CSV </li>
#endif
#if($access['is_pdf'] ==1)
<li class="nav-item"> Export PDF </li>
#endif
#if($access['is_print'] ==1)
<li class="nav-item"> Print Document </li>
#endif
<div class="dropdown-divider"></div>
<li class="nav-item"> Clear Search </li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- Table Grid -->
{!! Form::open(array('url'=>'shipments?'.$return, 'class'=>'form-horizontal m-t' ,'id' =>'SximoTable' )) !!}
<div class="table-responsive">
<table class="table table-hover table-striped " id="{{ $pageModule }}Table">
<thead>
<tr>
<th style="width: 3% !important;" class="number"> No </th>
<th style="width: 3% !important;">
<input type="checkbox" class="checkall filled-in" id="checked-all" />
<label for="checked-all"></label>
</th>
#foreach ($tableGrid as $t)
#if($t['view'] =='1')
<?php $limited = isset($t['limited']) ? $t['limited'] :'';
if(SiteHelpers::filterColumn($limited ))
{
$addClass='class="tbl-sorting" ';
if($insort ==$t['field'])
{
$dir_order = ($inorder =='desc' ? 'sort-desc' : 'sort-asc');
$addClass='class="tbl-sorting '.$dir_order.'" ';
}
echo '<th align="'.$t['align'].'" '.$addClass.' width="'.$t['width'].'">'.\SiteHelpers::activeLang($t['label'],(isset($t['language'])? $t['language'] : array())).'</th>';
}
?>
#endif
#endforeach
<th style="width: 10% !important;">{{ __('core.btn_action') }}</th>
</tr>
</thead>
<tbody>
#foreach ($rowData as $row)
<tr>
<td class="thead"> {{ ++$i }} </td>
<td class="tcheckbox">
<input type="checkbox" class="ids filled-in" name="ids[]" value="{{ $row->id }}" id="val-{{ $row->id }}" />
<label for="val-{{ $row->id }}"></label>
</td>
#foreach ($tableGrid as $field)
#if($field['view'] =='1')
<?php $limited = isset($field['limited']) ? $field['limited'] :''; ?>
#if(SiteHelpers::filterColumn($limited ))
<?php $addClass= ($insort ==$field['field'] ? 'class="tbl-sorting-active" ' : ''); ?>
<td align="{{ $field['align'] }}" width=" {{ $field['width'] }}" {!! $addClass !!} >
{!! SiteHelpers::formatRows($row->{$field['field']},$field ,$row ) !!}
</td>
#endif
#endif
#endforeach
<td>
<div class="dropdown">
<button class="btn dropdown-toggle" type="button" data-toggle="dropdown"><i class="fas fa-tasks"></i> </button>
<ul class="dropdown-menu">
#if($access['is_detail'] ==1)
<li class="nav-item"> {{ __('core.btn_view') }} </li>
#endif
#if($access['is_edit'] ==1)
<li class="nav-item"> {{ __('core.btn_edit') }} </li>
#endif
<div class="dropdown-divider"></div>
#if($access['is_remove'] ==1)
<li class="nav-item"><a href="javascript://ajax" onclick="SximoDelete();" class="nav-link tips" title="{{ __('core.btn_remove') }}">
Remove Selected </a></li>
#endif
</ul>
</div>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<input type="hidden" name="action_task" value="" />
{!! Form::close() !!}
<!-- End Table Grid -->
</div>
#include('footer')
</div>
</div>
<script>
$(document).ready(function(){
$('.copy').click(function() {
var total = $('input[class="ids"]:checkbox:checked').length;
if(confirm('are u sure Copy selected rows ?'))
{
$('input[name="action_task"]').val('copy');
$('#SximoTable').submit();// do the rest here
}
})
});
</script>
#stop
So you want to display shipments of a logged-in user? Then at this point, I'm expecting that you have already defined the Eloquent Relationships as methods on your Eloquent User and Shipment model classes and actually able to save the data.
In your Controller
use Illuminate\Support\Facades\Auth;
public function index()
{
$user = Auth::user()->load('shipments');
return view('sample.index', ['user' => $user]);
}
With the Auth::user() it checks if the current user is authenticated (returns true if the user is logged-in) via the Auth facade. Since the User model has already been retrieved, you can use Lazy Eager Loading with the load() to load the Shipment model.
And in your blade, you can display user's info and iterate over the shipment collection like so:
#foreach ($user->shipments as $shipment)
<p>{{ $shipment->field }}</p>
#endforeach

Categories