Detailed explanation of laravel framework routing and MVC examples

Time:2021-9-25

This paper describes the example of laravel framework routing and MVC. Share with you for your reference, as follows:

1. Routing

The function of routing is to forward different URL requests of users to corresponding programs for processing. The routing of laravel is defined in the routes folder. By default, four routing files are provided, of which the web.php file defines the basic page request.

1.1 basic routing

The most basic routing requests are get and post requests. Laravel defines different request methods through the route object. For example, define a get request with URL ‘req’ and return the string ‘get response’:


Route::get('req',function (){
  return 'get response';
});

When I request by gethttp://localhost/Laravel/laravel52/public/reqWhen, it returns as follows:

Similarly, when defining a post request, useRoute::post(url,function(){});

1.2 multi request routing

If you want to process multiple requests in the same way, you can use match or any:

Match is used to match the corresponding request method. For example, when req2 is requested by get or post, match response is returned:


Route::match(['get','post'],'req2',function (){
  return 'match response';
});

Any will match any request method, for example, req3 will be requested in any way, and any response will be returned:


Route::any('req3',function (){
  return 'any response';
});

1.3 request parameters

Required parameters: when the request is sent in the form of parameters, it can be received in the route. The parameters are enclosed in braces and divided by / for example:


Route::get('req4/{name}/{age}', function ($name, $age) {
  return "I'm {$name},{$age} years old.";
});

Pass the parameters when requesting with get, and the results are as follows:

Optional parameters: the above parameters are required. If a parameter is missing, an error will be reported. If you want a parameter to be optional, you can add a?, And set the default value. The default parameter must be the last parameter, otherwise it cannot be recognized in the middle:


Route::get('req4/{name}/{age?}', function ($name, $age=0) {
  return "I'm {$name},{$age} years old.";
});

Regular verification: the parameters in the request can be verified through where


Route::get('req4/{name}/{age?}', function ($name, $age=0) {
  return "I'm {$name},{$age} years old.";
})->where(['name'=>'[A-Za-z]+','age'=>'[0-9]+']);

1.4 routing group

Sometimes our route may have multiple levels. For example, we define the primary route home, and there are secondary routes article and comment under it. Therefore, we need to put article and comment in the home group. Add the prefix home to the routing article through the array key prefix:


Route::group(['prefix' => 'home'], function () {
  Route::get('article', function () {
    return 'home/article';
  });
});

In this way, the route can be accessed through home / article.

1.5 route naming

Sometimes you need to give a name to the route. You need to use the as array key to specify the route name when defining the route. For example, if you name the route home / comment comment comment, you can use the route name comment when generating URL and redirection:

Route::get('home/comment',['as'=>'comment',function(){
  return route('comment');    // Generate the URL corresponding to the comment through the route function
}]);

Output ashttp://localhost/Laravel/laravel52/public/home/comment

2. Controller

Route route only allocates and jumps requests, and the specific business logic needs to be processed by the controller. The controller is generally encapsulated into a PHP class. The controller files are generally placed in the app / HTTP / controllers folder. For example, create a new logincontroller class, inherit from the controller, and define the checklog method to respond to the login request,

namespace App\Http\Controllers;
class LoginController extends Controller
{
  public function checkLog($name){
    Return $name. 'login succeeded';
  }
}

Assign the login request to the checklog method in route.php:


Route::get('login/{name}','[email protected]');

Similarly, you can name the controller route, such as login:


Route::get('login/{name}',['uses'=>'[email protected]','as'=>'login']);

3. View

The controller is responsible for processing the logic of the application, and the view is responsible for the display of the application, which reflects the separation between different logic in MVC. Views are generally located in the / resource / views directory. Generally, a controller file corresponds to a view folder. Therefore, the view I created is: views / login / login.blade.php. Blade file is a template engine of laravel, which is compiled into PHP and stored. It contains HTML language, in which you can directly use PHP, such as login.blade.php:

<!DOCTYPE Html>
<html>
  <head>
    < title > login interface < / Title >
  </head>
  <body>
    {{$name}} login succeeded
  </body>
</html>

In controller’s checkLog method, the view is called and the parameters are passed in:


public function checkLog($name){
  return View('Login/login',[
    "name"=>$name
  ]);
}

4. Template

In MVC, models interact with tables in the database, and each database corresponds to a model template. Laravel does not define the models directory. Generally, you can create a new models folder under the app directory to store template files. For example, define a student template and specify the table name and primary key:


namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
  protected $table='student';
  protected $primaryKey='id';
}

Query all through the student template in the controller:


namespace App\Http\Controllers;
use App\Models\Student;
class Login
{
  public static function showDB(){
    $table=Student::all();
    dd($table);
  }
}

For more information about laravel, readers who are interested can see the special topics on this site: introduction and advanced tutorial of laravel framework, summary of PHP excellent development framework, introduction to PHP object-oriented programming, introduction to PHP + MySQL database operation, and summary of common database operation skills for PHP

I hope this article will be helpful to your PHP Programming Based on laravel framework.