Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

loced35156's avatar

How to create reusable function

I have a table where i add some custom style. Until now it was hard coded, but now i am switching to reusable component. So i have created a reurable table

export default {
	data() {
smallTable: {smTable: "", active: false},
                borderTable: {bTable: "", active: false},
                borderlessTable: {b0Table: "", active: false},
                hoverableTable: {hoverTable: "table-hover", active: true},
                b0disabled: false,
                bdisabled: false,
}    

    props: [
        'smallTable',
        'borderTable',
        'borderlessTable',
        'hoverableTable',
    ],
    
    template: `
        <div class="py-4 table-responsive table-wrapper shadow-sm">
            <!-- Table Header ./ -->
            <div class="table-extra d-flex justify-content-between">
                <div class="form-group d-flex">
                    <slot name="tableHeaderViewPerRecord" />
                </div>
                <div class="">
                    <slot name="tableHeaderReloadBtn" />
                </div>
            </div>
            <!-- ./ Table Header -->
            <table class="table align-middle mb-0" :class="[smallTable.smTable, borderTable.btable, hoverableTable.hoverTable, borderlessTable.b0Table]">
                <thead class="">
                    <tr>
                        <slot name="tableFields" />
                    </tr>
                </thead>
                <!-- Collapsed content ./ -->
                <thead class="collapse" id="collapseFilter">
                    <tr>
                        <slot name="tableFilterCollapse" />
                    </tr>
                </thead>
                <!-- ./ Collapse contet -->
                <tbody>
                    <slot name="tableBody" />
                </tbody>
            </table>
            <!-- Table Footer ./ -->
            <div class="table-extra-pagination d-flex justify-content-between py-4">
                <slot name="tableFooter" />
            </div>
            <!-- ./ Table Footer -->
        </div>
    `
}

on parent componenent i use this table and add some custom style based on option what i chose there

button component

<table-custom-action role="add-job-module"
                @tableStyles="tableStyles"
                :borderlessTable="borderlessTable"
                :hoverableTable="hoverableTable"
                :borderTable="borderTable"
                :b0disabled="b0disabled"
                :smallTable="smallTable"
                :bdisabled="bdisabled"
            ></table-custom-action>

on parent component

tableStyles() {
                if (this.smallTable.active) {
                    this.smallTable.smTable = "table-sm"
                }else {
                    this.smallTable.smTable = ""
                }

This works perfectly but for example if i have a place where i need to use this table JobComponent and a place like UserComponent both will have same table with different data and if i use this logic the table will work also the custom style i want to add or remove. But i am looking for a solution where i can maybe export this function on another js file or component i dont know and to call on the component i need to use this table. How can i do that?

0 likes
4 replies
Nihir's avatar

Hi I believe in the shortcode and reusable I'm not an expert, but I used to consider that whenever I used that case, I tried to understand the project's code and flow. After this, I wrote the code. Here is an example: I have to create the complete module of Roles and permissions. Either I create multiple controllers and routes and blades for that or use the same controller, Route and functions, modify it, create a separate rule, and put it in the request. While the request was sent, they called the law, and after the validation check for the recommendation, the name role_name or permission_name with the request.

That's it. You have to find a way to compress and beautify with reusable code.

loced35156's avatar

@Nihir I understand the logic. But i am beginer too in vue, so i dont know how to use this on practice

Nihir's avatar

Here I wrote demo code for a knowledge base on reusable code. just understand the code flow:

This code is used for the multiple search and multiple search action and based on users role.

public function ajaxadvancesearch(Request $request)
    {
        $application_date = Application::select(\DB::raw("(DATE_FORMAT(created_at, '%y-%m-%d')) as my_date"))->where('is_deleted', 0)->orderBy('my_date', 'desc')->groupBy(\DB::raw("DATE_FORMAT(created_at, '%y-%m-%d')"));
        if (auth()->user()->hasRole('agent')) {
            $application_date->where('agent_id', auth()->user()->id);
        } else {
            $application_date->get();
        }
        $application_date=$application_date->get()->toArray();
        $attributes=$request->input();
        unset($attributes['_token']);
        $date_search = [];
        if ($attributes['idle_date_frome'] && $attributes['idle_date']) {
            $date_search[]=$attributes['idle_date'];
            $date_search[] =$attributes['idle_date_frome'] ;
            unset($attributes['idle_date_frome']);
            unset($attributes['idle_date']);
        }
        $app_date = [];
        $is_followup =  $request->is_followup;
        foreach ($application_date as $key=>$val) {
            if ($request->is_followup) {
                $query=Application::with('educations')->with('latestnotes')->where('is_deleted', 0)->where('is_followup',  $is_followup)->where(\DB::raw("(DATE_FORMAT(created_at,'%y-%m-%d'))"), "=", $val['my_date'])->orderBy('created_at', 'desc')->where('step2', 1);
            } else {
                $query=Application::with('educations')->with('latestnotes')->where(\DB::raw("(DATE_FORMAT(created_at,'%y-%m-%d'))"), "=", $val['my_date'])->where('is_deleted', 0)->orderBy('created_at', 'desc')->where('step2', 1);
            }
            if (auth()->user()->hasRole('agent')) {
                $query->where('agent_id', auth()->user()->id);
            }
            $query->where(function ($query) use ($attributes) {
                foreach ($attributes as $attrikey=>$attrival) {
                    if (!empty($attrival)) {
                        $query->where($attrikey, $attrival);
                    }
                }
            });
            if (!empty($date_search)) {
                $query->whereBetween('idle_date', $date_search);
            }
            $result=  $query->get();

            if (!$result->isEmpty() /* !empty($result) */) {
                $app_date[] = $val;
                $data[$val['my_date']] = $result;
            }
        }

        $fileds=ManageFiled::get()->toArray();
        $type = 'tracking_status';
        $trackingstatusArray = \Arr::where($fileds, function ($value, $key) use ($type) {
            return $value['type'] == $type;
        });

        $stage = 'tracking_stage';
        $trackingstageArray = \Arr::where($fileds, function ($value, $key) use ($stage) {
            return $value['type'] == $stage;
        });

        $degree_status="degree_status";
        $degree_statusArray = \Arr::where($fileds, function ($value, $key) use ($degree_status) {
            return $value['type'] == $degree_status;
        });
        $degree_background_status="background_status";
        $degree_background_statusArray= \Arr::where($fileds, function ($value, $key) use ($degree_background_status) {
            return $value['type'] == $degree_background_status;
        });

        $passport_status="passport_status";
        $passport_statusArray= \Arr::where($fileds, function ($value, $key) use ($passport_status) {
            return $value['type'] == $passport_status;
        });


        $placement="placement";
        $placementArray= \Arr::where($fileds, function ($value, $key) use ($placement) {
            return $value['type'] == $placement;
        });
        $col = VisibleColoum::get()->toArray();
        foreach ($col as $val) {
            if ($val['value'] == 0) {
                if ($val['name'] == 'Tracking') {
                    $response['trackingstatusArray'] = $trackingstatusArray;
                    $response['trackingstageArray'] = $trackingstageArray;
                }
                if ($val['name'] == 'Documents') {
                    $response['degree_statusArray'] = $degree_statusArray;
                    $response['degree_background_statusArray'] = $degree_background_statusArray;
                    $response['passport_statusArray'] = $passport_statusArray;
                }
                if ($val['name'] == 'Notes') {
                    $response['notes']=1;
                }
                if ($val['name'] == 'Placement') {
                    $response['placementArray'] = $placementArray;
                }
                if ($val['name'] == 'Visa') {
                    $response['visa'] = 1;
                }
                if ($val['name'] == 'Arrival') {
                    $response['arrival'] = 1;
                }
                if ($val['name'] == 'Other') {
                    $response['other'] = 1;
                }
                if ($val['name'] == 'Invoicing') {
                    $response['invoicing'] = 1;
                }
                if ($val['name'] == 'Agent') {
                    $response['agent_array'] = 1;
                }
                if ($val['name'] == 'Preferences') {
                    $response['preferences'] = 1;
                }
                if ($val['name'] == 'Education') {
                    $response['education'] = 1;
                }
                if ($val['name'] == 'Offers') {
                    $response['offers'] = 1;
                }
            }
        }
        $response['nationality']=['American','Canadian','British','Irish','Australian','New Zealander','South African','Other Nationality'];

        if ($app_date) {
            $response['application_date'] = $app_date;
        } else {
            $response['application_date']= [];
        }
        if (isset($data)) {
            $response['application'] = $data;
        } else {
            $response['application']="";
        }

        $response['redirect']='allapplication';
        $response['col'] = $col;
        $response['resume']='resume';
        $response['cantassign']=0;
        $response['fullurl']=url()->full();

        //return response()->json(['success'=> view('advancesearchajax',$response)]);

        $html = view('advancesearchajax', $response)->render();

        return response()->json([
            'status' => true,
            'html' => $html,
            'message' => 'Coupon code applied successfully.',
        ]);
    }

You have to implement on it or you can create a short demo of crud operation and try to implement logic in the main code.

Note:This code follow the regular laravel logic.

Please or to participate in this conversation.