Steve
Steve

Reputation: 1672

Storing details in cookie

How can i store the user information in cookie. I have this form:

<form action="{{url('/Profile/details')}}"  method="POST">
{!!csrf_field()!!}  
<input type="text" name="name" class="form-control"><br>
<select name="rate" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="submit" class="form-control" value="Vote"> 
</form>

I don't really want to store these information in the database, rather want to store in Cookie, so that i can later retreive these values. i.e. name and rate. I've tried to retreive using:

$value = Request::cookie('name');
echo $value;

but it displayed:

Non-static method Illuminate\Http\Request::cookie() should not be called statically

Upvotes: 1

Views: 78

Answers (1)

Saumya Rastogi
Saumya Rastogi

Reputation: 13709

You can store these information in session() or cookie() like this:

class HomeController extends Controller
{
    // Store using sessions like this:
    public function index()
    {
        $inputs = request()->all();

        // Store it in session with key-pair values retrieved from the form
        session($inputs);

        // Retrieve session values by name (key - value pairs)
        session()->pull('key', 'default_value');
    }

    // Or by using cookies like this:
    public function index()
    {
        $inputs = request()->all();

        // Creates cookie instance
        $minutes = 60;
        $cookie = cookie('name', $inputs['value'], $minutes);
        return response('Hello World')->cookie($cookie);
    }
}

If you would like to generate a Symfony\Component\HttpFoundation\Cookie instance that can be given to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance

Hope this helps!

Upvotes: 2

Related Questions