“Laravel 8: Session does not apply” 可以翻译为 “Laravel 8:会话不生效”。

huangapple go评论111阅读模式
英文:

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&#39;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(&#39;email&#39;, &#39;wrong credentials&#39;);
        return redirect()-&gt;back();
    }

Then in the Blade:

     @if(\Session::has(&#39;email&#39;))
        @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()-&gt;all()); @endphp` at the end of blade to see the sessions but it is `[]`

So what&#39;s going wrong here? How can I solve this issue?

Here is the `config/session.php`:

    &lt;?php
    
    use Illuminate\Support\Str;
    
    return [
    
        /*
        |--------------------------------------------------------------------------
        | Default Session Driver
        |--------------------------------------------------------------------------
        |
        | This option controls the default session &quot;driver&quot; 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: &quot;file&quot;, &quot;cookie&quot;, &quot;database&quot;, &quot;apc&quot;,
        |            &quot;memcached&quot;, &quot;redis&quot;, &quot;dynamodb&quot;, &quot;array&quot;
        |
        */
    
        &#39;driver&#39; =&gt; env(&#39;SESSION_DRIVER&#39;, &#39;file&#39;),
    
        /*
        |--------------------------------------------------------------------------
        | 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.
        |
        */
    
        &#39;lifetime&#39; =&gt; env(&#39;SESSION_LIFETIME&#39;, 120),
    
        &#39;expire_on_close&#39; =&gt; 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.
        |
        */
    
        &#39;encrypt&#39; =&gt; 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.
        |
        */
    
        &#39;files&#39; =&gt; storage_path(&#39;framework/sessions&#39;),
    
        /*
        |--------------------------------------------------------------------------
        | Session Database Connection
        |--------------------------------------------------------------------------
        |
        | When using the &quot;database&quot; or &quot;redis&quot; 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.
        |
        */
    
        &#39;connection&#39; =&gt; env(&#39;SESSION_CONNECTION&#39;, null),
    
        /*
        |--------------------------------------------------------------------------
        | Session Database Table
        |--------------------------------------------------------------------------
        |
        | When using the &quot;database&quot; 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.
        |
        */
    
        &#39;table&#39; =&gt; &#39;sessions&#39;,
    
        /*
        |--------------------------------------------------------------------------
        | Session Cache Store
        |--------------------------------------------------------------------------
        |
        | While using one of the framework&#39;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&#39;s configured cache &quot;stores&quot;.
        |
        | Affects: &quot;apc&quot;, &quot;dynamodb&quot;, &quot;memcached&quot;, &quot;redis&quot;
        |
        */
    
        &#39;store&#39; =&gt; env(&#39;SESSION_STORE&#39;, 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.
        |
        */
    
        &#39;lottery&#39; =&gt; [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.
        |
        */
    
        &#39;cookie&#39; =&gt; env(
            &#39;SESSION_COOKIE&#39;,
            Str::slug(env(&#39;APP_NAME&#39;, &#39;laravel&#39;), &#39;_&#39;).&#39;_session&#39;
        ),
    
        /*
        |--------------------------------------------------------------------------
        | 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.
        |
        */
    
        &#39;path&#39; =&gt; &#39;/&#39;,
    
        /*
        |--------------------------------------------------------------------------
        | 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.
        |
        */
    
        &#39;domain&#39; =&gt; env(&#39;SESSION_DOMAIN&#39;, 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&#39;t be done securely.
        |
        */
    
        &#39;secure&#39; =&gt; env(&#39;SESSION_SECURE_COOKIE&#39;),
    
        /*
        |--------------------------------------------------------------------------
        | 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.
        |
        */
    
        &#39;http_only&#39; =&gt; 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 &quot;lax&quot; since this is a secure default value.
        |
        | Supported: &quot;lax&quot;, &quot;strict&quot;, &quot;none&quot;, null
        |
        */
    
        &#39;same_site&#39; =&gt; &#39;lax&#39;,
    
    ];



</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();
英文:
  1. Go to the App/Http/Kernel.php file.
  2. Add this line \Illuminate\Session\Middleware\StartSession::class, into the $middleware array. Please check the below screenshot.

“Laravel 8: Session does not apply” 可以翻译为 “Laravel 8:会话不生效”。

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(&#39;key&#39;, $array);
//or
session()-&gt;push(&#39;key&#39;, $array);

-- Store Session By a Key

Session::put(&#39;session_key&#39;, &#39;value&#39;);
//or
session([&#39;key&#39;=&gt;&#39;value&#39;]);

-- Retrieving Session By Key

Session::get(&#39;key&#39;);
//or
session(&#39;key&#39;);

-- Get All Data From The Session

Session::all();
//or
session()-&gt;all();

huangapple
  • 本文由 发表于 2023年5月7日 13:38:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192350.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定