在 Laravel 中正确使用控制器

Proper usage of the Controller in Laravel

我有一个页面,我想在其中列出数据库中的一些国家和州,每个国家和州都有自己的控制器。我想知道这样做是否正确:

<!DOCTYPE html>
<html>
    <head>  </head>
    <body>
        <?php $states = App\Http\Controllers\StatesController::getStates(); ?>
        @foreach($states as $state)
            <p>{{$state->name}}</p>
        @endforeach

        <?php $countries= App\Http\Controllers\CountriesController::getCountries(); ?>
        @foreach($countries as $country)
            <p>{{$country->name}}</p>
        @endforeach
    </body>
</html>

控制器正在执行 SQL 查询并将它们作为数组返回,例如:

 public static function getStates() {
        $states= DB::table('states')->get();

        return $states;
    }

因为我没有使用 view 并且没有在任何路由上设置来执行此操作,根据 MVC 格式,这样可以吗?不然怎么办?

您的方法没有错,但在 MVC 上下文中不正确。

工作流程是路由 -> 控制器 -> 视图。

web.php

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

YourController.php

public function index() {
    return view('index', [
       // 'states' => DB::table('states')->get(),
       'states' => \App\Models\States::all(),
       'countries' => \App\Models\Countries::all(),
     ]);
}

index.blade.php

<!DOCTYPE html>
<html>
    <head>  </head>
    <body>
        @foreach($states as $state)
            <p>{{$state->name}}</p>
        @endforeach

        @foreach($countries as $country)
            <p>{{$country->name}}</p>
        @endforeach
    </body>
</html>