所以我想从model和controller返回一些字符串,但它总是说未定义的变量,尽管当我用dd($检查时它成功通过了a) 和 dd($b)。我做错了什么?
about.blade:
@extends('layout.template');
@section('homeContainer');
<p> {{ $a }} </p>
<br>
<p>{{ $b }}</p>
@endsection
关于控制器:
<?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'));
}
}
关于模型:
<?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;
}
}
路线:
<?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(),
]);
}); Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
控制器从不运行,仅运行 web.php 文件中的回调。 这意味着你没有 a 和 b 变量,只有一个 name 变量
感谢您的回复!事实证明我错误地将模型声明为变量和路线,
对于我将其更改为的路线
Route::get('/about',[AboutController::class,'info']);对于控制器和模型,我删除静态并更改模型声明
控制器:public function info() { $model = new AboutModel(); $a = $model->Info(); $b = "This data is from controller"; return view('about', compact('a', 'b')); }型号:public function Info(){ $a = "This value is from model"; return $a; }