LARAVEL

Laravel Passing variables from controllers to views


In Laravel, you can pass variables from controllers to views within the context of a route. Here's how you can achieve this:

1.  Define a Route:

Open your routes/web.php file and define a route that points to a specific controller method.

Example : 

// routes/web.php

use App\Http\Controllers\YourController;

Route::get('/your-route', [YourController::class, 'yourControllerMethod']);

 

2. Controller Method:

Inside your controller method, you can create variables and pass them to the view

Example :

// app/Http/Controllers/YourController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class YourController extends Controller
{
    public function yourControllerMethod()
    {
        $data = [
            'title' => 'Welcome to My Website',
            'content' => 'This is the content of the page.',
        ];

        return view('your.view', $data);
    }
}

In this example, an associative array $data is created, and it's passed to the view.

 

3. View:

Inside your view, you can access the variables using Blade syntax. 

Example :

{{-- resources/views/your/view.blade.php --}}

<html>
<head>
    <title>{{ $title }}</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>{{ $content }}</p>
</body>
</html>

The variables $title and $content are directly accessible in the view.

4. Access the Route: 

Now serve your application , after that you navigate to http://127.0.0.1:8000/your-route in your browser, 

Example :

php artisan serve

 


LARAVEL