gpt4 book ai didi

php - undefined variable Laravel 4.1

转载 作者:行者123 更新时间:2023-11-29 13:02:28 25 4
gpt4 key购买 nike

我正在尝试从数据库获取数据并将值传递给 Controller ​​。我是 Laravel 的新手,这是第一个查询。这是我的代码:

class Cars extends Eloquent
{


}

FleetController.php

public function index()
{
$fleet = Cars::all()->first()->Description;
return View::make('pages.home')->with('fleet', $fleet);
}

home.blade.php

@extends('layouts.default')
@section('content')
{{ $fleet }}
@stop

问题是它在日志中显示了这一点

下一个带有消息的异常“ErrorException

'Undefined variable: fleet (View: C:\wamp\www\laravel\app\views\pages\home.blade.php)' in C:\wamp\www\laravel\app\storage\views\7da5cff457f71f3156f90053865b6cb1:2
Stack trace:

最佳答案

你应该尝试使用

@if(Session::has('fleet'))
{{Session::get('fleet')}}
@endif

您的“->with()”只是将变量闪烁到您的 session 中。不过,您仍然需要从那里检索它。

此外,您应该尝试创建一个与表同名的模型。如果您要创建一个扩展 Eloquent 的汽车模型,它将自动链接到您的 Cars 表。 Laravel 文档:

The lower-case, plural name of the class will be used as the table name unless another name is explicitly specified.

这部分也很重要:

Eloquent will also assume that each table has a primary key column named 'id'.

配置完成后,您将能够通过简单的操作来获取汽车的描述

Car::all()->first()->description;

另请参阅:Laravel docs on eloquent

更新

什么应该有效:

Car.php

class Car extends Eloquent{
//Let's try setting these manually. Make sure they are correct.
protected $table = 'cars';
protected primaryKey = 'id';
}

FleetController.php

public function index()
{
//You have to call the model here, so singular 'Car'.
$fleet = Car::all()->first()->Description;
return View::make('pages.home')->with('fleet', $fleet);
}

home.blade.php

@extends('layouts.default')
@section('content')
//You can use blade's @if as well:
@if(Session::has('fleet'))
{{Session::get('fleet')}}
@endif
@stop

关于php - undefined variable Laravel 4.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23156378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com