搜索

首页  >  问答  >  正文

从控制器 Laravel 传递变量时,blade 中的变量未定义

<p>所以我想从<code>model</code>和<code>controller</code>返回一些字符串,但它总是说未定义的变量,尽管当我用<code>dd($检查时它成功通过了a)</code> 和 <code>dd($b)</code>。我做错了什么?</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>关于控制器:</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>关于模型:</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>路线:</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粉056618053439 天前458

全部回复(2)我来回复

  • P粉111641966

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

    控制器从不运行,仅运行 web.php 文件中的回调。 这意味着你没有 a 和 b 变量,只有一个 name 变量

    回复
    0
  • P粉194919082

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

    感谢您的回复!事实证明我错误地将模型声明为变量和路线,

    对于我将其更改为的路线

    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;
        }

    回复
    0
  • 取消回复