John Davidson

php - Laravel - Passing a variable from a function to another function


The question is pretty simple, all I want to do is to use a variable from another function, but it doesn't get recognized.

Any help would be appreciated.


public function index()
return view('home')->with('users', $users);

public function getAllUsers()
$users = User::get();

My Answer:
> One way to pass a variable from one function to another in Laravel is to store the variable in a class property and then access it in the other function. Here's an example:

class YourController extends Controller
private $yourVariable;

public function index()
$this->yourVariable = 'your value';

public function anotherFunction()
// Access the variable here
echo $this->yourVariable;

In this example, the `yourVariable` is stored in a class property and set in the `index` function. It can then be accessed in the `anotherFunction` function using `$this->yourVariable`.

Make sure to define the class property at the top of your controller class and use `$this->yourVariable` to access it in other functions within the same class.

Rate this post

3 of 5 based on 8573 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us