how to use cookie in laravel 5.4 to store data - php

i am creating a website which needs to store user info and save to cookie.
here is my get cookie controller
public function index($id, Request $request)
{
$petitions = Petitions::where('id',$id)->first();
$sign->name = $request->cookie('name');
$sign->email = $request->cookie('email');
return view('petitions.index', compact('petitions'))->with(['name'=>$sign->name,'email'=>$sign->email]);
}
and here is set cookie controller
public function store(Request $request)
{
$sign = new ActionUsers();
$sign->name = $request->get('name');
$sign->email = $request->get('email');
$sign->job = $request->get('job');
$sign->reason = $request->get('reason');
$sign->ip_address = $request->get('ip_address');
$sign->petition_id = $request->get('petition_id');
$sign->is_anonymous = $request->get('is_anonymous');
$sign->save();
$name_cookie = cookie('name', $sign->name, 30);
$email_cookie = cookie('email', $sign->email, 30);
return back()->withCookie($name_cookie,$email_cookie);
}
my view to check cookie existed
#if( isset($sign->name) && isset($sign->email) )
done!
#else Oops! Error
and return error Creating default object from empty value in $sign->name = $request->cookie('name');
$sign->email = $request->cookie('email');
anyone help me solve that! thank you

Try return in store function as :
return back()->withCookie($name_cookie)->withCookie($email_cookie);

There are several ways to do this:
$response = new \Illuminate\Http\Response(view('your_view'));
$response->withCookie(cookie('cookieName' , 'cookieValue' , expires_in_minutes));
return $response;
or
\Cookie::queue('cookieName', 'cookieValue', expires_in_minutes);
return view('your_view');
you can also use this code to get cookies :
$request->cookie('coockieName');

Related

Laravel Cookie returns null

I am new to Laravel (version 8) and i am trying to figure out why my cookie is returning a null. I am setting up the cookie like this'
public function setCookies($value){
$minutes = 60;
$response = new Response('Hello World');
$response->withCookie(cookie('name', $value, $minutes));
return $response;
}
where $value is the string value of the cookie
and i am trying to get the cookie with this method
public function getCookies(Request $request) {
$value = $request->cookie('name');
return $value;
}
but the return value is always null. please let me know where i am going wrong
here are my routes
Route::get('/cookie/set','App\Http\Controllers\Cont#setCookies');
Route::get('/cookie/get','App\Http\Controllers\cont#getCookies');
you have to change code to this :
public function setCookie(Request $request){
$minutes = 60;
$response = new Response('Set Cookie');
$response->withCookie(cookie('name', 'MyValue', $minutes));
return $response;
}
You need to change the route to accept dynamic value.
If you're sending values from url, then set the route to
Route::get('/cookie/set/{value}','App\Http\Controllers\Cont#setCookies');

Laravel Redirecting to a route is not working?

I am new to Laravel, when I am using redirect()->route('route_name') after saving data, it does not work.
Here is my controller function:
public function store_layouts(Request $data){
$layout = new point_prizes();
$layout->name = $data->name;
$layout->points = $data->points;
$layout->prize = $data->price;
$layout->timestamps = false;
$layout->save();
redirect()->route('view_layouts');
}
Here are my routes :
Route::get('/admin/layouts' , 'AdminController#view_layouts')->name('view_layouts');
Route::get('/admin/layouts/make' , 'AdminController#create_layouts')->name('create_layouts');
Route::post('/admin/layouts/store' , 'AdminController#store_layouts')->name('store_layouts');
Any help will be appreciated.
You need to add the return keyword
return redirect()->route('view_layouts');

Laravel cookies error

I'm having problems creating a cookie with laravel, the thing is that sometimes the value of this cookie changes into a null intead of its real value which makes my system give errors that I've programed to show in case this cookie dont exist.
This happens when a reaload the page, I've debugged with dd() and every time that I reload the page the value changes from'activo' to 'null' and from 'null' to 'activo', why does this happen?
My code:
public function store_inicio(Request $request)
{
$empresa_id = $request->input('empresa_id');
$empresa = Empresa::find($empresa_id);
$cierre = $empresa->inicio_caja()->orderBy('id', 'desc')->first();
if (isset($cierre)) {
if (!isset($cierre->cierre)) {
Cookie::queue('estado_caja', 'activo', 180);
Cookie::queue('numero_caja', $cierre->caja, 180);
} else {
$this->crear_inicio($request, $empresa);
}
} else {
$this->crear_inicio($request, $empresa);
}
return redirect('ventas');
}
private function crear_inicio($request, $empresa)
{
$aux_usuario = $request->input('usuario_inicio_caja');
$usuario = User::where('name', $aux_usuario)->first();
$numero_caja = $request->input('caja_inicio_caja');
$valor = $request->input('valor_inicio_caja');
$inicio_caja = new Inicio_caja();
$inicio_caja->user_id = $usuario->id;
$inicio_caja->caja = $numero_caja;
$inicio_caja->valor = $valor;
$inicio_caja->save();
$empresa->inicio_caja()->syncWithoutDetaching($inicio_caja->id);
Cookie::queue('estado_caja', 'activo', 600);
Cookie::queue('numero_caja', $numero_caja, 600);
}

Sent All Variables in Controller Function to the View

I have a function in my controller. I created a lot of variables, and send them to my view via compact function one by one.
public function edit($id,$cpe_mac) {
$vcpe = VSE::vcpe($cpe_mac);
$vcpe = json_decode (json_encode($vcpe), FALSE);
$cpe = VSE::cpe($cpe_mac);
$wan = $cpe['wan'];
$acl = $cpe['acl'];
$guest = $cpe['vlan'][0];
$private = $cpe['vlan'][1];
$cpe_name = VSE::cpe_name($cpe_mac)['cpe_name'];
$p_max_up = $private['bandwidth']['max_up'];
$p_max_down = $private['bandwidth']['max_down'];
$p_ip = $private['lan']['ip_address'];
$p_netmask = $private['lan']['netmask'];
$p_max_clients = $private['lan']['dhcp_server']['max_clients'];
$p_dns = $private['lan']['dhcp_server']['dns'][0];
$p_dns2 = $private['lan']['dhcp_server']['dns'][1];
$cpe = json_decode (json_encode($cpe), FALSE);
return view('cpe.edit', compact(['vcpe','cpe_mac','cpe_name','cpe','wan','acl','private','guest',
'p_max_up','p_max_down','p_ip','p_netmask','p_max_clients','p_dns','p_dns2'
]));
}
Question
Is there a way to send all the variables to the view rather than doing it one by one ?
You could do the following...
return view('cpe.edit', get_defined_vars());
There might be some unnecessary overhead though if you are creating a lot of variables which you would not otherwise need in your view.
To simplify you can do this
// BaseController
protected $data = array();
// Controller
$this->data = array(
'variable' => $variable,
// ...
);
return View::make('example', $this->data);
But I dont think there is more simpler way or I am not aware.
You could use an array to send all the variables to the view.

CakePHP $this->Auth->user("id") always return null?

I have a function that I use to get the user id of Auth component. It works fine without use return json_encode. The problem is that I need this works with json_encode because I get values from ajax request.
Using json_encode it always return null to id and I can't understand why does it occur. The problem is with the function indexAjax() below.
How could I use $this->Auth->user("id") with json_encode and it not return null ?
Trying.
//using $this->set it works fine
public function index() {
$id = $this->Auth->user("id");
$empresas = $this->Empresa->find('all', array(
'fields'=>array("id", "nomeFantasia", "cnpj",
"telefone1", "telefone2", "celular", "aberto"),
'conditions'=>array("users_id = "=> $id)
));
debug($id) or die;
//$this->set(compact('empresas'));
}
//with json_encode always return null
public function indexAjax() {
$this->autoRender = false;
$id = $this->Auth->user("id");
$empresas = $this->Empresa->find('all', array(
'fields'=>array("id", "nomeFantasia", "cnpj",
"telefone1", "telefone2", "celular", "aberto"),
'conditions'=>array("users_id = "=> $id)
));
return json_encode($id);
}
solved the problem. My solution was when user make login I get the user id and write in session so when I need this id I get from session directly and not from AuthComponent.
It works.

Categories