0

I used many functions from class to be used in a controller and this is a normal way to prevent duplicate of the code, but I have a function that store distance in a model and use collection for pagination, this function works fine and return $stores variable in the controller to be used for pagination, now I need to put it in a class and call it from the controller, unfortunately it returns null value!!! how can I fix this issue? the same function in the controller works fine but if i put it in a class and called from controller will return null, please help me

enter image description here

Class:

public function getStoresDistance($allstores)
{
    $stores = collect([]);
    foreach (session('storeinfo') as $storeInfo) {
        $store = $allstores->find($storeInfo['id']);
        if ($store) {
            $store->distance = $storeInfo['distance'];
            $stores[] = $store;
            if (!Collection::hasMacro('paginate')) {
                Collection::macro('paginate', function ($perPage = 25, $page = null, $options = []) {
                    $options['path'] = $options['path'] ?? request()->path();
                    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);

                    return new LengthAwarePaginator(
                        $this->forPage($page, $perPage)->values(),
                        $this->count(),
                        $perPage,
                        $page,
                        $options
                    );
                });
            }
        }
    }
}

call from controller:

$allstores = Storeinfo::where('show', 'y')->get();
$findstores = Helper::getStoresDistance($allstores);

1 Answer 1

2

If the function is common for multiple controllers, move it to a PHP trait. Traits are specifically designed for reusability purpose. You can then use that trait in your controller and call its function as you would your controller functions like so $this->yourFunction(). Below is how your code will look:

Trait:

trait StoresDistance
{
    public function storesDistance(){}
}

Controller:

class YourController extends Controller
{
    use StoresDistance;

    public function getStoresDistance($allstores)
    {
         // some code
         $this->storesDistance();
         // some code
    }
}

Reference Docs: https://www.php.net/manual/en/language.oop5.traits.php

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.