Laravel 如何设置来自自己的会话 table 并显示以供查看

Laravel how to set session from own table and display to view

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

我想使用 table 数据设置会话,然后在视图中显示它。以前,当我使用原生 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

感谢您的建议和帮助

要在 Laravel 中创建会话,您可以使用此函数:

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

在您的代码中,类似于

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

通过请求实例

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

终于找到答案了:

    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('/');
        } 
}