Laravel - 将变量从一个函数传递给另一个函数

时间:2021-03-24 13:08:51

标签: php laravel controller

问题很简单,我想做的就是使用另一个函数中的变量,但它没有被识别。

任何帮助将不胜感激。

控制器:

/GL

2 个答案:

答案 0 :(得分:1)

让第二个函数返回你想要的值:

public function index()
    {
      $users=  $this->getAllUsers();
        return view('home')->with('users', $users);
    }

    public function getAllUsers()
    {
        return User::get();
    }

答案 1 :(得分:1)

您正在调用 getAllUsers 方法,但并未将其存储在变量中。此外,getAllUsers 方法应该return 所有用户。

public function index()
{
    //Store it in the $users variable.
    $users = $this->getAllUsers();
    return view('home')->with('users', $users);
}

public function getAllUsers()
{
    return User::get();
}