如何在控制器中使用构造函数为所有函数传递 $variables (Laravel)

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

我想在另一个函数中传递一个变量,我为此使用 __construct 函数,但我的浏览器 return “无法解析的依赖项解析 [参数 #0 [ $startingAt ]]”。感谢您的帮助!

我的控制器:

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;
}

我的 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>

我的 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');

只需调用您创建的函数来填充构造函数中的变量,并从构造函数方法中删除参数 $startingAt

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