Copying data between tables - php

I need to copy records from DeCategories to Categories (about 1.7 million) along with "processing" (new slug etc).
Category use: https://packagist.org/packages/kalnoy/nestedset
The following script works fine, but works for many days. How to optimize / make it work faster? I am beginner in Laravel.
I have this models
class DeCategories extends Model
{
use ScopeActiveTrait;
protected $quarded = ['id'];
protected $fillable = ['category_name', 'description', 'keywords', 'content', 'enable', 'photo', 'order', 'slug', '_lft', '_rgt', 'parent_id'];
public $timestamps = true;
protected $table = 'cms_multikategorie22';
}
class Category extends Model
{
use ScopeActiveTrait;
use NodeTrait;
use Slugable;
public function setCategoryNameAttribute($value)
{
$this->attributes['category_name'] = $value;
$this->attributes['slug'] = $this->makeSlug($value);
}
protected $quarded = ['id'];
protected $fillable = ['category_name', 'description', 'keywords', 'content', 'enable', 'photo', 'order', 'slug', '_lft', '_rgt', 'parent_id'];
public $timestamps = false;
}
trait Slugable
{
protected function makeSlug($value)
{
$slug = str_slug($value);
$count = static::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();
return $count ? "{$slug}-{$count}" : $slug;
}
}
trait ScopeActiveTrait
{
public function scopeActive($query)
{
return $query->where('enable', 1);
}
}
And controller:
public function index()
{
echo 'Importuje <br/>';
//die();
$level1 = DeCategories::where('title', "<>", '')->where('parent_id', 325193)->get();
if (!$level1->isEmpty()) {
foreach ($level1 as $key1 => $value1) {
echo $value1->title . "<br/>";
////////
$slug = str_slug($value1->title);
$next = 1;
while (Category::where('slug', '=', $slug)->exists()) {
$next++;
$slug = str_slug($value1->title . '-' . $next);
}
////////
$category = new Category();
$category->category_name = $value1->title;
$category->description = $value1->title;
$category->keywords = $value1->title;
$category->content = $value1->id . '-1';
$category->enable = 1;
$category->photo = '';
$category->order = $value1->position;
$category->parent_id = 0;
$category->slug = $slug;
$category->save();
$id1 = $category->id;
$level2 = DeCategories::where('parent_id', $value1->id)->get();
//dump($level2);
if (!$level2->isEmpty()) {
foreach ($level2 as $key2 => $value2) {
////////
$slug2 = str_slug($value2->title);
$next2 = 1;
while (Category::where('slug', '=', $slug2)->exists()) {
$next2++;
$slug2 = str_slug($value2->title . '-' . $next2);
}
////////
$category2 = new Category();
$category2->category_name = $value2->title;
$category2->description = $value2->title;
$category2->keywords = $value2->title;
$category2->content = $value2->id . '-2';
$category2->enable = 1;
$category2->photo = '';
$category2->order = $value2->position;
$category2->parent_id = $id1;
$category2->slug = $slug2;
$category2->save();
$id2 = $category2->id;
$level3 = DeCategories::where('parent_id', $value2->id)->get();
if (!$level3->isEmpty() && $value2->id !="" && $value2->id != null) {
foreach ($level3 as $key3 => $value3) {
////////
$slug3 = str_slug($value3->title);
$next3 = 1;
while (Category::where('slug', '=', $slug3)->exists()) {
$next3++;
$slug3 = str_slug($value3->title . '-' . $next3);
}
////////
$category3 = new Category();
$category3->category_name = $value3->title;
$category3->description = $value3->title;
$category3->keywords = $value3->title;
$category3->content = $value3->id . '-3';
$category3->enable = 1;
$category3->photo = '';
$category3->order = $value3->position;
$category3->parent_id = $id2;
$category3->slug = $slug3;
$category3->save();
$id3 = $category3->id;
$level4 = DeCategories::where('parent_id', $value3->id)->get();
if (!$level4->isEmpty() && $value3->id !="" && $value3->id != null) {
foreach ($level4 as $key4 => $value4) {
////////
$slug4 = str_slug($value4->title);
$next4 = 1;
while (Category::where('slug', '=', $slug4)->exists()) {
$next4++;
$slug4 = str_slug($value4->title . '-' . $next4);
}
////////
$category4 = new Category();
$category4->category_name = $value4->title;
$category4->description = $value4->title;
$category4->keywords = $value4->title;
$category4->content = $value4->id . '-4';
$category4->enable = 1;
$category4->photo = '';
$category4->order = $value4->position;
$category4->parent_id = $id3;
$category4->slug = $slug4;
$category4->save();
$id4 = $category4->id;
$level5 = DeCategories::where('parent_id', $value4->id)->get();
if (!$level5->isEmpty() && $value4->id !="" && $value4->id != null) {
foreach ($level5 as $key5 => $value5) {
$slug5 = str_slug($value5->title);
$next5 = 1;
while (Category::where('slug', '=', $slug5)->exists()) {
$next5++;
$slug5 = str_slug($value5->title . '-' . $next5);
}
$category5 = new Category();
$category5->category_name = $value5->title;
$category5->description = $value5->title;
$category5->keywords = $value5->title;
$category5->content = $value5->id . '-5';
$category5->enable = 1;
$category5->photo = '';
$category5->order = $value5->position;
$category5->parent_id = $id4;
$category5->slug = $slug5;
$category5->save();
$id5 = $category5->id;
$level6 = DeCategories::where('parent_id', $value5->id)->get();
if (!$level6->isEmpty() && $value5->id !="" && $value5->id != null) {
foreach ($level6 as $key6 => $value6) {
$slug6 = str_slug($value6->title);
$next6 = 1;
while (Category::where('slug', '=', $slug6)->exists()) {
$next6++;
$slug6 = str_slug($value6->title . '-' . $next6);
}
$category6 = new Category();
$category6->category_name = $value6->title;
$category6->description = $value6->title;
$category6->keywords = $value6->title;
$category6->content = $value6->id . '-6';
$category6->enable = 1;
$category6->photo = '';
$category6->order = $value6->position;
$category6->parent_id = $id5;
$category6->slug = $slug6;
$category6->save();
$id6 = $category6->id;
$level7 = DeCategories::where('parent_id', $value6->id)->get();
if (!$level7->isEmpty() && $value6->id !="" && $value6->id != null) {
foreach ($level7 as $key7 => $value7) {
$slug7 = str_slug($value7->title);
$next7 = 1;
while (Category::where('slug', '=', $slug7)->exists()) {
$next7++;
$slug7 = str_slug($value7->title . '-' . $next7);
}
$category7 = new Category();
$category7->category_name = $value7->title;
$category7->description = $value7->title;
$category7->keywords = $value7->title;
$category7->content = $value7->id . '-7';
$category7->enable = 1;
$category7->photo = '';
$category7->order = $value7->position;
$category7->parent_id = $id6;
$category7->slug = $slug7;
$category7->save();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
echo 'finish';
}

For this quantity, IMO, you shouldn't use Models. They are heavy and this case it's taking huge time. Instead, use DB::table('x')->....
For dealing with the slug, I recommend the cviebrock/eloquent-sluggable. Give it a try ;)
You will see a tremendous reduce on execution time, just by doing that.

Related

PHP Error 500 Internal Server Error in Codeigniter 3 When large Transaction

I have a problem when execute large transaction in Codeigniter 3.
I create transaction for migrating old data like below:
// Controller
public function migrate_document_get()
{
$this->benchmark->mark('code_start');
$data = $this->Delivery_order_model->read_data_class_from_stock();
foreach ($data as $obj) {
$parameters = $this->Delivery_order_model->read_data_for_do($obj->class_no);
$this->Delivery_order_model->create_data($parameters);
}
$this->benchmark->mark('code_end');
$data['message'] = "Finish migrate document DO";
$data['execution_time'] = round($this->benchmark->elapsed_time('code_start', 'code_end')) . " seconds";
$this->response($data, REST_Controller::HTTP_OK);
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
When I execute method above in loop,
I facing an issue with error 500 internal server error.
but when I execute method like below one by one, not in the loop it's running normally.
// Controller
public function create_post()
{
$this->benchmark->mark('code_start');
$parameters = $this->post();
if (!empty($parameters)) {
$validate_param = $this->validate_parameter_create($parameters[0]);
if ($validate_param->run() == TRUE) {
$save = $this->Delivery_order_model->create_data($parameters);
if (!empty($save) and $save['total_affected'] > 0) {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_OK;
$output['error'] = false;
$output['message'] = "Success create delivery order list.";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_OK);
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_NOT_MODIFIED;
$output['error'] = true;
$output['error_detail'] = $save['error'];
$output['message'] = "Failed create delivery order list!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_NOT_MODIFIED);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['error_detail'] = $validate_param->error_array();
$output['message'] = "Required JSON Array! [{.....}]";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['message'] = "Required parameters!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
I already resizing on DB temp space
and I already check the method it's running normally
what's wrong with that, please give me some advice.

How to insert in to two tables from an online from?

Is it possible to insert in to two tables at once? I need to insert some data in to a table (students) and then based on the primary key insert in to another (enrollments). Is this possible?
The enrollments table however pulls other primary key from another table called schools (id).
public function add()
{
if(isset($_POST['submit'])) {
$this->student_validation();
if($this->form_validation->run() === TRUE) {
$data = $this->_get_posted_student_data();
$insert_id = $this->student->insert('students', $data);
if($insert_id) {
$this->__insert_enrollment($insert_id);
success($this->lang->line('insert_success'));
redirect('web/index/' . $data['front_school_id']);
} else {
error($this->lang->line('insert_failed'));
redirect('web/admission');
}
} else {
$this->data['post'] = $_POST;
}
}
$this->data['schools'] = $this->schools;
$this->data['add'] = TRUE;
$this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('student') . ' | ' . SMS);
$this->layout->view('web/index', $this->data);
}
private function __insert_enrollment($insert_id)
{
$data = array();
$school = $this->student->get_school_by_id($this->input->post('front_school_id'));
$data['student_id'] = $insert_id;
$data['school_id'] = $this->input->post('front_school_id');
//$data['class_id'] = $this->input->post('class_id');
//$data['section_id'] = $this->input->post('section_id');
$data['academic_year_id'] = $school->academic_year_id;
//$data['roll_no'] = $this->input->post('roll_no');
$data['created_at'] = date('Y-m-d H:i:s');
//$data['created_by'] = logged_in_user_id();
$data['status'] = 1;
$this->db->insert('enrollments', $data);
}
private function _get_posted_student_data()
{
$items = array();
$school_id = $this->session->userdata('front_school_id');
$items[] = 'first_name';
$items[] = 'middle_name';
$items[] = 'last_name';
$items[] = 'gender';
$items[] = 'religion';
$items[] = 'dobpin';
$items[] = 'address';
$items[] = 'immunization_update';
$items[] = 'nationality';
$items[] = 'valid_permit';
$items[] = 'relation_father';
$items[] = 'father_name';
$items[] = 'father_phone';
$items[] = 'father_email';
$items[] = 'father_address';
$items[] = 'relation_mother';
$items[] = 'mother_name';
$items[] = 'mother_phone';
$items[] = 'mother_email';
$items[] = 'mother_address';
$items[] = 'other_sibling';
$items[] = 'name_sibling';
$items[] = 'class_sibling';
$items[] = 'name';
$items[] = 'relation';
$items[] = 'child';
$items[] = 'application_name';
$data = elements($items, $_POST);
$data['dob'] = date('Y-m-d', strtotime($this->input->post('dob')));
$data['admission_date'] = date('Y-m-d', strtotime($this->input->post('admission_date')));
$data['age'] = floor((time() - strtotime($data['dob'])) / 31556926);
$data['modified_at'] = date('Y-m-d H:i:s');
//$data['modified_by'] = logged_in_user_id();
$data['created_at'] = date('Y-m-d H:i:s');
//$data['created_by'] = logged_in_user_id();
$data['status'] = 1;
// create user
//$data['user_id'] = $this->student->create_user();
if($_FILES['birth_certificate']['name']) {
$data['birth_certificate'] = $this->_upload_birth_certificate();
}
if($_FILES['bill']['name']) {
$data['bill'] = $this->_upload_bill();
}
if($_FILES['immunization']['name']) {
$data['immunization'] = $this->_upload_immunization();
}
if($_FILES['photo']['name']) {
$data['photo'] = $this->_upload_photo();
}
return $data;
}
You need $this->db->insert_id() to get last inserted id which will get from this.
$this->db->insert('students', $data);
$insert_id = $this->db->insert_id();
if(!empty($insert_id)) {
$this->__insert_enrollment($insert_id);
success($this->lang->line('insert_success'));
redirect('web/index/' . $data['front_school_id']);
} else {
error($this->lang->line('insert_failed'));
redirect('web/admission');
}

Laravel - Import excel keep looping

Dears,
i have an excel file with 5K rows and i'm importing it to my table in the DB successfully.
But the error, when the system finish all the rows, it keeps looping and the page doesn't stop running and not redirecting to my view.
My controller:
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
foreach ($data as $key => $row) {
$res = policies::where('phone', '=', $row['phone'])
->where('draft_no', '=', $row['draftno'])
->where('due_date', '=', $duedate)
->select('id')->get()->toArray();
if(empty($res)) {
$polic = new policies();
$polic->cust_id = $row['custno'];
$polic->policy = '';
$polic->bord_date = $borddate;
$polic->client_id = $row['clientid'];
$polic->client_no = $row['clientno'];
$polic->client_name = $row['clientname'];
$polic->draft_no = $row['draftno'];
if ($row['status'] == '') {
$polic->status = '';
} else {
$polic->status = $row['status'];
}
$polic->due_date = $duedate;
if ($row['curno'] == 'USD') {
$polic->currency = 1;
} else {
$polic->currency = 0;
}
$polic->amount = $row['amnt'];
$polic->zone = $row['zone'];
$polic->broker_id = $row['brokercode'];
$polic->broker_name = $row['brokername'];
$polic->remarks = $row['remarks'];
$polic->phone = $row['phone'];
$polic->insured_name = $row['insname'];
// $polic->cust_id = $row['valuedate'];
$polic->address = ''; //address
if (trim($row['status']) == 'P') {
$polic->paid_at = date('Y-m-d');
}
$polic->new = 1; //address
$polic->save();
}
else {
//am updating the imported date in the DB
}
what is very strange that in my localhost is working fine, but in digitaloceans cloud, keep looping without redirecting.
Thanks for your help.
I can be because you have 5000 rows to insert and 5000 insert operation consumes lots of memory. What you can try is batch insert operation.
In your policies.php make all fields fillable
protected $fillable=['cust_id ','policy','bord_date','client_id','client_no','client_name ','draft_no','bord_date','status','due_date','currency','amount','zone','broker_id','broker_name','remarks','phone','insured_name','address','paid_at','new'];
And on your excel file import use exists rather than getting collections.
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
$data=[];
$i=0;
foreach ($data as $key => $row) {
$res = policies::where('phone', '=', $row['phone'])
->where('draft_no', '=', $row['draftno'])
->where('due_date', '=', $duedate)
->exists();
if(!$res) {
$i++;
$data[$i]['cust_id ']=$row['custno'];
$data['policy'] = '';
$data['bord_date'] = $borddate;
$data[$i]['client_id'] = $row['clientid'];
$data[$i]['client_no'] = $row['clientno'];
$data[$i]['client_name'] = $row['clientname'];
$data[$i]['draft_no'] = $row['draftno'];
if ($row['status'] == '') {
$data[$i]['status'] = '';
} else {
$data[$i]['status'] = $row['status'];
}
$data[$i]['due_date'] = $duedate;
if ($row['curno'] == 'USD') {
$data[$i]['currency'] = 1;
} else {
$data[$i]['currency'] = 0;
}
$data[$i]['amount'] = $row['amnt'];
$data[$i]['zone'] = $row['zone'];
$data[$i]['broker_id'] = $row['brokercode'];
$data[$i]['broker_name'] = $row['brokername'];
$data[$i]['remarks'] = $row['remarks'];
$data[$i]['phone'] = $row['phone'];
$data[$i]['insured_name'] = $row['insname'];
// $data[$i]['cust_id'] = $row['valuedate'];
$data[$i]['address'] = ''; //address
if (trim($row['status']) == 'P') {
$data[$i]['paid_at'] = date('Y-m-d');
}
$data[$i]['new'] = 1; //address
}
else {
//am updating the imported date in the DB
}
}
policies::insert($data);

Create custom api to get filterable attribute for specific category in magento 2

I am creating api to get filterable attribute for specific category in magento 2.
We see in category page for layered navigation. I want to achieve exact same data in api.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$filterableAttributes = $objectManager->get(\Magento\Catalog\Model\Layer\Category\FilterableAttributeList::class);
$appState = $objectManager->get(\Magento\Framework\App\State::class);
$layerResolver = $objectManager->get(\Magento\Catalog\Model\Layer\Resolver::class);
$filterList = $objectManager->create(
\Magento\Catalog\Model\Layer\FilterList::class,
[
'filterableAttributes' => $filterableAttributes
]
);
$category_id = 41;
// $appState->setAreaCode('frontend');
$layer = $layerResolver->get();
$layer->setCurrentCategory($category_id);
$filters = $filterList->getFilters($layer);
$finalFilters = [];
$data = array();
$i = 0;
foreach ($filters as $filter) {
if ($filter->getItemsCount()) {
$name = $filter->getName();
foreach ($filter->getItems() as $item) {
if($item->getFilter()->getAttributeModel()->getAttributeCode() == 'price'){
$finalFilters[$name][$i]['name'] = $this->Helper->removeHTML($item->getLabel()->getArguments());
$finalFilters[$name][$i]['value'] = $item->getValue();
$finalFilters[$name][$i]['code'] = $item->getFilter()->getAttributeModel()->getAttributeCode();
}
else{
$finalFilters[$name][$i]['name'] = $item->getLabel();
$finalFilters[$name][$i]['value'] = $item->getValue();
$finalFilters[$name][$i]['code'] = $item->getFilter()->getAttributeModel()->getAttributeCode();
}
$i++;
}
}
}
But getting following error.
Exception #0 (Magento\Framework\Exception\LocalizedException): The attribute model is not defined.
It is becasuse the in filter there is category also so it dont have attribute model so use below function to achieve that
public function filters($categoryId)
{
$categoryLayer = $this->layerResolver->get()->setCurrentCategory($categoryId);
$category = $this->getCategory();
$filterList = new FilterList($this->objectManager, $this->fill);
$filterAttributes = $filterList->getFilters($categoryLayer);
$filterArray = [];
$i = 0;
foreach ($filterAttributes as $filter) {
$attributeLabel = (string) $filter->getName();
$attributeCode = (string) $filter->getRequestVar();
$items = $filter->getItems();
$filterValues = [];
$j = 0;
foreach ($items as $item) {
if ($attributeCode == 'cat') {
$filterValues[$j]['display'] = strip_tags($item->getLabel());
$filterValues[$j]['value'] = $item->getValue();
} elseif ($category->getIsAnchor()) {
if ($filter->getAttributeModel()
&& $filter->getAttributeModel()->getFrontendInput() == 'price') {
$filterValues[$j]['min_price'] = $filter->getLayer()->getProductCollection()->getMinPrice();
$filterValues[$j]['max_price'] = $filter->getLayer()->getProductCollection()->getMaxPrice();
break;
}
$filterValues[$j]['display'] = strip_tags($item->getLabel());
$filterValues[$j]['value'] = $item->getValue();
// Get Swatches.
$swatchesValues = $this->getSwatches($filter, $item, $j);
if (!empty($swatchesValues)) {
$filterValues[$j]['swatch_value'] = $swatchesValues['swatch_value'];
$filterValues[$j]['swatch_type'] = $swatchesValues['swatch_type'];
}
}
$j++;
}
if (!empty($filterValues)) {
$filterArray['available_filter'][$attributeCode]['label'] = $attributeLabel;
$filterArray['available_filter'][$attributeCode]['values'] = $filterValues;
}
$i++;
}
return [$filterArray];
}//end filters()
<?php
namespace Example\ExtendedApi\Model;
use Example\ExtendedApi\Api\FiltersInterface;
class FiltersManagement implements FiltersInterface
{
protected $_request;
protected $_filterableAttributeList;
protected $_layerResolver;
protected $_filterList;
protected $_storeManagerInterface;
protected $_response;
protected $_redirFactory;
public function __construct(
\Magento\CatalogGraphQl\Model\Resolver\Layer\FilterableAttributesListFactory $filterableAttributeList,
\Magento\Catalog\Model\Layer\FilterListFactory $filterList,
\Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
\Magento\Catalog\Model\Layer\Resolver $layerResolver,
\Magento\Framework\Webapi\Rest\Request $request
)
{
$this->_filterList = $filterList;
$this->_filterableAttributeList = $filterableAttributeList;
$this->_layerResolver = $layerResolver;
$this->_request = $request;
$this->_storeManagerInterface = $storeManagerInterface;
}
/**
* GET review by its ID
*
* #api
* #return array
* #throws \Magento\Framework\Exception\NoSuchEntityException
*
*/
public function getLayeredFilters()
{
$categoryId = $this->_request->getParam('categoryId');
$layer = $this->_layerResolver->get();
$layerType = "search";
if ($categoryId){
$layer->setCurrentCategory($categoryId);
$layerType = "category";
}
$filterArray['store_id'] = $this->_storeManagerInterface->getStore()->getId();
$filterableAttributesList = $this->_filterableAttributeList->create($layerType);
$filterList = $this->_filterList->create(['filterableAttributes' => $filterableAttributesList]);
$filters = $filterList->getFilters($layer);
$i = 0;
foreach($filters as $filter)
{
// Don't show options with no items
if (! $filter->getItemsCount()) {continue;}
$availablefilter = (string)$filter->getName();
$items = $filter->getItems();
$filterValues = array();
$j = 0;
foreach($items as $item)
{
$filterValues[$j]['display'] = strip_tags($item->getLabel());
$filterValues[$j]['value'] = $item->getValue();
$filterValues[$j]['count'] = $item->getCount(); //Gives no. of products in each filter options
$filterValues[$j]['url'] = $item->getUrl(); //Gives filter url.
$j++;
}
if(!empty($filterValues) && count($filterValues)>1)
{
$filterArray['availablefilter'][$availablefilter] = $filterValues;
}
$i++;
}
if (!isset($filterArray["availablefilter"])) {
$filterArray['availablefilter'] = "No filters to show.";
}
header("Content-Type: application/json; charset=utf-8");
$this->response = json_encode($filterArray);
print_r($this->response,false);
die();
}
}

how to more than one module in laravel using array and forloop

$module_name = array(
"Customerdetails",
"Customercomments",
"Complaints",
"Customerquotes",
"Systemconfiguration",
"regulatoryreports",
"Customermain",
"Customerdomestic"
);
for ($i = 0; $i < count($module_name); $i++) {
$row = DB::table('tb_module')->where('module_name', $module_name[$i])->get();
if (count($row) <= 0) {
return Redirect::to('/Grouplevel')
->with('message', SiteHelpers::alert('error', 'Can not find module'));
}
//print_r($row);
$row = $row[0];
$row_name[$i] = $row;
$module[$i] = $this->module;
$config = SiteHelpers::CF_decode_json($row->module_config);
$tasks = array(
'is_view' => 'View ',
'is_detail' => 'Detail',
'is_add' => 'Add ',
'is_edit' => 'Edit ',
'is_remove' => 'Remove ',
);
/* Update permission global / own access new ver 1.1
Adding new param is_global
End Update permission global / own access new ver 1.1
*/
if (isset($config['tasks'])) {
foreach ($config['tasks'] as $row) {
$tasks[$row['item']] = $row['title'];
}
}
$this->data['tasks'] = $tasks;
$this->data['groups'] = DB::table('tb_groups')->get();
$access = array();
foreach ($this->data['groups'] as $r) {
// $GA = $this->model->gAccessss($this->uri->rsegment(3),$row['group_id']);
$group = ($r->group_id != null ? "and group_id ='" . $r->group_id . "'" : "");
$GA = DB::select("SELECT * FROM tb_groups_access where module_id ='" . $row->module_id . "' $group");
if (count($GA) >= 1) {
$GA = $GA[0];
}
$access_data = (isset($GA->access_data) ? json_decode($GA->access_data, true) : array());
$rows = array();
//$access_data = json_decode($AD,true);
$rows[$i]['group_id'] = $r->group_id;
$rows[$i]['group_name'] = $r->name;
foreach ($tasks as $item => $val) {
$rows[$i][$item] = (isset($access_data[$item]) && $access_data[$item] == 1 ? 1 : 0);
}
$access[$r->name] = $rows[$i];
$id[$i] = $row->module_id;
}
}
for ($i = 0; $i < count($module_name); $i++) {
$this->data['row'] = $row_name[$i];
$this->data['module'] = $module[$i];
$this->data['module_name'] = $row_name[$i]->module_name;
$this->data['access'] = $access;
$this->data['groups_access'] = DB::select("select * from tb_groups_access where module_id ='" . $id[$i] . "'");
$this->layout->nest('content', 'Grouplevel.index', $this->data)
->with('menus', SiteHelpers::menus());
}

Categories