当从控制器Laravel 10传递变量时,刀片中的变量未定义

m3eecexj  于 2023-03-31  发布在  其他
关注(0)|答案(4)|浏览(83)

所以我想从modelcontroller返回一些字符串,但它总是说undefined变量,尽管当我用dd($a)dd($b)检查它时,它成功通过了。我做错了什么?
about.blade:

@extends('layout.template');
@section('homeContainer');

<p> {{ $a }} </p>
<br>
<p>{{ $b }}</p>
@endsection

AboutController :

<?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'));
    }
}

AboutModel :

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

Routes :

<?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(),
    ]);
});
gajydyqb

gajydyqb1#

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

hsgswve4

hsgswve42#

路由声明不正确。路由无法将渲染的刀片代码作为返回响应处理。请检查web.php文件的以下代码。

<?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', [AboutController::class, 'info'])->name("info");

休息守则很好。对你有用。

bmp9r5qi

bmp9r5qi3#

web.php中,您应该编写以下代码:

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

wgmfuz8q4#

谢谢你的回复!,原来我是错误的声明模型为变量和路由,
我改的路线

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

对于控制器和模型,我删除了静态变量并更改了模型声明
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;
    }

相关问题