從控制器 Laravel 傳遞變數時,blade 中的變數未定義
P粉056618053
2023-08-31 15:58:04
<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>
控制器從不執行,僅執行 web.php 檔案中的回呼。 這意味著你沒有 a 和 b 變量,只有一個 name 變數
感謝您的回覆!事實證明我錯誤地將模型宣告為變數和路線,
對於我將其更改為的路線
對於控制器和模型,我刪除靜態並更改模型聲明
控制器:
型號: