I have a page where I want to list some countries and states I have in my database, each one has their own controllers. I'd like to know if this is the proper way to do it:
<!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>
The controllers are perfoming SQL queries and returning them as arrays, such as:
public static function getStates() {
$states= DB::table('states')->get();
return $states;
}
Since I'm not using view
and not setting up at any routes to do this, is this ok according to the MVC format? If not, how could I make it?
CodePudding user response:
Your approach is not wrong but not correct in the context of an MVC.
The workflow would be Route -> Controller -> View.
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>