英文:
Laravel 8: Session does not apply
问题
I'm here to provide translations. Here's the translated content:
我在Laravel 8中,想要在`login.blade.php`中向用户显示错误消息,当他输入错误的凭据登录他的帐户时。
所以在控制器中,我有以下代码:
if (Auth::attempt($credentials)) {
    // 登录用户
} else {
    Session::flash('email', '错误的凭据');
    return redirect()->back();
}
然后在Blade模板中:
@if(\Session::has('email'))
    @dd(1)
@endif
但是`@dd(1)` 不知何故不起作用。这意味着会话电子邮件未提交。
我还在Blade模板末尾添加了`@php dump(session()->all()); @endphp`,以查看会话,但结果是`[]`。
那么,这里出了什么问题?我该如何解决这个问题?
以下是`config/session.php`的内容:
<?php
use Illuminate\Support\Str;
return [
    /*
    |--------------------------------------------------------------------------
    | 默认会话驱动程序
    |--------------------------------------------------------------------------
    |
    | 此选项控制将在请求上使用的默认会话“驱动程序”。默认情况下,我们将使用轻量级的本地驱动程序,
    | 但是您可以指定这里提供的任何其他精彩驱动程序。
    |
    | 支持:“file”、“cookie”、“database”、“apc”、
    | “memcached”、“redis”、“dynamodb”、“array”
    |
    */
    'driver' => env('SESSION_DRIVER', 'file'),
    /*
    |--------------------------------------------------------------------------
    | 会话生存时间
    |--------------------------------------------------------------------------
    |
    | 在此处,您可以指定会话在过期之前允许保持空闲的分钟数。如果您希望它们在浏览器关闭时立即过期,
    | 请设置该选项。
    |
    */
    'lifetime' => env('SESSION_LIFETIME', 120),
    'expire_on_close' => false,
    /*
    |--------------------------------------------------------------------------
    | 会话加密
    |--------------------------------------------------------------------------
    |
    | 此选项允许您轻松指定在存储之前应加密所有会话数据。
    | 所有加密将由Laravel自动运行,您可以像正常使用会话一样使用它。
    |
    */
    'encrypt' => false,
    /*
    |--------------------------------------------------------------------------
    | 会话文件位置
    |--------------------------------------------------------------------------
    |
    | 当使用本机会话驱动程序时,我们需要一个位置来存储会话文件。
    | 默认为您设置了一个,但可以指定不同的位置。这仅适用于文件会话。
    |
    */
    'files' => storage_path('framework/sessions'),
    /*
    |--------------------------------------------------------------------------
    | 会话数据库连接
    |--------------------------------------------------------------------------
    |
    | 当使用“数据库”或“redis”会话驱动程序时,您可以指定应该用于管理这些会话的连接。
    | 这应该与数据库配置选项中的连接对应。
    |
    */
    'connection' => env('SESSION_CONNECTION', null),
    /*
    |--------------------------------------------------------------------------
    | 会话数据库表
    |--------------------------------------------------------------------------
    |
    | 当使用“数据库”会话驱动程序时,您可以指定用于管理会话的表。
    | 当然,为您提供了明智的默认值;但是,您可以根据需要自由更改。
    |
    */
    'table' => 'sessions',
    /*
    |--------------------------------------------------------------------------
    | 会话缓存存储
    |--------------------------------------------------------------------------
    |
    | 在使用框架的缓存驱动会话后端之一时,您可以列出应该用于这些会话的缓存存储。
    | 此值必须与应用程序配置的缓存“存储”之一匹配。
    |
    | 影响:“apc”、“dynamodb”、“memcached”、“redis”
    |
    */
    'store' => env('SESSION_STORE', null),
    /*
    |--------------------------------------------------------------------------
    | 会话清理抽奖
    |--------------------------------------------------------------------------
    |
    | 一些会话驱动程序必须手动扫描其存储位置以从存储中删除旧会话。
    | 在给定的请求上发生的机会如下。默认情况下,几率是100中的2。
    |
    */
    'lottery' => [2, 100],
    /*
    |--------------------------------------------------------------------------
    | 会话Cookie名称
    |--------------------------------------------------------------------------
    |
    | 在此处,您可以更改用于通过ID标识会话实例的cookie的名称。
    | 每次由框架为每个驱动程序创建新的会话cookie时,都将使用指定的名称。
    |
    */
    'cookie' => env(
        'SESSION_COOKIE',
        Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),
    /*
    |--------------------------------------------------------------------------
    | 会话Cookie路径
    |--------------------------------------------------------------------------
    |
    | 会话cookie路径确定cookie将被视为可用的路径。
    | 通常,这将是您的应用程序的根路径,但在必要时可以自由更改。
    |
    */
    'path' => '/',
    /*
    |--------------------------------------------------------------------------
    | 会话Cookie域
    |--------------------------------------------------------------------------
    |
    | 在此处,您可以更改应用程序中用于标识会话的cookie的域。
    | 这将确定哪些域可以在应用程序中使用该cookie。已设置了明智的默认值。
    |
    */
    'domain' => env('SESSION_DOMAIN', null),
    /*
    |--------------------------------------------------------------------------
    | 仅限HTTPS的Cookie
    |--------------------------------------------------------------------------
    |
    | 将此选项设置为true,会话cookie只会在浏览器具有HTTPS连接时发送回服务器。
    | 这将防止在无法安全发送时将cookie发送给您。
    |
    */
    'secure' => env('SESSION_SECURE_COOKIE'),
    /*
    |--------------------------------------------------------------------------
    | 仅HTTP访问
    |--------------------------------------------------------------------------
    |
    | 将此值设置为true将阻止JavaScript访问cookie的值,
    | 并且只能通过HTTP协议访问cookie。如有需要,您可以自由修改此选项。
    |
    */
    'http_only' => true,
    /*
    |--------------------------------------------------------------------------
    | Same-Site Cookies
<details>
<summary>英文:</summary>
I'm in Laravel 8 and I wanted to show an error message to user when he enters wrong credentials for signing into his account at `login.blade.php`.
So in the Controller, I have this:
    if(Auth::attempt($credentials)){
        // log user in
    }else{
        Session::flash('email', 'wrong credentials');
        return redirect()->back();
    }
Then in the Blade:
     @if(\Session::has('email'))
        @dd(1)
    @endif
But `dd(1)` does not work out somehow. Meaning that the session email was not submitted. 
I also added the `@php dump(session()->all()); @endphp` at the end of blade to see the sessions but it is `[]`
So what's going wrong here? How can I solve this issue?
Here is the `config/session.php`:
    <?php
    
    use Illuminate\Support\Str;
    
    return [
    
        /*
        |--------------------------------------------------------------------------
        | Default Session Driver
        |--------------------------------------------------------------------------
        |
        | This option controls the default session "driver" that will be used on
        | requests. By default, we will use the lightweight native driver but
        | you may specify any of the other wonderful drivers provided here.
        |
        | Supported: "file", "cookie", "database", "apc",
        |            "memcached", "redis", "dynamodb", "array"
        |
        */
    
        'driver' => env('SESSION_DRIVER', 'file'),
    
        /*
        |--------------------------------------------------------------------------
        | Session Lifetime
        |--------------------------------------------------------------------------
        |
        | Here you may specify the number of minutes that you wish the session
        | to be allowed to remain idle before it expires. If you want them
        | to immediately expire on the browser closing, set that option.
        |
        */
    
        'lifetime' => env('SESSION_LIFETIME', 120),
    
        'expire_on_close' => false,
    
        /*
        |--------------------------------------------------------------------------
        | Session Encryption
        |--------------------------------------------------------------------------
        |
        | This option allows you to easily specify that all of your session data
        | should be encrypted before it is stored. All encryption will be run
        | automatically by Laravel and you can use the Session like normal.
        |
        */
    
        'encrypt' => false,
    
        /*
        |--------------------------------------------------------------------------
        | Session File Location
        |--------------------------------------------------------------------------
        |
        | When using the native session driver, we need a location where session
        | files may be stored. A default has been set for you but a different
        | location may be specified. This is only needed for file sessions.
        |
        */
    
        'files' => storage_path('framework/sessions'),
    
        /*
        |--------------------------------------------------------------------------
        | Session Database Connection
        |--------------------------------------------------------------------------
        |
        | When using the "database" or "redis" session drivers, you may specify a
        | connection that should be used to manage these sessions. This should
        | correspond to a connection in your database configuration options.
        |
        */
    
        'connection' => env('SESSION_CONNECTION', null),
    
        /*
        |--------------------------------------------------------------------------
        | Session Database Table
        |--------------------------------------------------------------------------
        |
        | When using the "database" session driver, you may specify the table we
        | should use to manage the sessions. Of course, a sensible default is
        | provided for you; however, you are free to change this as needed.
        |
        */
    
        'table' => 'sessions',
    
        /*
        |--------------------------------------------------------------------------
        | Session Cache Store
        |--------------------------------------------------------------------------
        |
        | While using one of the framework's cache driven session backends you may
        | list a cache store that should be used for these sessions. This value
        | must match with one of the application's configured cache "stores".
        |
        | Affects: "apc", "dynamodb", "memcached", "redis"
        |
        */
    
        'store' => env('SESSION_STORE', null),
    
        /*
        |--------------------------------------------------------------------------
        | Session Sweeping Lottery
        |--------------------------------------------------------------------------
        |
        | Some session drivers must manually sweep their storage location to get
        | rid of old sessions from storage. Here are the chances that it will
        | happen on a given request. By default, the odds are 2 out of 100.
        |
        */
    
        'lottery' => [2, 100],
    
        /*
        |--------------------------------------------------------------------------
        | Session Cookie Name
        |--------------------------------------------------------------------------
        |
        | Here you may change the name of the cookie used to identify a session
        | instance by ID. The name specified here will get used every time a
        | new session cookie is created by the framework for every driver.
        |
        */
    
        'cookie' => env(
            'SESSION_COOKIE',
            Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
        ),
    
        /*
        |--------------------------------------------------------------------------
        | Session Cookie Path
        |--------------------------------------------------------------------------
        |
        | The session cookie path determines the path for which the cookie will
        | be regarded as available. Typically, this will be the root path of
        | your application but you are free to change this when necessary.
        |
        */
    
        'path' => '/',
    
        /*
        |--------------------------------------------------------------------------
        | Session Cookie Domain
        |--------------------------------------------------------------------------
        |
        | Here you may change the domain of the cookie used to identify a session
        | in your application. This will determine which domains the cookie is
        | available to in your application. A sensible default has been set.
        |
        */
    
        'domain' => env('SESSION_DOMAIN', null),
    
        /*
        |--------------------------------------------------------------------------
        | HTTPS Only Cookies
        |--------------------------------------------------------------------------
        |
        | By setting this option to true, session cookies will only be sent back
        | to the server if the browser has a HTTPS connection. This will keep
        | the cookie from being sent to you when it can't be done securely.
        |
        */
    
        'secure' => env('SESSION_SECURE_COOKIE'),
    
        /*
        |--------------------------------------------------------------------------
        | HTTP Access Only
        |--------------------------------------------------------------------------
        |
        | Setting this value to true will prevent JavaScript from accessing the
        | value of the cookie and the cookie will only be accessible through
        | the HTTP protocol. You are free to modify this option if needed.
        |
        */
    
        'http_only' => true,
    
        /*
        |--------------------------------------------------------------------------
        | Same-Site Cookies
        |--------------------------------------------------------------------------
        |
        | This option determines how your cookies behave when cross-site requests
        | take place, and can be used to mitigate CSRF attacks. By default, we
        | will set this value to "lax" since this is a secure default value.
        |
        | Supported: "lax", "strict", "none", null
        |
        */
    
        'same_site' => 'lax',
    
    ];
</details>
# 答案1
**得分**: 1
前往 `App/Http/Kernel.php` 文件。
将 `\Illuminate\Session\Middleware\StartSession::class` 这行代码添加到 `$middleware` 数组中。请查看下面的截图。
![截图][1]
[1]: https://i.stack.imgur.com/Vk1to.png
就是这样。现在我们来测试一下会话功能。
****
如果仍然存在问题,请尝试以下方法来存储数据。希望对你有所帮助。
尝试使用全局的 `session()` 辅助函数,方法如下。
**-- 存储数组**
```php
Session::push('key', $array);
//或者
session()->push('key', $array);
-- 按键存储会话
Session::put('session_key', 'value');
//或者
session(['key' => 'value']);
-- 通过键检索会话
Session::get('key');
//或者
session('key');
-- 从会话获取所有数据
Session::all();
//或者
session()->all();
英文:
- Go to the 
App/Http/Kernel.phpfile. - Add this line 
\Illuminate\Session\Middleware\StartSession::class, into the$middlewarearray. Please check the below screenshot. 
That’s it. Let’s test the session now.
If you still have an issue then try the following way to store the data.
I hope that helps.
Try to use a global session() helper function as below.
-- To Store An Array
Session::push('key', $array);
//or
session()->push('key', $array);
-- Store Session By a Key
Session::put('session_key', 'value');
//or
session(['key'=>'value']);
-- Retrieving Session By Key
Session::get('key');
//or
session('key');
-- Get All Data From The Session
Session::all();
//or
session()->all();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论