laravel code focus

Posted by ibanez270dx on Thu, 20 Feb 2020 04:54:06 +0100

1. To create a project through composer:

composer create-project --prefer-dist laravel/laravel laravel

2. Enter project:

cd /var/www/html/laravel

3. To create a controller:

 php artisan make:controller StudentController

4. Create model classes and data migration files:

php artisan make:model Student –m   

[the migration file is in / database/migrations]
Another way to create a migration file:

php artisan make:migration create_students_table

5. Open the migration file, supplement other fields in the up method, and the function of the down() method is opposite

public function up(){
    Schema::create('students', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name','64');
        $table->integer('age')->unsigned()->default(0);
        $table->integer('sex')->unsigned()->default(1);
        $table->integer('created_at')->default(0);
        $table->integer('updated_at')->default(0);
});
}

6. Run migration file:

php artisan migrate

7. Add test data with data filling, and create a new filling file:

php artisan make:seeder StudentsTableSeeder 

[fill file in / database/seeds]
8. Open the fill file and add an insert statement to the run method

public function run(){
    DB::table('students')->insert([
        ['name'=>'im','age'=>'23'],
        ['name'=>'Lily','age'=>18]
    ]);
}

9. Run the specified population file:

php artisan db:seed --class=StudentsTableSeeder 

[PHP artican DB: seed run all filler files]
10. Configure multi request routing for add method of Student controller

Route::match(['get','post'],'student/add',['as'=>'student/add','uses'=>'StudentController@add']);

11. View code focus
Put the header/footer and other public parts of the page into views/common/layouts.blade.php

Layouts. Blade. PHP <! -- parent template -- >
< link rel = "stylesheet" href = "{{asset ('dist / CSS / style. CSS')}" >
< a href = "{route ('student / add ')}" >
<h1 class="section-header">
     @The section ('name ') instruction <! -- @ section defines part of the view, while the @ yield instruction is used to display the content of the specified part -- >
        Public area
     @show
 </h1>
 <div class="section-body">
    @yield('body ',' no content ')
 </div>
Message.blade.php
 <h3>I am the include d view file</h3>
add.blade.php 
@Extensions ('common. Layouts') <! -- inherit layouts template -- >
@section('name')
  @Parent <! -- @ section can use @ parent to inherit the content of the parent template -- >
  <div>Dashboard</div>
@stop
 @Section ('body ') <! -- defined with @ Yield in the parent template, but also rewritten with @ section, @ yield can only rewrite the content of the parent template, not inherit -- >
@Include ('common. Message ') <! -- include other files -- >
<form method="post" class="needs-validation" novalidate action="">
<! - form form needs to add token, otherwise 419 error will appear. csrf_token does not need to be generated by itself, just put it in, and laravel will generate -- >
  	<input type="hidden" name="_token" value="{{csrf_token()}}">
</form>
 @stop

12. Key points of controller
(1) There are two ways to add data: save and create
① save()

public function add(Request $request){   	
	if($request->isMethod('POST')){
		$student=new Student();
        $student->name=$data['name'];
        $student->age=$data['age'];
        $student->sex=$data['sex'];
        if($student->save()){
        	return redirect('student/info');
        }else{
           return redirect('student/add')->with('Add failure');
        }
    } 
    return view('student.add');
}

② create(): you can use the create method to save the new model, which returns the model instance. However, you need to specify the fillable or guarded attribute on the model

public function add(Request $request){
	if($request->isMethod('POST')){
		$data=$request->input('student');
        if(Student::create($data)){
        	return redirect('student/info')->with('success','Add success'); //with content can be saved into session and taken out on the page. See Step 3
        }else{
            return redirect()->back();
        }
    }
    return view('student.add');
}
model Class:		
protected $fillable=['name','age','sex'];

③ Take out the data with when redirecting

@if(Session::has('success'))
 Success: {{Session::get('success')}}
@endif

(2) Data validation
StudentController.php
//Verification method 1: use validate to verify

/*
①,If the verification succeeds, it will continue. If the verification fails, it will automatically redirect to the previous location and save the error information to the session
②,The view does not need to be obtained by the get method. You can get all error validation information by using the $errors - > all() method, and get the first error validation information by using $errors - > first()
③,$errors Variables are bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware provided by the web middleware group
*/

$this->validate($request,[
        'student.name'=>'required|min:2|max:10',
        'student.age'=>'required|integer',
        'student.sex'=>'required|integer'
    ],[
        'required'=>':attribute Required items',//: attribute is a placeholder
        'integer'=>':attribute Integer'
    ],[
        'student.name'=>'Full name',
        'student.age'=>'Age',
        'student.sex'=>'Gender'
    ]);
//Verification method 2: use the validator class to verify
$validator=Validator::make($request->input(),[
    'student.name'=>'required|min:2|max:10',
    'student.age'=>'required|integer',
    'student.sex'=>'required|integer'
],[
    'required'=>':attribute Required items',//: attribute is a placeholder
    'integer'=>':attribute Integer'
],[
    'student.name'=>'Full name',
    'student.age'=>'Age',
    'student.sex'=>'Gender'
]);
if($validator->fails()){
    return redirect()->back()->withErrors($validator);
}
///////////////////////////////////////
Validate.blade.php
@foreach($errors->all() as $error)
<div>{{$error}}</div>
@endforeach


(3) Data retention
Add a withInput to the data validation redirection in the second

 return redirect()->back()->withErrors($validator)->withInput();

Then set the value in the input box of the view

<input type="text" name="student[name]" value="{{old('student')['name']}}" class="form-control" required> 

13. Model focus
(1) Model gender
In the column of gender on the list page, only 1 / 2 / 3 will be displayed, but not men and women. You can do the following
① Model class definition

class Student extends Model{
    const SEX_BOY=1;
    const SEX_GIRL=2;
    const SEX_UN=3;
    public function sex($key){
        $array=[
            self::SEX_BOY=>'male',
            self::SEX_GIRL=>'female',
            self::SEX_UN=>'Unknown',
        ];
        if($key !==null){
            return array_key_exists($key,$array)?$array[$key]:$array[self::SEX_UN];
        }
    }
}

② Controller value

public function info(){
	$result=Student::paginate(5);//paging
    return view('student.info',['students'=>$result]);
}

③ View display

@foreach($students as $stu)
<td>{{$stu->sex($stu->sex)}}</td>
 @endforeach
 {{$blog->links()}}

Effect picture

(2) Time processing

public $timestamps=false;//No automatic maintenance timepublic function getDateFormat(){
	return time();
}

14, paging

StudentController.php
$result=Student::paginate(10);
return view('student.info',['students'=>$result]);

Info.blade.php
{{$students->render()}}

15. Data modification
(1) Because the modified page is basically the same as the added page, you can extract the form form form of the added page and create a new file ﹤ form.blade.php, and then add the new form page of the added page and the modified page include
Update.blade.php

@extends('common.layouts')<!--Inheritance template-->
@section('name')
    @parent
    <div>Modify user</div>
 @stop
 @section('body')
  @include('common.validate')
  <div class="row">
    <div class="col-lg-5 col-md-12 col-12 col-sm-12">
      @include('student._form');
    </div>
  </div>
@stop
     _form.blade.php
<form method="post" class="needs-validation" novalidate action="">
    <input type="hidden" name="_token" value="{{csrf_token()}}">
<div class="form-group">
    <label>Name</label>
    <input type="text" name="student[name]" value="{{old('student')['name']? old('student')['name']:$student->name}}" required>
    <div class="invalid-feedback">{{$errors->first('student.name')}}</div>
    </div>
    <div class="form-group">
    <label>Age</label>
    <input type="number"  name="student[age]" value="{{old('student')['age']? old('student')['age']:$student->age}}" required>
    <div class="invalid-feedback">Please fill in the age</div>
    </div>
    <div class="form-group">
    <label>Sex</label>
   @foreach($student->sex() as $key=>$val)
   <input type="radio" name="student[sex]"  value="{{$key}}"{{$student->sex==$key?'checked':''}}>{{$val}}
  @endforeach

</div>
</form>

(2) New update method and corresponding route
StudentController.php

public function update(Request $request,$id){
    $student=Student::find($id);
    if($request->isMethod('POST')){
        $data=$request->input('student');
        $student->name=$data['name'];
        $student->age=$data['age'];
        $student->sex=1;
        if($student->save()){
            return redirect('student/info')->with('success','Modified success');
        }else{
            return redirect()->back()->withInput();
        }
    }
    return view('student.update',[
        'student'=>$student
    ]);
}

Web.php

Route::group(['middler'=>'web'],function(){
	Route::any('student/info','StudentController@info')->name('student/info');
	Route::any('student/index','StudentController@index');
	Route::any('student/save','StudentController@save')->name('save');
	Route::any('student/update/{id}','StudentController@update');
});

(3) Modify button links

<a href="{{url('student/update', ['id'=>$stu->id])}}">modify</a>

16. Delete data

public function del($id){
	   //  $num=Blog::destroy(1,2);
	   //  echo $num;
	   // $bool=Blog::where('id',$id)->delete();
	   // var_dump($bool);

    $student=Student::find($id);
    if($student->delete()){
        return redirect('student/info')->with('success','Delete successful');
    }else{
        return redirect()->back();
    }
}

17. Auth user authentication

user@bogon:/var/www/html/laravel$ composer require laravel/ui Report errors


Solve:
user@bogon:/var/www/html/laravel$ composer dump-autoload
User @ Bogon: / var / www / HTML / laravel $composer update -------- update dependency

user@bogon:/var/www/html/laravel$ php artisan ui vue –auth

18. File upload
(1) Configuration file config/filesystems.php
Add a configuration under the disks element:

'disks' => [
	'local' => [
		'driver' => 'local',
        'root' => storage_path('app'),
    ],
    //Newly added
	'upload' => [
       'driver' => 'local',
       'root' => storage_path('app/uploads'),//The upload file path is storage/app/uploads
//     'root' = > public_path ('uploads'), / / the upload file path is public/uploads
       'url' => env('APP_URL').'/storage',
       'visibility' => 'public',
    ],
    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
        ],
        //..........
];

(2) View: Upload.blade.php

<form method="post" class="needs-validation" novalidate action="" enctype="multipart/form-data">
 	<input type="hidden" name="_token" value="{{csrf_token()}}">
<label>Select file</label>
    <input type="file" name="source" value="" class="form-control" required>
    <button class="btn btn-primary">Confirm upload</button>
</form>

(3) Controller: StudentController.php

public function upload(Request $request){
    if($request->isMethod('POST')){
        $file=$request->file('source');
        //Whether the file is uploaded successfully
        if($file->isValid()){
            $originalName=$file->getClientOriginalName();//original file name
            $ext=$file->getClientOriginalExtension();//Extension name
            $mineType=$file->getClientMimeType();
            $realPath=$file->getRealPath();//Temporary file path
            $filename=date('Y-m-d-H-i-s').'.'.$ext;
            //Upload files
            $bool=Storage::disk('upload')->put($filename,file_get_contents($realPath));
            var_dump($bool);
        }
    }
    return view('student/upload');
}

19. Mail sending
(1) The configuration file is in the config/mail.php file

'from' => [
    'address' => env('MAIL_FROM_ADDRESS', '9***9@qq.com'),
    'name' => env('MAIL_FROM_NAME', 'oneself'),
],
//modify.env file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.qq.com
MAIL_PORT=465
MAIL_USERNAME=qq mailbox
MAIL_PASSWORD=qq Email authorization code
MAIL_ENCRYPTION=ssl

(2) Send mail
① Send text

public function mail(){
   Mail::raw('Mail content',function($message){
       $message->from('9**1@qq.com','Muzi');
       $message->to('9**2@163.com');
       $message->subject('Mail theme');
   });
}

② Send html template

public function mail(){
   Mail::send('student.mail',['name'=>'Muzi'],function($message){
       $message->to('123**345@163.com');
   });
}

mail.blade.php

<h1>hello,{{$name}}</h1>

20. The configuration file is in config/cache.php

//put() to set 10 minute expiration
Cache::put('key1','val1',10);
//add() if the key1 does not exist, the addition fails
$bool=Cache::add('key2','val2',10);
//forever() is permanently stored in the cache
Cache::forever('key3','val3');
//has() determines whether the key exists
if(Cache::has('key1')){
    echo Cache::get('key1');
}
//get() value
$val1=Cache::get('key1','default');
//pull() gets the data from the cache and then deletes it
$val3=Cache::pull('key3');
//forget() to delete data from cache
$bool=Cache::forget('key3');

21. Errors and logs
(1) HTTP exception
① Some exceptions are used to describe HTTP error codes generated from the server, such as 404 and 500. You can use the abort function to generate such a response anywhere in the program

public function index(){
    abort('404');
}


② You can also customize the HTTP error page
Create a new resources/views/errors/404.blade.php file

<h3>Page lost</h3>


(2) The log configuration file is in config/logging.php
Log level: emergency, alert, critical, error, warning, notice, info and debug

public function index(){
    Log::info('I am info Level error');
}

Log files will be generated in the storage/logs folder

22. The queue application configuration file is in config/queue.php
The queue supports many drivers. Next, use the database driver. First, modify it in the. env file

QUEUE_CONNECTION=database

(1) Data table required for migration queue:
To create a task table:

php artisan queue:table

Under the database/migrations file, 2020 ﹐ 01 ﹐ 16 ﹐ 06 ﹐ create ﹐ jobs ﹐ table.php will be generated
To perform a migration file:

php artisan migrate

(2) Write task class
Use command

php artisan make:job sendEmail

In the app/Jobs folder, a new sendEmail.php will be created. Make the following changes

class sendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $email;
    public function __construct($email)
    {
        //
        $this->email=$email;
    }
    public function handle()
    {
        //Send mail
//        Mail::raw('test message 233',function ($message){
//            $message->from('9****9@qq.com');
//            $message->to('1****8@qq.com');
//            $message - > subject ('test test ');
//        });
 Log::info('Sent message'.$this->email);
}
}

(3) Push task to queue

use App\Jobs\sendEmail;
class StudentController extends Controller
{
    public function index(){
        SendEmail::dispatch('1111@163.com');
     }
}

Run the index method, and a new piece of data will be added to the jobs table
(4) Run queue listener

php artisan queue:listen


open the log file

(5) Processing failed tasks
① Create failure task table: PHP artican queue: failed table
② View failure task record: PHP artican queue: failed
③ Re execute the failed task with id 1: PHP artican queue: retry 1
④ Re execute all failed tasks: php a rtisan queue:retry all
⑤ Delete failed task with id 1: PHP artican queue: forget 1
⑥ Delete all failed tasks: PHP artican queue: flush

Published 3 original articles, won praise 0, visited 140
Private letter follow

Topics: PHP Laravel Attribute Database