Akari Oozora
Akari Oozora

Reputation: 368

Proper usage of the Controller in Laravel

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?

Upvotes: 0

Views: 697

Answers (2)

Durgesh Codebergit
Durgesh Codebergit

Reputation: 1

In Laravel, the Controller is a central component of the MVC (Model-View-Controller) pattern, responsible for handling user requests, orchestrating logic, and returning responses. To properly use a Controller in Laravel, follow these guidelines

Upvotes: -3

Maik Lowrey
Maik Lowrey

Reputation: 17566

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>

Upvotes: 4

Related Questions