Laravel framework 06: files, migration filling, sessions, caching

Laravel framework 06: files, migration fill, session, cache

  • 1. File upload
    • 1. File upload form
    • 2. Upload business processing
    • 3. All code
  • 2. Migration and filling of data tables
    • 1. Migrating files
      • ① Create a migration file
      • ② Write the migration file
      • ③ Execute the migration file
      • ④ Roll back the migration file
    • 2. Populate (seed) file
      • ① Create a filling file
      • ② Write the filling file
      • ③ Execute the filling file
  • 3. Session Control
  • 4. Caching mechanism
    • 1. Set the cache
    • 2. Get the cache
    • 3. Delete the cache
    • 4. Counter

1. File upload

1. File upload form

  • action, method, enctype
  • file
  • submit
<form action="/home/test/test12" method="POST" enctype="multipart/form-data">
    {<!-- -->{csrf_field()}}
    <input type="file" name="file" id="">
    <button type="submit">Submit</button>
</form>

2. Upload business processing

  • Whether to upload files
$request->hasFile("avatar");
  • Verify that the file was uploaded successfully
$request->file("avatar")->isValid();
  • Get uploaded files
$file = $request->file("avatar");
// or
$file = $request->avatar;
  • extension method
    • path: the absolute path of the file
    • extension: extension.
    • See the manual for more methods…
  • Storage path
    If the path is for PHP code, it is recommended to use a relative path. If the path is for the browser, use an absolute path.
    You need to add the folder uploads under /public first.
$request->file("avatar")->move('./uploads', md5(time() . rand(100000, 999999)) .".". $request - > file("avatar") -> getClientOriginalExtension());

3. All code

public function test12(Request $request) {<!-- -->
    //Determine the request type
    if ($request->isMethod("POST")) {<!-- -->
        // upload
        if ($request->hasFile("avatar") & amp; & amp; $request->file("avatar")->isValid()) {<!-- -->
            $request->file("avatar")->move('./uploads', md5(time() . rand(100000, 999999)) .".". $request -> file( "avatar") -> getClientOriginalExtension());
        }
    }else{<!-- -->
        // show the view
        return view("home.test.test8");
    }
}

2. Data table migration and filling

  • Migration: operation of creating data table + operation of deleting data table
  • Filling: fill the data table with the data written into the test (data insertion operation)

1. Migrating files

  • The files stored under database/migrations are called migration files.

① Create migration file

php .\artisan make:migration create_paper_table
  • In the newly created migration file, up() is to create a data table, and down() is to delete a data table.

② Write migration file

  • The Schema facade is used to manipulate the database.
  • $table represents an instance of the entire table.
  • Syntax: $table -> column type method (field name [, length/range]) -> column modification method ([modified value]);
public function up()
{<!-- -->
    Schema::create('paper', function (Blueprint $table) {<!-- -->
        $table->increments("id");
        $table->string("paper_name", 100);
        $table->tinyInteger("paper_score")->default(100);
        $table->integer("start_time")->nullable();
        $table->tinyInteger("duration");
        $table->enum("status", [1, 2])->default(1);
    });
}

public function down()
{<!-- -->
    Schema::dropIfExists('paper');
}

③ Execute the migration file

  • Before executing the migration file for the first time, you need to create a migration file record table.
php .\artisan migrate:install


After execution, there will be an additional data table migrations in the database.

  • Delete the built-in migration file and only keep your own.
  • Execute the migration file
php .\artisan migrate

④ Rollback migration file

  • Roll back the last migration operation
php .\artisan migrate:rollback

2. Populate (seed) file

  • The files stored under database/seeds are called seed files.

① Create a fill file

php .\artisan make:seeder PaperTableSeeder

② Write a fill file

  • In the form file you can use the DB facade to add data.
public function run() {<!-- -->
    //
    $data = [
        [
            "paper_name" => "Five-year college entrance examination, three-year simulation",
            "start_time" => strtotime(" + 7 days"),
            "duration" => "120",
        ],
        [
            "paper_name" => "Huanggang Secret Scroll",
            "start_time" => strtotime(" + 7 days"),
            "duration" => "120",
        ],
        [
            "paper_name" => "Hengshui mid-term volume",
            "start_time" => strtotime(" + 7 days"),
            "duration" => "120",
        ]
    ];
    DB::table()->insert($data);
}

③ Execute the filling file

php .\artisan db:seed --class=PaperTableSeeder

3. Session control

  • Sessions are stored in files by default.
  • Directory of session files: storage/framework/sessions.
  • session facade: use Illuminate\Support\Facades\Session;
  • session can also be used in views.
public function test13() {<!-- -->
    // Store a variable in the Session
    Session::put("name", "Zhang San");
    
    // Get the variables in the Session
    echo Session::get("name");
    
    // Get the variable in the Session, if it does not exist, return the default value
    echo Session::get("age", 80);
    echo Session::get("gender", function () {<!-- -->
        return "Walmart Shopping Bag";
    });
    
    // Get all relevant information in the Session
    var_dump(Session::all());
    
    // Check if the variable exists in the Session
    var_dump(Session::has("name"));
    
    // Delete variables in Session
    Session::forget("name");
    
    // Delete all variables in the Session
    Session::flush();
}

4. Caching mechanism

  • The cache configuration is located in config/cache.php

1. Set cache

  • put() If the key already exists, it will directly overwrite the original value.
  • The validity period must be set, and the unit is minute.
Cache::put('key', 'value', $minutes);
  • add() returns false if the key exists. If it does not exist, it will return true if it is successfully added.
Cache::add('key', 'value', $minutes);
  • forever() is used for persistent storage to the cache, and must be deleted from the cache using the forget method.
Cache::forever('key', 'value');
  • remember() If the key does not exist, get the default value and set the variable to the default value.
Cache::remember("time", 10, function (){<!-- -->
   return date("Y-m-d H:i:s");
});

2. Get cache

  • get() Gets a variable.
Cache::get("name", "No username");
Cache::get("age", function (){<!-- -->
    return "No age is set";
});
  • has() determines whether a variable exists
Cache::has("gender")

3. Delete cache

  • pull() Get it from the cache and then delete it, which is often used for one-time storage.
Cache::pull("age")
  • forget() Delete directly.

  • flush() clears all caches and deletes the corresponding directory.

Cache::flush();

4. Counter

  • increment and decrement are used to adjust integer values in the cache. Generally used for counters.
Cache::increment("count");
Cache::increment("count", 2);
Cache::decrement("count");
Cache::decrement("count", 2);