未定义的变量laravel 4.1

时间:2014-04-18 14:41:39

标签: php mysql laravel blade

我正在尝试从数据库中获取数据并将值传递给控制器​​。我是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:

1 个答案:

答案 0 :(得分:1)

你应该尝试使用

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

你的' - > with()'只需将变量闪烁到您的会话中即可。你仍然需要从那里检索它。

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

  

该类的小写复数名称将用作表格   name,除非明确指定了其他名称。

这一部分也很重要:

  

Eloquent还会假设每个表都有一个主键列   名为' 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