Search code examples
phplaravelcontrollerphp-carbon

How pass $variables for all functions with constructor in controller (Laravel)


i would like pass a variable in another function, i use __construct function for it, but my browser return "Unresolvable dependency resolving [Parameter #0 [ $startingAt ]]". Thanks for your help !

My Controller :

protected $startingAt;


public function __construct($startingAt)
{
    $this->startingAt = $startingAt;
}

public function index()
{
    return view('index');
}

public function startingAt()
{
    $this->startingAt = Carbon::now();
    return $this->startingAt;
}

My blade.pĥp:

<form action="{{ route('starting.race') }}" method="POST">
    {{ csrf_field() }}
    @method('post')
    <button class="bg-indigo-600 text-white font-bold px-3 rounded-full" type="submit" name="submit">Start</button>
</form>

My web.php :

Route::get('/', [\App\Http\Controllers\CarbonController::class, 'index'])->name('index.race');

Route::post('/start', [\App\Http\Controllers\CarbonController::class, 'startingAt'])->name('starting.race');

Solution

  • just call the function you made to fill the variable in your constructor and remove the parameter $startingAt from the contructor method.

    public function __construct()
    {
        $this->startingAt();
    }