Question

I am trying to get data from database and pass values to controller. I am new at laravel and thats the first query. Here is my code:

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

The problem is that it shows this at log

Next exception 'ErrorException' with message

'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:
Was it helpful?

Solution

You should try using

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

Your '->with()' just flashes the variable to your session. You still need to retrieve it from there though.

Also, you should try creating a model with the same name as your table. If you were to create a model Car that extends Eloquent, it will automatically be linked to your Cars table. Laravel docs:

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

This part is important as well:

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

Once you got that configured, you'll be able to get the description of a car by simple doing

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

See also: Laravel docs on eloquent

Update

What should work:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top