So I want to return some string from model
and controller
, but it always says undefined variable although it passed successfully when I check it with dd($a)
and dd($b)
. What did I do wrong ?
about.blade:
@extends('layout.template');
@section('homeContainer');
<p> {{ $a }} </p>
<br>
<p>{{ $b }}</p>
@endsection
AboutController :
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsAboutModel;
class AboutController extends Controller
{
//
public static function info(){
$a = AboutModel::info();
$b = "This data is from controller";
return view('about', compact('a', 'b'));
}
}
AboutModel :
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class AboutModel extends Model
{
use HasFactory;
public static function Info(){
$a = "This value is from model";
return $a;
}
}
Routes :
<?php
use IlluminateSupportFacadesRoute;
use AppHttpControllersAboutController;
/*
|--------------------------------------------------------------------------
| 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(),
]);
});
4
Answers
Thanks for the replies!, turn out I was wrong declarating the model as variable and the routes,
for the routes I change it to
and for the controller and model I remove the static and change the model declaration
Controller :
Model :
the controller never run, only the callback in the web.php file runs.
this means you do not have a and b variables but only a name variable
Route declaration is not correct. Route can’t handle rendered blade code as return response. Please check below code for web.php file.
Rest code is fine. It will work for you.
In
web.php
, you should write the following code: