php - Laravel: calling the View on the Routes vs Controller

  • I want to know what are the differences between using Routes and Controller? Is there a major difference in Laravel's system, or is it just a matter of logic?
  • Is there a difference between calling the View on the Routes and the View on the Controller?
  • Does the Controller automatically cache the View and Routes does not? Because I read somewhere that if we call the View in the Controller, it will be cached, but if we call the View in the Routes, it is not so we have to cache the View manually in the Routes. Is this true?

Answer

Solution:

I want to know what are the differences between using Routes and Controller? Is there a major difference in Laravel's system, or is it just a matter of logic?

Routes are where you declare your application urls, Controller contain the code that represents the logic of your application.

You can put code in the callback parameter of the route declaration

Route::get('/user', function () {
    $user = User::where('active', '=', 1)
        ->where('parent_user_id', '=', Auth::id())
        ->paginate(10);
    return view('users', ['users' => $user]);
});

but it will get messy very quicly, so it's better to declare a route related to a controller class

Route::get('/user', [UserController::class, 'index']);

Is there a difference between calling the View on the Routes and the View on the Controller?Does the Controller automatically cache the View and Routes does not?Because I read somewhere that if we call the View in the Controller, it will be cached, but if we call the View in the Routes, it is not so we have to cache the View manually in the Routes. Is this true?

No difference , both dont cache unless it's related to a third party caching package.

Answer

Solution:

Does the Controller automatically cache the View and Routes does not? Because I read somewhere that if we call the View in the Controller, it will be cached, but if we call the View in the Routes, it is not so we have to cache the View manually in the Routes. Is this true?

Views and Routes are automatically cached by Laravel.

View cache exists at: storage/framework/views

If you want to manage cache of Views:

php artisan view:clear
php artisan view:cache

Route cache exists at: bootstrap/cache/routes.php

If you want to manage cache of Routes:

php artisan route:clear
php artisan route:cache

Source