Undefined index: description - Uploading Excel File - laravel

Is there a way i can stop the reader from reading the excel file when any of the row data is different? When i upload an excel file, i get Undefined index: description which means description cannot be found in the file uploaded.
Is there a way i can just handle this error ?
if ($request->file('imported-file')) {
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader) {
$reader->calculate(false);
})->get();
if (($request->file('imported-file')->getClientOriginalExtension()) != 'xlsx') {
return redirect('')->with('error','File Format may not be supported');
} else {
if (!empty($data) && $data->count()) {
foreach ($data->toArray() as $row) {
if (!empty($row)) {
$dataArray[] = [
'name' => $row['name'],
'description' => $row['description'],
];
}
}
if (!empty($dataArray)) {
Item::insert($dataArray);
return redirect('')->with('status','successfully added');
}
}
}
}

Instead of:
'description' => $row['description'],
you could use
'description' => array_get($row, 'description'),

I was also facing the same issue, here is my solution, Hope it will help someone.
Note : This is for Laravel 6.0, Importer class must implements ToModel, WithHeadingRow these two interfaces,
return new Holiday([
'name' => Arr::get($row,'name'),
'start_date' => Arr::get($row,'start_date'),
'end_date' => Arr::get($row,'end_date'),
]);

Related

Laravel ErrorException Undefined variable in my public function

I ran into the error:
ErrorException Undefined variable: pesan
I have gone through similar problems solved here but none of the solutions have worked for me.
The error is thrown from my RegisterController at bottom of the line. At the pesan
I use laravel 8
Here is my controller code:
` public function simpan_rm(Request $request)
{
$this->validate($request, [
'idpasien' => 'required|numeric|digits_between:1,4',
'keluhan_utama' => 'required|max:40',
'anamnesis' => 'required|max:1000',
'px_fisik' => 'max:1000',
'diagnosis' => 'max:40',
'dokter' => 'required',
]);
// Decoding array input pemeriksaan lab
if (isset($request->lab))
{
if (has_dupes(array_column($request->lab,'id'))){
$errors = new MessageBag(['lab'=>['Lab yang sama tidak boleh dimasukan berulang']]);
return back()->withErrors($errors);
}
$this->validate($request, [
'lab.*.hasil' => 'required|numeric|digits_between:1,4',
]);
$lab_id = decode('lab','id',$request->lab);
$lab_hasil = decode('lab','hasil',$request->lab);
}
else {
$lab_id ="";
$lab_hasil ="";
}
// Decoding array input resep
if (isset($request->resep))
{
if (has_dupes(array_column($request->resep,'id'))){
$errors = new MessageBag(['resep'=>['resep yang sama tidak boleh dimasukan berulang']]);
return back()->withErrors($errors);
}
$this->validate($request, [
'resep.*.jumlah' => 'required|numeric|digits_between:1,3',
'resep.*.aturan' => 'required',
]);
$resep_id = decode('resep','id',$request->resep);
$resep_jumlah = decode('resep','jumlah',$request->resep);
$resep_dosis = decode('resep','aturan',$request->resep);
}
else {
$resep_id = "";
$resep_jumlah = "";
$resep_dosis = "";
}
$newresep = array();
$oldresep=array();
if (is_array($request) || is_object($newresep))
{
foreach ($request->resep as $resep){
$newresep[$resep['id']] = $resep['jumlah'];
}
}
if (empty($oldresep)) {
$resultanresep = resultan_resep($oldresep,$newresep);
}
else {$resultanresep=$newresep;}
$errors = validasi_stok($resultanresep);
if ($errors !== NULL) {
return back()->withErrors($errors);
}
foreach ($resultanresep as $key => $value) {
$perintah=kurangi_stok($key,$value);
if ($perintah === false) { $habis = array_push($habis,$key); }
}
DB::table('rm')->insert([
'idpasien' => $request->idpasien,
'ku' => $request->keluhan_utama,
'anamnesis' => $request->anamnesis,
'pxfisik' => $request->px_fisik,
'lab' => $lab_id,
'hasil' => $lab_hasil,
'diagnosis' => $request->diagnosis,
'resep' => $resep_id,
'jumlah' => $resep_jumlah,
'aturan' => $resep_dosis,
'dokter' => $request->dokter,
'created_time' => Carbon::now(),
'updated_time' => Carbon::now(),
]);
$ids= DB::table('rm')->latest('created_time')->first();
switch($request->simpan) {
case 'simpan_edit':
$buka=route('rm.edit',$ids->id);
$pesan='Data Rekam Medis berhasil disimpan!';
break;
case 'simpan_baru':
$buka=route('rm.tambah.id',$request->idpasien);;
$pesan='Data Rekam Medis berhasil disimpan!';
break;
}
return redirect('buka')->with('pesan',$pesan);
}`
Unfortunately i've modified return redirect('buka')->with('pesan',$pesan); but didn't work for me.
Please help
$pesan is defined in 2 cases of your switch statement.
So what happens when $request->simpan is neither equal to simpan_edit or simpan_baru ?
In this case (wich is not handled in your code), $pesan will be undefined and an error will throw.
A good practice using switch statements is to add a default: case wich will match any other values that you didn't explicitely set a case: for.
Example :
switch($request->simpan) {
case 'simpan_edit':
$buka=route('rm.edit',$ids->id);
$pesan='Data Rekam Medis berhasil disimpan!';
break;
case 'simpan_baru':
$buka=route('rm.tambah.id',$request->idpasien);;
$pesan='Data Rekam Medis berhasil disimpan!';
break;
default:
// you may set a default value for `$pesan` here
$pesan=null;
}
it seems that the error is related to the $pesan variable, according to the code you've provided, $pesan is not defined anywhere in the controller, which is why you're receiving the Error Exception Undefined variable : pesan error
for resolve this issue, you should either define the $pesan variable or remove any reference to it in the code
if $pesan is meant to store some message, it should be defined and assigned a value before being used

How to create a validation when importing CSV in Laravel using Maatwebsite?

How to create a validation when importing CSV. I'm using the "maatwebsite/excel": "^3.1" if the imported csv column header name is not exact with the database column it should display some validation. This is my reference LaravelDaily
/
Laravel-8-Import-CSV
Importing CSV
public function parseImport(CsvImportRequest $request)
{
if ($request->has('header')) {
$headings = (new HeadingRowImport)->toArray($request->file('csv_file'));
$data = Excel::toArray(new AwardeesImport, $request->file('csv_file'))[0];
} else {
$data = array_map('str_getcsv', file($request->file('csv_file')->getRealPath()));
}
if (count($data) > 0) {
$csv_data = array_slice($data, 0, 6);
$csv_data_file = CsvData::create([
'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
'csv_header' => $request->has('header'),
'csv_data' => json_encode($data)
]);
} else {
return redirect()->back();
}
return view('admin.import-csv.import-fields', [
'headings' => $headings ?? null,
'csv_data' => $csv_data,
'csv_data_file' => $csv_data_file
])->with('success', 'The CSV file imported successfully');;
}
When parsing CSV
public function processImport(Request $request)
{
$data = CsvData::find($request->csv_data_file_id);
$csv_data = json_decode($data->csv_data, true);
foreach ($csv_data as $row) {
$awardees = new SIS();
foreach (config('app.db_fields') as $index => $field) {
if ($data->csv_header) {
$awardees->$field = $row[$request->fields[$field]];
} else {
$awardees->$field = $row[$request->fields[$index]];
}
}
$awardees->save();
}
return redirect()->action([ImportController::class, 'index'])->with('success', 'Import finished.');
}
CsvImportRequest
public function rules()
{
return [
'csv_file' => 'required|mimes:csv,txt'
];
}
config/app.php
'db_fields' => [
'email_address',
'surname',
'first_name',
'middle_name',
'course',
'year_level',
'contact_number',
'gwa_1st',
'gwa_2nd',
'applying_for',
'remarks',
'comments'
]
if one of those field is missing it should show the validation error

When collection->map returnes array then data in Collection raise error

In laravel 6 app I have collection defined as :
class PermissionCollection extends ResourceCollection
{
public static $wrap = 'permissions';
public function toArray($request)
{
return $this->collection->transform(function($permission){
return [
'id' => $permission->id,
'name' => $permission->name,
'is_checked' => !empty($permission->is_checked) ? $permission->is_checked : null,
'guard_name' => $permission->guard_name,
'created_at' => $permission->created_at,
];
});
}
}
I use it in a control, like :
$permissions = $user->permissions->all();
$userPermissionLabels= Permission
::get()
->map(function ($item) use($permissions) {
$is_checked= false;
foreach( $permissions as $nextPermission ) {
if($nextPermission->permission_id === $item->id) {
$is_checked= true;
break;
}
}
return [ 'id'=> $item->id, 'name'=> $item->name, 'is_checked' => $is_checked];
})
->all();
return (new PermissionCollection($userPermissionLabels));
and I got error :
Trying to get property 'id' of non-object
Looks like the reason is that collection->map returnes array of data, not objects.
If there is a way to fix it without creating new collection(using array) ?
MODIFIED :
I logged loging in my collection,
public function toArray($request)
{
return $this->collection->transform(function($permission){
\Log::info(' PermissionCollection $permission');
\Log::info($permission);
return [
'id' => $permission->id,
'name' => $permission->name,
'is_checked' => !empty($permission->is_checked) ? $permission->is_checked : null,
'guard_name' => $permission->guard_name,
'created_at' => $permission->created_at,
];
});
}
and I see in logs:
PermissionCollection $permission
array (
'id' => 1,
'name' => 'App admin',
'is_checked' => false,
)
local.ERROR: Trying to get property 'id' of non-object
The value is valid array, not null.
I mean I have already use this collenction in other part of the app, can I use it without creating a new one...
I think you get this error because you CollectionResource need to object of the Permission model, but in your case it is trying to get id from an array, after map function. Try to extend your model instead of returning an new array

Verify duplicate values (multi column unique) on the array in Laravel5.7

relate as below issue
Verify duplicate values on the array in Laravel5.7
I am add two fields to data base.
// database/migrations/UpdateUsersTable.php
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('staff_no' , 10);
$table->string('staff_code');
$table->unique(['staff_no', 'staff_code']);
});
}
I want to verify if multi column unique in my database or post array value is duplicate or not?
Here is my codes :
this is my Controller
UsersController
public function MassStore(MassStoreUserRequest $request)
{
$inputs = $request->get('users');
//mass store process
User::massStore($inputs);
return redirect()->route('admin.users.index');
}
and this is my POST data (post data($inputs) will send like as below) :
'users' => [
[
'name' => 'Ken Tse',
'email' => 'ken#gamil.com',
'password' => 'ken12ken34ken',
'staff_no' => '20191201CT',
'staff_code' => 'IT-1azz',
],
[
'name' => 'Tom Yeung',
'email' => 'tom#gamil.com',
'password' => 'tom2222gt',
'staff_no' => '20191201CT', // staff_no + staff_code is duplicate, so need trigger error
'staff_code' => 'IT-1azz',
],
]
MassStoreUserRequest
public function rules()
{
return [
'users' => ['required','array'],
'users.*.name' => ['required'],
'users.*.email' => ['required','unique:users','email', 'distinct'],
'users.*.password' => ['required','string','min:8'],
'users.*.staff_no' => ['required','size:10'],
'users.*.staff_code' => ['required','string']
// how to set verify duplicate values(staff_no,staff_code unique) in here?
];
}
You can use distinct validation rule. So your code will look like-
public function rules()
{
return [
'users' => ['required','array'],
'users.*.name' => ['required'],
'users.*.email' => ['required','unique:users','email', 'distinct'],
'users.*.password' => ['required','string','min:8'],
'users.*.staff_no' => ['required','size:10'],
'users.*.staff_code' => ['required','string', 'distinct']
];
}
Change
`'users.*.staff_code' => ['required','string']` line to
'users.*.staff_code' => ['required','string', Rule::exists('staff')->where(function ($query) {
//condition to check if staff_code and staff_no combination is unique
return $query->where('staff_code', $request->('your_key')['staff_code'])->where('staff_no', $request->('your_key')['staff_no']) ? false : true; // You may need to make a loop if you can not specify key
}),]
I solve this problem myself.
https://laravel.com/api/5.7/Illuminate/Foundation/Http/FormRequest.html#method_validationData
main point is overrides method validationData(),make value "staff_no_code" to validation data.
Here is my codes :
MassStoreUserRequest
public function rules()
{
$validate_func = function($attribute, $value, $fail) {
$user = User::where(DB::raw("CONCAT(staff_no,staff_code )", '=', $value))
->first();
if (!empty($user->id)) {
$fail(trans('validation.alreadyExists'));
}
};
return [
'users' => ['required','array'],
'users.*.name' => ['required'],
'users.*.email' => ['required','unique:users','email', 'distinct'],
'users.*.password' => ['required','string','min:8'],
'users.*.staff_no' => ['required','size:10'],
'users.*.staff_code' => ['required','string']
// 'distinct' check when working with arrays, the field under validation must not have any duplicate values.
// $validate_func check DB exist
'users.*.staff_no_code' => ['distinct',$validate_func]
];
}
//make value "staff_no_code" to validation data
protected function validationData()
{
$inputs = $this->input();
$datas = [];
foreach ($inputs as $input ) {
$input['staff_no_code'] = $input['staff_no'] . $input['staff_code'];
$datas[] = $input;
}
return $datas;
}

Extend Laravel package

I've searched around and couldn't find a definitive answer for this...
I have a package DevDojo Chatter and would like to extend it using my application. I understand I'd have to override the functions so that a composer update doesn't overwrite my changes.
How do I go about doing this?
UPDATE
public function store(Request $request)
{
$request->request->add(['body_content' => strip_tags($request->body)]);
$validator = Validator::make($request->all(), [
'title' => 'required|min:5|max:255',
'body_content' => 'required|min:10',
'chatter_category_id' => 'required',
]);
Event::fire(new ChatterBeforeNewDiscussion($request, $validator));
if (function_exists('chatter_before_new_discussion')) {
chatter_before_new_discussion($request, $validator);
}
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
$user_id = Auth::user()->id;
if (config('chatter.security.limit_time_between_posts')) {
if ($this->notEnoughTimeBetweenDiscussion()) {
$minute_copy = (config('chatter.security.time_between_posts') == 1) ? ' minute' : ' minutes';
$chatter_alert = [
'chatter_alert_type' => 'danger',
'chatter_alert' => 'In order to prevent spam, please allow at least '.config('chatter.security.time_between_posts').$minute_copy.' in between submitting content.',
];
return redirect('/'.config('chatter.routes.home'))->with($chatter_alert)->withInput();
}
}
// *** Let's gaurantee that we always have a generic slug *** //
$slug = str_slug($request->title, '-');
$discussion_exists = Models::discussion()->where('slug', '=', $slug)->first();
$incrementer = 1;
$new_slug = $slug;
while (isset($discussion_exists->id)) {
$new_slug = $slug.'-'.$incrementer;
$discussion_exists = Models::discussion()->where('slug', '=', $new_slug)->first();
$incrementer += 1;
}
if ($slug != $new_slug) {
$slug = $new_slug;
}
$new_discussion = [
'title' => $request->title,
'chatter_category_id' => $request->chatter_category_id,
'user_id' => $user_id,
'slug' => $slug,
'color' => $request->color,
];
$category = Models::category()->find($request->chatter_category_id);
if (!isset($category->slug)) {
$category = Models::category()->first();
}
$discussion = Models::discussion()->create($new_discussion);
$new_post = [
'chatter_discussion_id' => $discussion->id,
'user_id' => $user_id,
'body' => $request->body,
];
if (config('chatter.editor') == 'simplemde'):
$new_post['markdown'] = 1;
endif;
// add the user to automatically be notified when new posts are submitted
$discussion->users()->attach($user_id);
$post = Models::post()->create($new_post);
if ($post->id) {
Event::fire(new ChatterAfterNewDiscussion($request));
if (function_exists('chatter_after_new_discussion')) {
chatter_after_new_discussion($request);
}
if($discussion->status === 1) {
$chatter_alert = [
'chatter_alert_type' => 'success',
'chatter_alert' => 'Successfully created a new '.config('chatter.titles.discussion').'.',
];
return redirect('/'.config('chatter.routes.home').'/'.config('chatter.routes.discussion').'/'.$category->slug.'/'.$slug)->with($chatter_alert);
} else {
$chatter_alert = [
'chatter_alert_type' => 'info',
'chatter_alert' => 'You post has been submitted for approval.',
];
return redirect()->back()->with($chatter_alert);
}
} else {
$chatter_alert = [
'chatter_alert_type' => 'danger',
'chatter_alert' => 'Whoops :( There seems to be a problem creating your '.config('chatter.titles.discussion').'.',
];
return redirect('/'.config('chatter.routes.home').'/'.config('chatter.routes.discussion').'/'.$category->slug.'/'.$slug)->with($chatter_alert);
}
}
There's a store function within the vendor package that i'd like to modify/override. I want to be able to modify some of the function or perhaps part of it if needed. Please someone point me in the right direction.
If you mean modify class implementation in your application you can change the way class is resolved:
app()->bind(PackageClass:class, YourCustomClass::class);
and now you can create this custom class like so:
class YourCustomClass extends PackageClass
{
public function packageClassYouWantToChange()
{
// here you can modify behavior
}
}
I would advise you to read more about binding.
Of course a lot depends on how class is created, if it is created using new operator you might need to change multiple classes but if it's injected it should be enough to change this single class.

Resources