I'm building an application using Laravel. Where I had to run a Query in different pages. So same Query i had to run in several controller. But i think this is not a good practice of coding ..Where can i write a single and execute it form several controller instead of writing it in again again? I know laravel eloquent and eager loading also. if i have a large query suppose joining two three tables how do i implement that?
Thank in advance.
You need create a new php-file in folder Helpers (app/Helpers) and put new class there. I use Main for example.
namespace App\Helpers;
class Main
{
static public function getSomething($id) {
// ... DO something
return var;
}
}
Next you need add to config/app.php
'aliases' => [
...
'Main' => App\Helpers\Main::class
]
After that you can use from anywhere of your project
Main::getSomething($id);
with 'use App\Helpers\Main;' of course
This allows you to use this function in all controllers and not to repeat it every time.
You can use Sharing Data With All Views.
You can do so by sharing the data through the view Facade. With this every view will have access to the data. No need to query data from multiple controllers.
in you AppServiceProvider class > boot method
// write query
$query = User::all();
// Share data
View::share("user", $query);
Don't forget to use Illuminate\Support\Facades\View at the top of the class
You can also use View Composer to achieve similar scenario.