Detailed explanation of form operation of laravel framework learning record


This paper describes the form operation of learning records in laravel framework. Share with you for your reference, as follows:

1. MVC data flow

The most basic thing to get a laravel project is to find out how its page request and data flow are carried out. For example, when requesting the index page through get, how to display the following student information list:

First, when a page request arrives, you need to define the routing request and the corresponding processing method in routes / web.php:

Route::get('index','[email protected]');

Then set up the database connection under the. Env file, create a new database model student and put it in the app / directory, where you specify the corresponding data table as student

class Student extends Model
  protected $table='student';       // Specify database
  protected $fillable=['name','age','sex'];  // Fields allowed to be modified

The new control class StudentController is implemented and the getIndex method is implemented. The student/index.blade.php page is invoked in the getIndex method, and the student information is transmitted to view through the Student model.

public static function getIndex(){
  return view('student.index',['students'=>Student::paginate(5)]);

Implement the page view, and create a new student folder under the resources / views folder to store student related pages.

Use the idea of template to realize the index page: create a new page template file layout.blade.php, keep the public part, and replace the different parts with @ section or @ yield. New index.blade.php inherits the public part of the layout template and implements the customized part of the index page

  <!--  Index page custom content -- >
    In the user-defined content, the student data information is cyclically displayed to the list through @ foreach
@foreach($students as $student)
    <th scope="row">{{$student->id}}</th>

In this way, when the user requests the index page through get, the student data will be taken out of the database and displayed in the page.

2. Introducing page resource files into blade

Although the view file is placed in the resources / views directory, the blade file will be located in the public directory after compilation, so the directory is relative to public. The static resources required by the page should be placed in the public directory and introduced relative to the public path through the asset function.

By default, laravel provides bootstrap and jQuery, which correspond to public / CSS / app.css and public / JS / app.js files respectively. You can import them if necessary.

<!--  Bootstrap CSS file -- >
<link rel="stylesheet" href="{{ asset('./css/app.css')}}" rel="external nofollow" >
<!--  JQuery file -- >
<script src="{{ asset('./js/app.js')}}"></script>

3. Paging in laravel

Paging data display can be easily realized in laravel. The first step is to page out the database data in the controller and transfer it to the page:

return view('student.index',['students'=>Student::paginate(5)]);

The second part renders pagination labels in the page:


4. Form validation

Laravel provides a validate method to verify whether the form submitted by the user meets the requirements. For example, after the page submits the student form through post, verify it in the controller first. If it is correct, it will be stored in the database. Otherwise, it will return to the previous page and throw an exception $errors, and the information in error $errors will be displayed in the page

//Form validation
  'required '= >': attribute is required ',
  'MAX '= >': attribute length is too long ',
  'Integer' = > ': attribute must be an integer'
  'student. Name '= >' name ',
  'student. Age '= >' age ',
  'student. Sex '= >' gender '
//Save student data

Validation rules for fields defined in the first array in validate(), whereStudent.nameIs the name defined in the submitted form

Input type = "text" name = "student [name]" placeholder = "please enter student name" >

Required is the validation rule you need, separated by “|” in the middle. See the document for detailed rules

Validate() the prompt after the second array custom validation error, “: attribute” is a placeholder

Validate() the third array customizes the prompt name for each field

The errors reported on the page are as follows:

Can pass$errors->all()After getting all the errors, the loop is displayed

      @foreach($errors->all() as $error)

it’s fine too$errors->first()Gets the validation error for the specified field, which is displayed after each input box


When the verification fails and returns to the form page, the user’s original input information will disappear, so it needs to be filled in again. The user’s original input can be displayed through the old method

<input type="text" name="Student[name]" value="{{old('Student')['name']}}" >

5. Error record

①、 MethodNotAllowedHttpException No message

This error is because I sent the post request of the form toRoute::get()On the defined route, it will not process post requests and can pass the routeRoute::Match(['get','post'],)To define

②、Action App\Http\Controllers\[email protected] not defined

This error occurs when I request to jump to an action on the blade page and cannot find the controller

<a href="{{action(' [email protected] '['id' = > $student - > ID]) "}}" rel = "external nofollow" > delete</a>

However, when I register this method under routes / web.php, the error message disappears

Route::get('delete/{id}','[email protected]');

③、The page has expired due to inactivity. Please refresh and try again.

This is because laravel is automatically set to prevent CSRF cross domain attacks. You need to add it in the formcsrf_filed()To tell laravel that the originator of the request is the same person as the form submitter.

<form method="post" action="{{url('student/create')}}">
  {{ csrf_field() }}

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.