How to define variable in controller in laravel?

by lindsey.homenick , in category: PHP Frameworks , 7 months ago

How to define variable in controller in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 7 months ago

@lindsey.homenick 

In Laravel, you can define variables in a controller by declaring them within a method in the controller class. Here's an example of how you can define a variable in a Laravel controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
namespace AppHttpControllers;

use IlluminateHttpRequest;

class UserController extends Controller
{
    public function index()
    {
        $name = 'John Doe';
        $age = 30;

        return view('user.index', compact('name', 'age'));
    }
}


In the example above, we have defined two variables - $name and $age - within the index method of the UserController class. We then pass these variables to a view using the compact function, which creates an associative array where the variable names are the keys.


You can then access these variables in the corresponding view file using the variable names. For example, in the user/index.blade.php view file:

1
2
<p>Name: {{ $name }}</p>
<p>Age: {{ $age }}</p>


This will output:

1
2
Name: John Doe
Age: 30