Saturday 15 October 2016

Creating And Retrieving Laravel Cookies In controller

Creating  cookies using controllers functions in laravel is pretty simple and straight forward. most times i like creating and getting cookies with oop functions than do it procedurally. 
First of it all, Create a controller using this artisan command
"php artisan make:controller myCookie" without quote.
then, make sure the namespace and packages are similar to the below script.

<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
class posting extends Controller
{

}

to create a cookies with controller, create a functions like this

public function createCookie(Request $response, $key)
    {
return Cookie::queue('country',$key);
}

you can change the function name, the cookies name as well. be aware the first parameter allow to create the cookies, while the $key parameter is the value that will be stored by cookies.
to get a cookies create function like the script below.

public function getCookie(Request $request)
{
    return $request->cookie('country');
}
you can also change the function name and cookies name as well.
if you are familiar with oop and also knows how to call functions to perform their individual task the rest is simple as calling the createCookies and getCookies functions. 

lets assume we want to call the laravel cookies functions to create their own indivicual task. the below script demonstrate it. 

public function index(Request $request){
$val  = ‘Ehis’;
  $c = $this->createCookie($request, $val);
  Return $cp = $this->getCookie();
}

the above index function call on individual functions to do their jobs based on oop way. to check the workabilty of the above script, you should know how to route to a function, you need to route to index functions to return the cookies values, or you can pass the value to views. 



No comments:

Post a Comment