Search code examples
phplaravelmodel-view-controllerlaravel-8laravel-7

Laravel 8 sending data from controller to blade


Hey i need to send data from my controller to view. Following is Route code when user type

http://127.0.0.1:8000/About a controller will be activated. But an error is thrown and I have no clue what to do. Any hint or solution will be welcomed :)

Following is the code

Route

Route::get('About','App\Http\Controllers\Users@about');

Controller

<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class Users extends Controller
{
    public function about(){
        $name = "Tony Stack";
        return view('aboutus')->with('name', $name);
    }
}

Blade Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>About Us page</h1>
    <?php echo $name;?>
 <br>   
    <br> <br>
    <a href="About">About Us</a> <br>
    <a href="Contact"> Contact</a><br>
    <a href="/"> HOME</a>
    
</body>
</html>

Error

ErrorException
Undefined variable: name (View: C:\xampp\htdocs\storify\resources\views\aboutus.blade.php)
http://127.0.0.1:8000/About

Solution

  • Use this

    return view('aboutus', compact('name'));
    

    Here in compact's parameter you have to pass variable name without $ sign in qoutes. Then in blade file you can access the passed value like $name