-2

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?

yossi
  • 3,090
  • 7
  • 45
  • 65

1 Answers1

1

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
  • this is the current solution that i'm using.. i wonder if there are any others. thanks – yossi Jan 14 '23 at 21:52
  • 1
    @yossi - "*this is the current solution that i'm using*" - then why did you show something different in your question? Even your title says you are using only `web.php`. – Don't Panic Jan 14 '23 at 21:58
  • @Don'tPanic because i wrote the question several hours before it was posted. regardless, i'm not sure that this is a good practice. so the questions still stands.. – yossi Jan 14 '23 at 22:06
  • 1
    This really depends on the situation. You can optimize your code depend on your logic and tasks. Keep your code as simple as possible. My general approach to optimizing the performance of code is to keep things "flat." The more layers there are, the more expensive the function call will likely be. Layers (e.g. classes that depend on classes that depend on other classes) allow for powerful functionality in less code, but generally comes at the cost of performance. – Nuriddin Rashidov Jan 14 '23 at 22:16