One of my project needs code indentation, it has many of controller files looking like below code.
so basically I want to do is format code which should be done automatically without changing each file manually.
Controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use File;
use Html;
use DB;
use Illuminate\Validation\Rule;
use Illuminate\Support\Str;
use Validator;
use Datatables;
use AppHelper;
use LaraCore;
use Image;
use App\Models\Customer;
use App\Models\_List;
use Carbon;
class CustomerController extends Controller
{
public function validator(array $data, $id = NULL)
{
$email_Rules = explode(',',"required,email,unique");
$email_Rules['unique'] = Rule::unique('customers')->ignore($id);
if(($key = array_search('unique',$email_Rules)) !== false) {
unset($email_Rules[$key]);
}
return Validator::make($data, [
'secret_key' => 'required|min:6|max:10',
'email' => $email_Rules,
'first_name' => 'required|alpha_num',
'city' => 'required',
]
);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('panel.customers.index');
}
public function create()
{
$data = array();
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
return view('panel.customers.create',$data);
}
public function edit($id,Request $request)
{
$data = array();
$Dates = array();
$customers = Customer::findOrFail($id);
$data['customers'] = $customers;
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$preference= explode(',',$customers->preference);
$customers->preference = $preference;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
if($customers->ready!=''){
$ready= explode(',',$customers->ready);
$customers->ready = $ready;
}
if($customers->approved!=''){
$approved= explode(',',$customers->approved);
$customers->approved = $approved;
}
$Name = explode(',','start_date,end_date');
$Dates[0] = new Carbon($customers->$Name[0]);
$Dates[1] = new Carbon($customers->$Name[1]);
$data['start_dateend_date'] = $Dates[0]->format('m/d/Y').' - '.$Dates[1]->format('m/d/Y') ;
return view('panel.customers.create',$data);
}
public function store(Request $request,$id="")
{
$this->validator($request->all(),$request->id)->validate();
if($request->id == null || $request->id == ""){
$inputs = $request->all();
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}else{
$inputs['ready'] = "";
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$nameArr = explode(',',$key_file);
$file = $value_file;
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
}
Customer::create($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
else{
$customers = Customer::where(['id'=>$request->input('id')])->first();
$inputs = $request->except('_token');
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$nameArr = explode(',',$key_file);
$OldFile = $customers->$nameArr[1];
if($OldFile!=''){
$OldFile = $destinationPath.'/'.$OldFile;
if(\File::exists($OldFile)){
\File::delete($OldFile);
}
}
$file = $value_file;
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
$SavedFile = $destinationPath.$encrypted_name;
}
$customers->update($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
}
public function listCustomer(Request $request)
{
$customers = Customer::all();
$datatables = Datatables::of($customers)
->addColumn('actions', function($customers){
$html = '';
$html .= '<i class="fa fa-edit"></i>';
$html .= '<i class="fa fa-trash"></i>';
return $html;
})
->setRowId('id');
return $datatables->make();
}
public function destroy($id)
{
$customer = Customer::find($id);
$customer->delete();
return response()->json(array(
"status" => "success",
"message" => "Customer Deleted Successfully",
));
}
}
Maybe you could call a php beautifier on the file you created ? http://pear.php.net/package/PHP_Beautifier/
Note : you can call a command with exec
exec("php_beautifier $filename $filename");
It is hard to tell without more of your source but I imagine expressions like explode(',', $value["dbfield"] )[0] are catching some sort of tab character or importing blank fields that are somehow translated into spaces or tabs and causing the unwanted spacing.
#foreach($fields as $key => $value)
#if($value['dbfield'] == '')
#continue
#endif
#if($value['validation'])
#if(in_array('unique',explode(',',$value['validation'])))
'{{$value['dbfield']}}' => ${{$value['dbfield']}}_rules,
#else
#if(strpos($value["dbfield"],","))
'{{ explode(',', $value["dbfield"] )[0] }}' => '{{str_replace(',', '|', $value['validation'])}}',
#else
'{{$value['dbfield']}}' => '{{str_replace(',', '|', $value['validation'])}}',
#endif
#endif
#endif
#endforeach
Related
I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.
Created a simple miniCMS in a portal for content creation. The issue at first was in TinyMCE stripping of id attribute from html tag I've resolved that using valid_elements now the request is being sent to Model as is with no issues however in the Model level it's stripping the id again
Example
<div id="agreement">text ......... </div>
Being Saved in model as
<div>text ......... </div>
The controller code:
public function frontendContent(Request $request, $key)
{
$purifier = new \HTMLPurifier();
$valInputs = $request->except('_token', 'image_input', 'key', 'status', 'type');
foreach ($valInputs as $keyName => $input) {
if (gettype($input) == 'array') {
$inputContentValue[$keyName] = $input;
continue;
}
$inputContentValue[$keyName] = $purifier->purify($input);
}
$type = $request->type;
if (!$type) {
abort(404);
}
$imgJson = #getPageSections()->$key->$type->images;
$validation_rule = [];
$validation_message = [];
foreach ($request->except('_token', 'video') as $input_field => $val) {
if ($input_field == 'has_image' && $imgJson) {
foreach ($imgJson as $imgValKey => $imgJsonVal) {
$validation_rule['image_input.'.$imgValKey] = ['nullable','image','mimes:jpeg,jpg,png,svg'];
$validation_message['image_input.'.$imgValKey.'.image'] = inputTitle($imgValKey).' must be an image';
$validation_message['image_input.'.$imgValKey.'.mimes'] = inputTitle($imgValKey).' file type not supported';
}
continue;
}elseif($input_field == 'seo_image'){
$validation_rule['image_input'] = ['nullable', 'image', new FileTypeValidate(['jpeg', 'jpg', 'png'])];
continue;
}
$validation_rule[$input_field] = 'required';
}
$request->validate($validation_rule, $validation_message, ['image_input' => 'image']);
if ($request->id) {
$content = Frontend::findOrFail($request->id);
} else {
$content = Frontend::where('data_keys', $key . '.' . $request->type)->first();
if (!$content || $request->type == 'element') {
$content = Frontend::create(['data_keys' => $key . '.' . $request->type]);
}
}
if ($type == 'data') {
$inputContentValue['image'] = #$content->data_values->image;
if ($request->hasFile('image_input')) {
try {
$inputContentValue['image'] = uploadImage($request->image_input,imagePath()['seo']['path'], imagePath()['seo']['size'], #$content->data_values->image);
} catch (\Exception $exp) {
$notify[] = ['error', 'Could not upload the Image.'];
return back()->withNotify($notify);
}
}
}else{
if ($imgJson) {
foreach ($imgJson as $imgKey => $imgValue) {
$imgData = #$request->image_input[$imgKey];
if (is_file($imgData)) {
try {
$inputContentValue[$imgKey] = $this->storeImage($imgJson,$type,$key,$imgData,$imgKey,#$content->data_values->$imgKey);
} catch (\Exception $exp) {
$notify[] = ['error', 'Could not upload the Image.'];
return back()->withNotify($notify);
}
} else if (isset($content->data_values->$imgKey)) {
$inputContentValue[$imgKey] = $content->data_values->$imgKey;
}
}
}
}
$content->update(['data_values' => $inputContentValue]);
$notify[] = ['success', 'Content has been updated.'];
return back()->withNotify($notify);
}
When I dd the request
as dd($request) I can see the html tag in full
<div id="agreement">text ......... </div>
But when I dd the content
as dd($content) I can see that the id attribute is stripped
<div>text ......... </div>
The model part
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Frontend extends Model
{
protected $guarded = ['id'];
protected $table = "frontends";
protected $casts = [
'data_values' => 'object'
];
public static function scopeGetContent($data_keys)
{
return Frontend::where('data_keys', $data_keys);
}
}
Kindly asking for help, thank you!
While checking the forum here at SOF I found a solution with a remark from #FarhanIbnWahid thanks to him.
$config = HTMLPurifier_Config::createDefault();
$config->set('Attr.EnableID', true);
$purifier = new \HTMLPurifier($config);
This will resolve the issue.
I am trying to export a sheet with multiple workbooks and to generate each workbook from a view. I have created 5 different .blade files containing HTML tables and want to generate each work book from each .blade file.
I am trying to export a sheet with multiple workbooks and to generate each workbook from a view. I have created 5 different .blade files containing HTML tables and want to generate each work book from each .blade file.
<?php
namespace App\Exports;
use App\Models\GenerateQrCode;
use App\Models\Scan;
use DateInterval;
use DatePeriod;
use DateTime;
use Hashids\Hashids;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Excel;
class ScansExport implements FromView,WithMultipleSheets {
public $id;
public $from;
public $to;
public function __construct($id,$request) {
$this->from = $request['from'];
$this->to = $request['to'];
$this->id = $id;
}
public function getScansCountGroupBy($id, $field) {
return Scan::where('qr_code_id', $id)->select($field, \DB::raw('count(*) as scans'))->groupBy($field)->orderBy('created_at', 'asc')->get();
}
public function view(): View {
$id = \Hashids::decode($this->id)[0];
$data['qrCode'] = GenerateQrCode::find($id);
if ($this->from && $this->to) {
$from = $this->from . ' 00:00:00';
$to = $this->to . ' 23:59:59';
$data['from'] = $this->from;
$data['to'] = $this->to;
} else {
$from = date('Y-m-d', strtotime("-30 days")) . ' 00:00:00';
$to = date('Y-m-d') . ' 23:59:59';
$data['from'] = date('Y-m-d', strtotime("-30 days"));
$data['to'] = date('Y-m-d');
}
$data['scansList'] = Scan::where('qr_code_id', $id)->whereBetween('created_at', [$from, $to])->orderBy('created_at', 'desc')->get();
$data['firstScan'] = Scan::where('qr_code_id', $id)->whereBetween('created_at', [$from, $to])->first();
$data['scansDataPoints'] = [];
$data['uniqueUsersDataPoints'] = [];
if (!empty($data['firstScan'])) {
$data['countryCount'] = Scan::where('qr_code_id', $id)->whereBetween('created_at', [$from, $to])->where('country', $data['firstScan']->country)->count();
$data['deviceCount'] = Scan::where('qr_code_id', $id)->whereBetween('created_at', [$from, $to])->where('device', $data['firstScan']->device)->count();
/*
** Countries
** Cities
** Languages
*/
$data['countries'] = $this->getScansCountGroupBy($id, 'country');
$data['cities'] = $this->getScansCountGroupBy($id, 'city');
$data['languages'] = $this->getScansCountGroupBy($id, 'language');
/*
** Devices
** Platforms
** Browsers
*/
$data['devices'] = $this->getScansCountGroupBy($id, 'device');
$data['platforms'] = $this->getScansCountGroupBy($id, 'platform');
$data['browsers'] = $this->getScansCountGroupBy($id, 'browser');
// $period = new \DatePeriod(
// new \DateTime(date('Y-m-d', strtotime("-30 days"))),
// new \DateInterval('P1D'),
// new \DateTime(date('Y-m-d', strtotime("+1 days")))
// );
$period = new \DatePeriod(
new \DateTime($from),
new \DateInterval('P1D'),
new \DateTime($to)
);
/*
** Scans Graph
*/
$scans = Scan::where('qr_code_id', $id)->whereBetween('created_at', [$from, $to])->select(\DB::raw('DATE(created_at) as date'), \DB::raw('count(*) as scans'))->groupBy('date')->orderBy('created_at', 'asc')->get()->toArray();
$scansDataPoints = array();
foreach ($period as $key => $value) {
$date = $value->format('Y-m-d');
$index = array_search($value->format('Y-m-d'), array_column($scans, 'date'));
if ($index !== false) {
$scansDataPoints[$date] = $scans[$index]['scans'];
} else {
$scansDataPoints[$date] = 0;
}
}
$data['scansDataPoints'] = $scansDataPoints;
/*
** Unique Users Graph
*/
$unique_users = Scan::where('qr_code_id', $id)->whereBetween('created_at', [$from, $to])->select(\DB::raw('DATE(created_at) as date'), \DB::raw('count(DISTINCT ip) as unique_count'))->groupBy('date')->orderBy('created_at', 'asc')->get()->toArray();
$uniqueUsersDataPoints = array();
foreach ($period as $key => $value) {
$date = $value->format('Y-m-d');
$index = array_search($value->format('Y-m-d'), array_column($unique_users, 'date'));
if ($index !== false) {
$uniqueUsersDataPoints[$date] = $unique_users[$index]['unique_count'];
} else {
$uniqueUsersDataPoints[$date] = 0;
}
}
$data['uniqueUsersDataPoints'] = $uniqueUsersDataPoints;
}
// $array = [
// view('frontend.dashboard.export-statistics.qrcode-countries', $data),
// view('frontend.dashboard.export-statistics.qrcode-cities', $data),
// ];
return $data;
}
public function sheets(): array {
$data = $this->view();
return [
view('frontend.dashboard.export-statistics.qrcode-countries', $data),
view('frontend.dashboard.export-statistics.qrcode-cities', $data),
];
}
}
You cannot pass views as sheets. You must create individual sheet exports for each view. Then you can combine them using the WithMultipleSheets concern.
CountriesExport.php
class CountriesExport implements FromView
{
public function view(): View
{
$data = ...
return view('frontend.dashboard.export-statistics.qrcode-countries', $data);
}
}
CitiesExport.php
class CitiesExport implements FromView
{
public function view(): View
{
$data = ...
return view('frontend.dashboard.export-statistics.qrcode-cities', $data);
}
}
ScansExport.php
class ScansExport implements WithMultipleSheets
{
public function sheets(): array
{
return [
new CountriesExport(),
new CitiesExport(),
];
}
}
**Am new to laravel8 trying to import data from excel sheet to the database, here is my code in the import class its not passing not giving any error. so the database has relationship am trying to import the data and make sure the relationships are considered so that l shouldn't have any problems **
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use App\Models\District;
use App\Models\Organisation;
use App\Models\FocalPerson;
use App\Models\Ta;
use App\Models\Location;
use App\Models\Service;
use App\Models\Category;
use App\Models\Type;
class InformationImport implements ToCollection
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
$instance_id = $row[1];
$organisation_name = $row[2];
$service_provider = $row[3];
$catchment_area = $row[4];
$organisation_type = $row[5];
$district_name = $row[6];
$organisation_web = $row[7];
$primary_name = $row[8];
$primary_title = $row[9];
$primary_number = $row[10];
$primary_email = $row[11];
$secondary_name = $row[12];
$secondary_number = $row[13];
$secondary_title = $row[14];
$secondary_email = $row[15];
$services_name = $row[16];
$location = explode(',',$row[17],2);
return $location;
$location_altitude = $row[18];
$location_accuracy = $row[19];
$comments_distance = $row[20];
$data_comments = $row[21];
$ta = Ta::where('name','like','%'.$row[4] .'%')->whereHas('district',
function($query) use($district_name){
$query->where('name','like','%'.$district_name .'%');
})->get();
if(!$ta){
$district = District::firstOrCreate([
'name' => $row[6]
]);
$ta = new Ta;
$ta->name = $row[4];
$district->tas()->save($ta);
}
$gvh = Gvh::firstOrCreate([
'name' => 'unknown',
'ta_id' => $ta->id
]);
$location = Location::firstOrCreate([
'latitude'=>$location,
'longitude'=>$location,
'gvh_id'=> $gvh->id
]);
$service = Service::firstOrCreate([
'name'=>$services_name
]);
$category = Category::firstOrCreate([
'name'=>'unknown'
]);
$type = Type::firstOrCreate([
'name'=>$organisation_type
]);
$organisation = Organisation::firstOrCreate([
'name'=> $organisation_name,
'location_id' => $location->id,
'organisation_type_id' => $type->id,
'organisation_category_id' => $category->id
]);
$focalperson =FocalPerson::firstOrCreate([
'title'=> $primary_title, $secondary_title,
'name' => $primary_name,$secondary_name,
'phonenumber'=>$primary_number,$secondary_number,
'email'=> $primary_email, $secondary_email
]);
}
}
}
**below is my controller class. in the controller that's the code l have because it wasn't bringing anything l had to write it in that way and see if it will be able to output the messages **
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Imports\InformationImport;
use Maatwebsite\Excel\Facades\Excel;
class InformationController extends Controller
{
public function import(Request $request)
{
//Excel::import(new InformationImport, $request->file);
//return response()->json(['message' => 'Your data imported successfully !'], 200);
if ($request->ajax()) {
try {
Excel::import(new InformationImport, $request->file);
return response()->json(['message' => 'Your data imported successfully !'], 200);
} catch (ValidationException $ex) {
$failures = $ex->failures();
foreach ($failures as $failure) {
return response()->json(['message' => 'Row - ' . $failure->row() . ', ' . $failure->errors()[0]], 500);
}
}
}
return response()->json(['message' => 'Something went wrong !'], 500);
}
}
public function import(Request $request)
{
ini_set('max_execution_time', -1);
ini_set('memory_limit ', -1);
if ($request->ajax()) {
try {
$file_content = $request->file('excel');
$file_name = time() . '.xlsx';
Storage::disk('local')->putFileAs('public', $file_content, $file_name);
$url = "/app/public/" . $file_name;
$path = storage_path() . $url;
Excel::import(new InformationImport, $path);
return response()->json(['message' => 'Your data imported successfully !'], 200);
} catch (ValidationException $ex) {
$failures = $ex->failures();
foreach ($failures as $failure) {
return response()->json(['message' => 'Row - ' . $failure->row() . ', ' . $failure->errors()[0]], 500);
}
}
}
return response()->json(['message' => 'Something went wrong !'], 500);
}
This is sample and runnable code. Please refer
In Your Controller
public function import(Request $request){
$this->validate($request,[
'file'=> 'required|mimes:xlsx,csv'
]);
try{
Excel::import(new CannedResponseImport,request()->file('file'));
return back()
->withSuccess('Data imported successfully.');
}catch(\Exception $ex){
return back()
->withError('Someting went wrong please try again.');
}
}
In your Import
<?php
namespace App\Imports;
use App\Models\CannedResponses;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Validator;
class CannedResponseImport implements ToCollection,WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function collection(Collection $rows)
{
foreach ($rows as $row) {
if($row->filter()->isNotEmpty()){
if(!empty($row['business_type_id']) && !empty($row['brand_id']) && !empty($row['contact_reason_id'])
&& !empty($row['contact_sub_reason_id']) && !empty($row['personality_type_id']) && !empty($row['response_segment_id'])
&& !empty($row['response_tone_id']) && !empty($row['nature_conversation_id']) && !empty($row['canned_response'])
){
$id = CannedResponses::insertGetId([
'business_type_id' => $row['business_type_id'],
'brand_id' => $row['brand_id'],
'contact_reason_id' => $row['contact_reason_id'],
'contact_sub_reason_id' => $row['contact_sub_reason_id'],
'nature_conversation_id' => $row['nature_conversation_id'],
'personality_type_id' => $row['personality_type_id'],
'response_segment_id' => $row['response_segment_id'],
'response_tone_id' => $row['response_tone_id'],
'message' => $row['canned_response']
]);
}
}
}
}
}
When I showed it in a browser when upgrading to symfony3, I had a title error (line 25).
I had questions on similar mistakes in StackOverflow, but I think it's a different trend.
I want to know how it can be improved.
Stack Trace
[1] Symfony\Component\Debug\Exception\FatalErrorException: Error:
Cannot use object of type Symfony\Component\HttpFoundation\Request as array
at n/a
in /Symfony/.../Bundle/Listener/PortalListener.php line 25
Code
PortalListener.php
<?php
namespace Ahi\Sp\PublicBundle\Listener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Ahi\Sp\PublicBundle\Controller\BaseController;
use Ahi\Sp\PublicBundle\Model\Service\AhiCookieService;
use Symfony\Component\HttpFoundation\Request;
/**
*/
class PortalListener
{
/*
*
* #param FilterControllerEvent $event
*/
public function preControllerExecute(FilterControllerEvent $event, Request $request)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$_controller = $event->getRequest();
if (isset($_controller[0])) { //line25
$controller = $_controller[0];
if (method_exists($controller, 'preExecute')) {
$controller->preExecute($request);
}
}
}
}
BaseController.php
<?php
namespace Ahi\Sp\PublicBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
/ **
* Front controller.
* /
abstract class BaseController extends Controller
{
const MAX_ITEM_COUNT = 4; // Maximum number to get the item part number from the coordination. (You can get up to 4)
protected $parameters = array();
protected $response = null;
protected $cookie = null;
public function preExecute (Request $request) {
$this->cookie = $this->get('public.ahiCookieService');
// ---------------------------------------
// Gender (The order is the member's gender → portal top gender button → brand → shop → MEN'S $LADIE'S button)
$this->gender = $this->cookie->get('gender');
// Get the brand and overwrite the gender of the brand
$this->brand = null;
$brandDir = null;
$brandDirUrlParam = $request->attributes->get('brandDir');
$brandDirGetParam = $request->query->get('brandDir');
if ($brandDirUrlParam) {
$brandDir = $brandDirUrlParam;
} elseif ($brandDirGetParam) {
$brandDir = $brandDirGetParam;
}
$brandService = $this->get('public.brandService');
if ($brandDir) {
$brand = $brandService->getBrand($brandDir);
if (!$brand) {
throw $this->createBrandNotFoundException();
}
if(!$this->isPreview() && !$brand->getDispFlg()) {
throw $this->createBrandNotFoundException();
}
$brandSex = $brand->getBrandSex();
if ($brandSex != 2) {
$this->gender = $brandSex;
}
$this->brand = $brand;
}
// shop --------------------------------->
$this->shop = null;
$shopDir = null;
$shopDirUrlParam = $request->attributes->get('shopDir');
$shopDirGetParam = $request->query->get('shopDir');
if ($shopDirUrlParam) {
$shopDir = $shopDirUrlParam;
} elseif ($shopDirGetParam) {
$shopDir = $shopDirGetParam;
}
$this->shopDir = $shopDir;
$shopService = $this->get('public.shopService');
if ($shopDir) {
$shop = $shopService->getShop($shopDir);
if (!$shop) {
throw $this->createShopNotFoundException();
}
if (!$this->isPreview() && !$shop->getDispFlg()) {
if ($shop->getRedirectFlg() == true) {
$redirectUrl = $shop->getRedirectUrl();
if (empty($redirectUrl)) {
$redirectUrl = $this->generateUrl('ahi_sp_public_brand_top', array('brandDir' => $shop->getBrand()->getDirName()));
}
throw new ShopRedirectException($redirectUrl);
} else {
throw $this->createShopNotFoundException();
}
}
$shopSex = $shop->getShopSex();
if ($shopSex != 2) {
$this->gender = $shopSex;
}
$this->shop = $shop;
}
// shop <---------------------------------
$gender = $request->query->get('gender');
if ($gender !== null) {
$this->gender = $gender;
}
if ($this->getRequest()->get('_route') !== 'ahi_sp_public_portal_top') {
$gender = $request->query->get('gender');
if ($gender !== null) {
$this->gender = $gender;
}
}
if ($this->gender !== null) {
$this->gender = intval($this->gender);
$this->cookie->set('gender', $this->gender, 30);
$this->cookie->set('ec_gender', $this->gender, 30);
}
if ($this->gender === 0 or $this->gender === 1) {
$this->paramsSex = array('sex'=> array($this->gender, 2));
} else {
$this->paramsSex = array('sex'=> array(0, 1, 2));
}
$mid = $this->cookie->get('member_id');
$session = $request->getSession();
if ($mid && !$session->has('favoriteShops')) {
$route = $this->container->getParameter('ats_http');
$list = $this->container->getParameter('favorite_shop_list');
$url = $route . $list . $mid;
$ahiStoreIdList = file_get_contents($url);
$favoriteShops = array();
if ($ahiStoreIdList !=='') {
$ahiStoreIdArray = explode(",", $ahiStoreIdList);
$shopService = $this->get("public.shopService");
$sortKey = array();
foreach ($ahiStoreIdArray as $key => $storeId) {
$id = explode(':', $storeId);
$shop = $shopService->getShopById($id[1]);
if ($shop) {
$favoriteShops[$key]['shopName'] = $shop->getShopName();
$favoriteShops[$key]['shopDir'] = $shop->getDirName();
$sortKey[$key] = $shop->getShopName();
}
}
array_multisort($sortKey, SORT_ASC, $favoriteShops);
}
$session->set('favoriteShops', $favoriteShops);
}
$trend_tag_list_limit = $this->container->getParameter("trend_tag_list_limit");
if(!$brandDirUrlParam and !$shopDirUrlParam){
$this->parameters['brandPrefectures'] = $this->service('coordinate')->getPrefExistBrand();
$this->parameters['prefBrands'] = $this->service('coordinate')->getBrandPerPref();
$this->parameters['shopBrandPrefectures'] = $this->service('brand')->getPrefExistBrand();
$this->parameters['shopPrefBrands'] = $this->service('brand')->getBrandPerPref();
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->paramsSex,false,$trend_tag_list_limit);
}elseif($brandDirUrlParam){
$this->parameters['brandPrefectures'] = $this->service('coordinate')->getPrefExistBrand($brandDirUrlParam);
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->brand,false,$trend_tag_list_limit);
}else{
$this->parameters['coordinateCount'] = $this->service('coordinate')->getCountArticle(
$this->brand,
$this->shop
);
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->shop->getBrand(),false,$trend_tag_list_limit);
}
}
Version
Cent OS 6.7
PHP 5.6
Symfony3.0.9
The error was resolved when I fixed it as follows.
public function preControllerExecute(FilterControllerEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$request = $event->getRequest();
$_controller = $event->getController();
if (isset($_controller[0])) {
$controller = $_controller[0];
if (method_exists($controller, 'preExecute')) {
$controller->preExecute($request);
}
}
}
}