Laravel 中控制器的正确使用

问题描述 投票:0回答:2

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

<!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 格式这可以吗?如果没有的话我该怎么办呢?

php laravel model-view-controller
2个回答
4
投票

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

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

web.php

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

你的Controller.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>

0
投票

在 Laravel 中,Controller 是 MVC(模型-视图-控制器)模式的核心组件,负责处理用户请求、编排逻辑并返回响应。要在 Laravel 中正确使用控制器,请遵循以下指南

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.