M
M
MSAFT2019-03-14 13:18:04
Laravel
MSAFT, 2019-03-14 13:18:04

How to catch session data in Laravel controller?

On the site I write functionality for working with several regions.
View:

@if(session()->has('city'))
        {{ session('city') }}       

        @else
            {{session(['city' => 'Base City'])}} //если пользователь впервые зашел на сайт, ставит базовый город
            {{ session('city') }}

        @endif

The controller where the session is established via route and everything works afterwards:
public function set(Request $request)
    {

        $city = $request->get('city'); //забирает данные установленные во вьюшке

        session()->put('city', $city); //ставит обновленные данные в сессию

        if (session()->has('city')) {

            return redirect()->back();
        }
            echo 'Some kind of bug with the sessions of the cities';

    }

Now I need to call a session in another controller in order to issue the necessary offers in accordance with the city, however, as I don’t do it, it returns null . I
tried it like this: So: But it still shows null in the debugger. What am I doing wrong?
$region = session('city');
$region = session()->get('city');

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
backEndDeveloper, 2019-03-14
@MSAFT

Why are you writing logic in views?
I would bring such general logic to the middleware level

public function handle($request, Closure $next)
{
$request->session()->get('city', 'default');
/* логика с переменной $city */
    view()->share(['city' => $city]); 

    return $next($request);
}

Then you will immediately see {{ city }}

A
Arthur, 2019-03-14
@ART_CORP

use Session;

Session::get('city');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question