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 :)
$varbl = App::make("ControllerName")->FunctionName($params); to call a controller function from a my balde template(view page).
A Controller is that which controls the behavior of a request. It handles the requests coming from the Routes. In Laravel, a controller is in the 'app/Http/Controllers' directory. All the controllers, that are to be created, should be in this directory.
Laravel applications follow the traditional Model-View-Controller design pattern, where you use: Controllers to handle user requests and retrieve data, by leveraging Models. Models to interact with your database and retrieve your objects' information. Views to render pages.
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);
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With