Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access cookie from view in PHP Laravel 5

Tags:

php

laravel-5

I can access cookie in controller then pass it to view

//HomeController.php
public function index(Request $request)
{
  $name = Cookie::get('name');
  return view('index', ['name'=> $name]);
}

But I want to write a small control (widget) that can fetch data from cookie without concern of parent controller. For example, header, footer widgets could fetch its own data without main page controller knowing which data is needed.

I can query the data from database by using View Composer. But, how can I access data from view in the request cookie ?

like image 935
Momo Avatar asked Mar 20 '16 12:03

Momo


2 Answers

Using static function with defining namespace and etc is a not safe.

Cuz maybe in next versions of framework this namespace can change.

It's better to use helper functions.

{{ request()->cookie('laravel_session') }}

or

{{ cookie('laravel_session') }}

Tested on working app with Laravel 5.2

like image 181
num8er Avatar answered Sep 19 '22 00:09

num8er


You can use {{ Cookie::get('laravel_session') }} to print out the cookie inside your view.

like image 24
Steffo Dimfelt Avatar answered Sep 23 '22 00:09

Steffo Dimfelt