Laravel How to store extra data/value in session Laravel

后端 未结 5 630
我寻月下人不归
我寻月下人不归 2021-01-20 23:11

I\'m using default auth() in laravel login (email & password) Now i try to take input from the user in text field like (Age or City)

Now i want to store (Age/City) i

5条回答
  •  日久生厌
    2021-01-20 23:28

    Ok let me enlighten you. if you want to store it in session do it this way.

    session('country', $user->country); // save
    $country = session('country')`; // retrieve
    

    But that is not the way we do in Laravel like frameworks, it uses models

    once the user is authenticated each time when we refresh the page, application looks for the database users table whether the user exists in the table. the authenticated user model is a user model too. so through it we can extract any column. first thing is add extra fields to the User class(Model) $fillable array. so it would look something like this.

    User.php

    protected $fillable = ['username', 'password', 'remember_token', 'country'];
    

    so after simply logging in with user name and password in anywhere just use Request class or Auth facade. Facades are not too recommended so here for your good as a new one i would just say how to use Request. Suppose you want to retrieve your Authenticated user country inside TestController.php here is how it could be used in the methods.

    TestController.php

    use Illuminate\Http\Request;
    
    public function testMethod(Request $request)
    {
       $someCountry = $request->user()->country; //gets the logged in user country
       dd($someCountry); //dd is die and dump, could be used for debugging purposes like var_dump() method
    }
    

提交回复
热议问题