How to access cookie from view in PHP Laravel 5 - php

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 ?

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

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

You can use
{{\Illuminate\Support\Facades\Cookie::get('laravel_session')}}
in a blade template

You can use:
$response = new \Illuminate\Http\Response(view('your_view'));
$response->withCookie(cookie('cookieName' , 'cookieValue' , expire));
return $response;
or
\Cookie::queue('cookieName', 'cookieValue', expire);
return view('your_view');
I've used both of them.

Related

How do I use a controller for a "partial" view in Laravel?

Here is my situation. I have a layout.blade.php which most of my pages use. Within this file, I have some partial pieces that I include, like #include('partials.header'). I am trying to use a controller to send data to my header.blade.php file, but I'm confused as to exactly how this will work since it is included in every view that extends layout.blade.php.
What I am trying to do is retrieve a record in my database of any Game that has a date of today's date, if it exists, and display the details using blade within the header.
How can I make this work?
I think to define those Game as globally shared is way to go.
In your AppServiceProvider boot method
public function boot()
{
view()->composer('partials.header', function ($view) {
view()->share('todayGames', \App\Game::whereDay('created_at', date('d')->get());
});
// or event view()->composer('*', Closure) to share $todayGames accross whole blade
}
Render your blade as usual, partial.header blade
#foreach ($todayGames as $game)
// dostuffs
#endforeach
In Laravel you can create a service class method that acts like a controller and use #inject directive to access this in your partial view. This means you do not need to create global variables in boot(), or pass variables into every controller, or pass through the base view layout.blade.php.
resources/views/header.blade.php:
#inject('gamesToday', 'App\Services\GamesTodayService')
#foreach ($gamesToday->getTodayGames() as $game)
// display game details
#endforeach
While it's different value you retrieved belong of the game chosen, you can do something like that:
Controller
$data = Game::select('id', 'name', 'published_date')->first();
return view('game')->with(compact('data'));
layout.blade.php
<html><head></head><body>
{{ $date }}
</body></html>
game.blade.php
#extend('layout')
#section('date', $data->date)
#section('content')
#endsection
The better solution would be this
Under your app folder make a class named yourClassNameFacade. Your class would look like this.
class yourClassNameFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'keyNameYouDecide';
}
}
Then go to the file app/Providers/AppServiceProvider.php and add to the register function
public function register()
{
$this->app->bind('keyNameYouDecide', function (){
//below your logic, in my case a call to the eloquent database model to retrieve all items.
//but you can return whatever you want and its available in your whole application.
return \App\MyEloquentClassName::all();
});
}
Then in your view or any other place you want it in your application you do this to reference it.
view is the following code:
{{ resolve('keyNameYouDecide') }}
if you want to check what is in it do this:
{{ ddd(resolve('keyNameYouDecide')) }}
anywhere else in your code you can just do:
resolve('keyNameYouDecide'))

How to allow $user variable in a blade view page in Laravel?

I have this page support.blade.php in views folder and I'm using Laravel.
I can't echo out $user->id or $user[id] in this page and I get undefined variable error. It's possible to echo it out in other pages, like in tickets.blade.php but in this specific page it's not working.
How can I fix this?
Within your Service Provider you can use
View::share('key', 'value')
You can consult the docs for a more indepth explanation.
You need to pass the data first from controller method:
return view('support', ['user' => $user]);
If you want to display ID of an authenticated user, you can do this from any part of the app without passing data from controller method:
{{ auth()->user()->id }}
Did you pass data in view file??
return view('support', ['user' => $user]);

Slim Framework passing data to Twig view

I'm trying to build a page in Slim that will bring up a subscribers details. I've worked out how to create the route and the relevant method in the controller which all works correctly. I'm using Twig for the views and can't work out how I would access the subscriber from the view.
Route
$app->get('/subscriber/{id}', 'SubscriberController:getSubscriber');
Subscriber controller
public function getSubscriber($request, $response, $args)
{
$subscriber = Subscriber::where('id', $args['id'])->first();
}
I've been using the below in my controller to render my Twig templates
return $this->container->view->render($response, 'subscriber.twig');
How would I pass in or access my subscriber variable in the Twig template? I can't work out how to pass it through?
On the render method the 3. parameter is data where you can give the twig template variables.
$data = ['subscriber' => $subscriber];
return $this->container->view->render($response, 'subscriber.twig', $data);
now you can access this variable inside twig.

return back() in Laravel without session params

I have this code in a project with Laravel 5:
return back()->with('msg_ok','successfully sent');
The param msg_ok is pushed in Session, but I´m not want use session params, I want pass the msg_ok parameter as variable.
For example I want print this en my blade file:
{{ $msg_ok }}
Laravel back() function will always return data in a Session. Normally you can't return variable with back() function. You have to use view() function for that.
Alternate Solution
You can use keep() function for storing data in session like variable. Which will not be flushed after refresh.
e.g
$request->session()->keep(['username', 'email']);
and then get data with key.
Laravel back() will redirect you back from the form where it is submitted,
and back()->with('msg_ok', 'successfully..');
if you place an item inside back()->with(); it will automatically place the value
inside session.
You can use return redirect()->to('url/path?msg_ok=successfully') add the query string parameter to url to pass it as variable.
and then on the controller where you have been redirected inject the Reqest class to your method
e.g
public function index(Request $request) {
$msg_ok = $request->get('msg_ok', '');
return view('view.blade', compact('msg_ok'));
}
Place the variable string inside the compact to make it accessible to your view.
You can just use Session::get('msg_ok') in your blade file. Or pass the variable to the view explicitly, in controller, like
return view()->make('view', ['msg_ok' => session()->get('msg_ok')]);

How to access session in blade before request

I have an admin template which I builded with blade templates,including one another.The user request is extending the main blade and returning only the content.
However in the template I have stuff like - user messages(count),theme options etc.
These things must be saved in the user session.Cookies are not an option.
The question is how to do it in the best possible option.
I'm thinking of gettind the request in middleware and accessing the session there.After that I must pass the data to the blade templates (not the final extending one).
Whats your opinion ?! Thanks!
If I understand correctly, you have a main layout blade template that is later extended by the user view returned by the controller.
No additional code like you described is needed. Both user and layout templates are processed after controller action is executed and both have access to user session via session() helper and user object via Auth::user().
So the following sample code should work for you :
// SomeController
public function someAction() {
return return response()->view('user');
}
// main.blade.php
#if (Auth::check())
Show this text only to authenticated users
#endif
Value of session parameter is {{ session('parameter_name') }}
// user.blade.php
#extends('main')

Categories