0
0
0ldn0mad2019-09-16 20:20:14
Laravel
0ldn0mad, 2019-09-16 20:20:14

How to properly set up a session in Laravel?

Good afternoon.
Please help me figure out how sessions are configured correctly in Laravel?
As an example, let's implement a page open counter. If you write a script in pure PHP in a view, then no questions asked - how would everything work:

@php
if (!isset($_SESSION['count2']))
 {
   $_SESSION['count2'] = 1;
 }
 else
 {
   ++$_SESSION['count2'];
 }
 echo "Число открытия страницы: {$_SESSION['count2']}";
@endphp

And if, let's say, I do it through the method:
public function countVisit(Request $request)
  {
    $request->session()->put('count', 1);
    $count = $request->session()->get('count');
    if(!isset($count)){
      $count = 1;
    }else{
      ++$count;
    }
    return view('form.test', ['count' => $count]);
  }

Then only a deuce is transferred to the view and that's it, nothing changes when the page is updated, since the logic remains in the method.
Show how sessions are configured between an action and a view using this counter as an example.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Sokharev, 2019-09-17
@0ldn0mad

$counter = $request->session()->get('counter', 1);
$request->session()->put('counter', ++$counter);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question