In Laravel, you can pass variables from controllers to views within the context of a route. Here's how you can achieve this:
Open your routes/web.php file and define a route that points to a specific controller method.
// routes/web.php
use App\Http\Controllers\YourController;
Route::get('/your-route', [YourController::class, 'yourControllerMethod']);
Inside your controller method, you can create variables and pass them to the view.
// 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.
Inside your view, you can access the variables using Blade syntax.
{{-- 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.
Now serve your application , after that you navigate to http://127.0.0.1:8000/your-route in your browser,
php artisan serve