Home  >  Q&A  >  body text

Variable in blade is undefined when passing variable from controller Laravel

<p>So I want to return some string from <code>model</code> and <code>controller</code> but it always says undefined variable, although when I use <code> When checked with dd($ it successfully passes a)</code> and <code>dd($b)</code>. What did i do wrong? </p> <p><code>about.blade:</code></p> <pre class="brush:php;toolbar:false;">@extends('layout.template'); @section('homeContainer'); <p> {{ $a }} </p> <br> <p>{{ $b }}</p> @endsection</pre> <p><code>About the controller:</code></p> <pre class="brush:php;toolbar:false;"><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\AboutModel; class AboutController extends Controller { // public static function info(){ $a = AboutModel::info(); $b = "This data is from controller"; return view('about', compact('a', 'b')); } }</pre> <p><code>About the model:</code></p> <pre class="brush:php;toolbar:false;"><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class AboutModel extends Model { use HasFactory; public static function Info(){ $a = "This value is from model"; return $a; } }</pre> <p><code>Directions: </code></p> <pre class="brush:php;toolbar:false;"><?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\AboutController; /* |------------------------------------------------- ----------------------- | Web Routes |------------------------------------------------- ----------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "web" middleware group. Make something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/about', function () { return view('about', [ "name" => AboutController::info(), ]); });</pre></p>
P粉056618053P粉056618053437 days ago453

reply all(2)I'll reply

  • P粉111641966

    P粉1116419662023-09-01 14:48:55

    The controller never runs, only the callbacks in the web.php file. This means you don't have a and b variables, only a name variable

    reply
    0
  • P粉194919082

    P粉1949190822023-09-01 11:02:49

    thank you for your reply! Turns out I mistakenly declared the model as a variable and a route,

    For the route I changed it to

    Route::get('/about',[AboutController::class,'info']);

    For controllers and models I remove the static and change the model declaration

    Controller:

    public function info()
        {
            $model = new AboutModel();
            $a = $model->Info();
            $b = "This data is from controller";
    
            return view('about', compact('a', 'b'));
        }

    model:

    public function Info(){
            $a = "This value is from model";
            return $a;
        }

    reply
    0
  • Cancelreply