我有一個頁面,我想在其中列出我資料庫中的一些國家和州,每個國家和州都有自己的控制器。我想知道這是否是正確的方法:
<!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 格式可以嗎?如果沒有,我怎么能做到?
uj5u.com熱心網友回復:
在 MVC 的背景關系中,您的方法沒有錯,但不正確。
作業流程是路線 -> 控制器 -> 視圖。
網頁.php
Route::get('/', [App\Http\Controllers\YourController::class, 'index']);
你的控制器.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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/481431.html
