Nikhil Agrawal
Nikhil Agrawal

Reputation: 285

Defining methods which can be used in multiple controllers (in short library) in laravel 5

I want to define some methods which can be used in multiple place or multiple controllers. Basically these methods will be like libraries which will perform multiple queries.

My main aim is to avoid writing common logic multiple times by creating some libraries.

Please help me with it.

Thanks in advance :)

Upvotes: 5

Views: 1882

Answers (4)

Laravel User
Laravel User

Reputation: 1129

Use helper classes and create common functions in them.

Create a folder named helper in app folder and create a helper class in it. And then use that helper class's function in multiple controller or views as you want.

Upvotes: 0

scrubmx
scrubmx

Reputation: 2556

Depends what are you trying to do. Here are some options:

By default all your controllers extend App\Http\Controllers\Controller class. Just put all the shared logic between controllers there.

For complex queries to the database you can create a Repository and and inject in the controllers.

class UserRepository {
    public function getActiveUsers() {
        return Users::with('role')
            ->where('...')
            ->someQueryScopes()
            ->anotherQueryScope()
            ->yetAnotherScope();
    }
}

class SomeController extends Controller {
    public function index(UserRepository $repository) {
        $users = $repository->getActiveUsers();
        return view('users.index')->withUsers($users);
    }
}

Yet another option is to create a Service classes for business logic and inject them in the constructor or relevant methods

 class UserCreatorService {
    public function create($email, $password){
        $user = User::create(['email' => $email, 'password' => $password]);
        $user->addRole('Subscriber');
        Event::fire(new UserWasCreated($user));
        return $user;
    }
}

class RegisterController extends Controller {
    public function store(Request $request, UserCreatorService $service) {
        $user = $service->create($request->input('email'), $request->input('password'));
        return view('home')->withUser($user);
    }
}

Upvotes: 6

Calin Blaga
Calin Blaga

Reputation: 1373

You can make a folder named lib and inside that a functions.php file and in composer.json

...
"autoload": {
    "files": [
      "app/lib/functions.php"
    ],
...

and run composer dump-autoload

Upvotes: 0

martiendt
martiendt

Reputation: 2216

it's simple, build your own library in your app folder then create new file MyLibrary.php

namespace App;

Class MyLibrary {

    public static function sum($a, $b) {
        return $a + $b;
    }

}

then create alias in your config/app.php

'MyLibrary'      => App\MyLibrary::class,

and finally you can call it in anywhere your controller

$result = MyLibrary::sum(4, 5); // your $result now have value of 9

Upvotes: 2

Related Questions