Hathaway's avatar

Simple Laravel Counter between routes?

I would like to create a counter which counts visited pages for each user. The counter should still increase between different routes!

namespace App\Repositories;

class CounterRepository
{
    protected $_times = 0;
    public $message = "Hello World!  We've met %d times!";

    public function sayHello()
    {        
        echo sprintf($this->message, $this->_times);
        $this->_times++;
    }
}
namespace App\Providers;

use App\Repositories\CounterRepository;
use Illuminate\Support\ServiceProvider;

class CounterProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        echo "boot ";
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        echo "register ";


        $this->app->bind('Counter', 'App\Repositories\CounterRepository', true);
    }
}

I tried to do it with Laravel Shared Services. But every time the route is changing, the counter starts at 0.

0 likes
4 replies
tomopongrac's avatar

Why don't you use session for pass count number between routes

1 like
Hathaway's avatar

Because honestly, I need this solution for another class (which is more complex; API Client) and I would like to build one object per session.

Is it possible to store one object (900 lines of code) inside a session?

Please or to participate in this conversation.