【问题标题】:Laravel how to set session from own table and display to viewLaravel如何从自己的表中设置会话并显示到视图
【发布时间】:2021-05-07 16:55:19
【问题描述】:

我一直在谷歌搜索并浏览 Laravel 文档,但没有找到解决方案。

我想通过使用表数据设置会话,然后在视图中显示它。以前,当我使用原生 PHP 时,我是这样做的:

<?php
session_start();
$query = mysqli_query($conn, "SELECT username, full_name from tbl_user WHERE username = 'john01'");
$row = mysqli_fetch_assoc($query);

$_SESSION['full_name'] = $row['full_name'];
?>

<?php echo $_SESSION['full_name'] ?>

但是在 Laravel 中,我失败了。这是我的代码:

身份验证控制器:

<?php
    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\Hash;
    use Illuminate\Support\Facades\Auth;
    use Validator;
    use Session;
    use App\User;

    class Login extends Controller
    {
    public function auth(Request $r) {
       $data = [
          'username'   => $r->input('txt_username'), //my username text_field
          'password'   => $r->input('txt_password') // my password text_field
       ];

       Auth::attempt($data);
       if(Auth::check()) {

           $data2 = DB::table('tbl_user')
                ->select('user_id','username', 'full_name')
                ->where('username', '=', $data->$r->input('txt_username'))
                ->limit(1)
                ->get();

           foreach($data2 as $a) {
               Session::put('full_name', $a->full_name);
           }

           return redirect('home', ['data' => $data2]);
       }else{
           return redirect('login');
       }
   }
?>

如果我输入错误的用户名或密码,页面将重定向到“登录”并且无法访问“主页”,但是当我点击“登录”时,我会收到此错误:

TypeError
Symfony\Component\HttpFoundation\RedirectResponse::__construct(): Argument #2 ($status) must be of type int, array given

感谢您的建议和帮助

【问题讨论】:

  • 你的意思是当你输入正确的用户名和密码时,而不是成功验证,你得到了上面提到的错误?
  • @AhmadKarimi 是的,正确。如果我注释掉查询生成器部分并在 Auth 之后键入 return redirect('home'),它将直接返回主页。但我无法在主页上回显会话。我需要为我的表(tbl_user)上的某些字段设置会话

标签: laravel session


【解决方案1】:

要在 Laravel 中创建一个 Session,你可以使用这个函数:

session(['key' => 'value']);

在您的代码中,类似于

session(['full_name' => $a->full_name]);

【讨论】:

  • 感谢您的回答,但我仍然不知道如何从表中获取“全名”值到会话
【解决方案2】:

通过请求实例

$request->session()->put('key', 'value');

【讨论】:

  • 感谢您的回答,但我仍然不知道如何将“full_name”值从表中抓取到会话中
【解决方案3】:

我终于找到了答案:

    public function auth(Request $r) {

        $username = $r->input('txt_username');
        $password = $r->input('txt_password');

        $data = DB::table('tbl_user')
                ->select('user_id', 'username', 'full_name')
                ->where('username', '=', $username)
                ->limit(1)
                ->get();
        
        if(Hash::check($password, $data[0]->password)) {
            Session::put('full_name', $data[0]->full_name);
            return redirect('home');
        }else{
            return redirect('/');
        } 
}

【讨论】:

    猜你喜欢
    • 2015-07-05
    • 2016-05-19
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多