Search code examples
phplaravellaravel-routinglaravel-models

Includin many models in the routes `web.php` file practice


I have many routes, and for a single page (my homepage) I need to sample almost all of my models. I do it like that:

use App\Models\Aa;
use App\Models\Bb;
use App\Models\Cc;
// and so on ...

Route::get('/', function () {
    $data_for_view = [
        'aa' => Aa::where('show', true)->inRandomOrder()->limit(4)->get(),
        'bb' => Bb::where('published', true)->limit(4)->get(),
        'cc' => Cc::where('published', true)->limit(4)->get()
        // ... and so on
        // ...
    ];
    return view('welcome', $data_for_view);
});

However, this is the only route that uses so many models. so my questions is: is there a better way to achieve that goal?

is it a standard practice?


Solution

  • In the beginning you should use some controller for that and wrap your all logic inside method

    For example: in web.php route file add this:

    use App\Http\Controllers\SomeController;
    // SomeController
    Route::get('/', [SomeController::class, 'index']);
    

    In SomeController

    <?php  
    namespace App\Http\Controllers;
     
    use App\Models\Aa;
    use App\Models\Bb;
    use App\Models\Cc;
    
    class SomeController extends Controller
    {
       
        public function index()
        {
          $data_for_view = [
            'aa' => Aa::where('show', true)->inRandomOrder()->limit(4)->get(),
            'bb' => Bb::where('published', true)->limit(4)->get(),
            'cc' => Cc::where('published', true)->limit(4)->get()
            // ... and so on
            // ...
           ];
            return view('welcome',compact('data_for_view'));
        }
    }
    

    You can use artisan command for creating controller.

    php artisan make:controller SomeController