search

Home  >  Q&A  >  body text

How to create button click counter in Laravel

I am new to Laravel. Currently I'm trying to create a button that when clicked adds a value to the name or $_POST value.

In plain PHP I can do this using $_SESSIONs:

session_start();

// if counter is not set, set to zero
if(!isset($_SESSION['counter'])) {
    $_SESSION['counter'] = 0;
}

// if button is pressed, increment counter
if(isset($_POST['button'])) {
      $_SESSION['counter'];
}

// reset counter
if(isset($_POST['reset'])) {
    $_SESSION['counter'] = 0;
}

?>

<form method="POST">
    <input type="hidden" name="counter" value="<?php echo $_SESSION['counter']; ?>" />
    <input type="submit" name="button" value="Counter" />
    <input type="submit" name="reset" value="Reset" />
    <br/><?php echo $_SESSION['counter']; ?>
</form>

However, I don't know how to do this in Lavel. Is there any documentation on how to do something like this?

P粉226413256P粉226413256279 days ago435

reply all(1)I'll reply

  • P粉041881924

    P粉0418819242024-02-27 00:43:29

    There are many ways to do this using Laravel. One of them is as follows:

    Send (GET/POST) request is made when the user clicks the desired button.

    You can get whatever is sent via the request() helper function, so in a simple controller we can have:

    request()->session()->increment('count');
    

    There is no need to use the request() method, the session can be accessed directly through the session() helper function (or Session Facade).

    Additionally, displaying the results on a simple blade.php page might look like this:

    @if(Session::has('count'))
    <span>
      {{ Session::get('count')}}
    </span>
    @endif
    

    You can increment and decrement the session value in .

    reply
    0
  • Cancelreply