Home > Net >  How to knowing that view is linked with controller in PHP Laravel
How to knowing that view is linked with controller in PHP Laravel

Time:03-15

I beginner in PHP and I sill struggling to understand about controller, view and rout. I do so many thing to showing my code in view.

I write this to connect the function index in file ChargeController

 Route::get('/', 'app\http\controllers\ChargeController@index');

So, how can I knowing that code was integration as MVC in PHP? thank's

CodePudding user response:

So basically how it works is when you navigate to http or https://yourhost.com (with no path, the default path will be /), your application will try to check if the path / is registered. By defining the code on your question, it is registered and Laravel will run whatever method that linked to that path. In this case, it will run your index method on ChargeController class. Inside that index method, you may be needing some data, which you can access using Models class that Laravel provides. After getting those data, you also need to register which view to show with the data inside that index method. If you registered your view and design it correctly, the path / will show the view along with your provided data.

Inside MVC, all of the view's logic, animation, etc. is also coded inside the view file, which makes it different from other design patterns. For ex. there's a MVVM design pattern (Model-View-ViewModel), this pattern separates the view's logic and put it inside the ViewModel file. (see MVVM for more information)

CodePudding user response:

Laravel follows MVC design pattern (Model-View-Controller).

  • Model interacts with database (Laravel's ORM is Eloquent)
  • View is responsible for rendering.
  • Controller handles the user input (form inputs, data, validation etc.)

In the web, we have web sites and their urls. You visit a site and move inside a site with urls. Laravel has own Router which maps urls to a controller's action (in your case / maps to ChargeController's index method)

Your request goes into controller's method then you validate user's request if needed. After that you have validated user inputs (string, array, file etc.) with these inputs you may some database queries that handles by Laravel Models.

Controller give/get all information via Models. Then pass these information/data to view.

Laravel has Blade templating engine. It has directives to help you to use PHP inside HTML. Blade view names ends with blade.php (for your example it is resources/views/charge/index.blade.php) from there your controller returns view with givin data from laravel model to your controller.

In some cases, you don't use Laravel's Blade, and directly returns JSON response from your controller to be consumed by your frontend (VueJS, React, Flutter etc.)

  • Related