laravel5.5路由使用name的好处与http会话机制

使用name的好处

辅助函数 route 可以用于为指定路由生成 URL。命名路由生成的 URL 不与路由上定义的 URL 相耦合。因此,就算路由的 URL 有任何更改,都不需要对 route 函数调用进行任何更改。例如,假设你的应用程序包含以下路由:

Route::get('/post/{post}', function () {
    //
})->name('post.show');

要生成此路由的 URL,可以像这样使用辅助函数 route:

echo route('post.show', ['post' => 1]);

// http://example.com/post/1

将 Eloquent 模型 作为参数值传给 route 方法,它会自动提取模型的主键来生成 URL。

echo route('post.show', ['post' => $post]);

http会话机制

1、配置文件 config/session.php

大多数是用file驱动,将session保存在storage/framework/sessions,可以考虑使用redis或者memcached 驱动实现更出色的性能

2、使用database作为驱动

需要创建数据表

php artisan session:table

php artisan migrate

数据表内容

Schema::create('sessions', function ($table) {
    $table->string('id')->unique();
    $table->integer('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity');
});

3、使用session

laravel 中处理 Session 数据有两种主要方法:

1> 全局辅助函数 session 和通过一个 Request 实例。

    public function show(Request $request, $id)
    {
        $value = $request->session()->get('key');

        //
    }
Route::get('home', function () {
    // 获取 Session 中的一条数据...
    $value = session('key');

    // 指定一个默认值...
    $value = session('key', 'default');

    // 在 Session 中存储一条数据...
    session(['key' => 'value']);
});

2> 通过 HTTP 请求实例操作 Session 与使用全局辅助函数 session 两者之间并没有实质上的区别

获取所有 Session 数据

$data = $request->session()->all();

要确定 Session 中是否存在某个值,可以使用 has 方法。如果该值存在且不为 null,那么 has 方法会返回 true:

if ($request->session()->has('users')) {
    //
}

要确定 Session 中是否存在某个值,即使其值为 null,也可以使用 exists 方法。如果值存在,则 exists 方法返回 true:

if ($request->session()->exists('users')) {
    //
}

猜你喜欢

转载自blog.csdn.net/qq_20355575/article/details/81975216