1

I am working through the Laravel 4 From Scratch tutorial at https://laracasts.com/series/laravel-from-scratch. Tutorial 4: Database Access describes several methods for retrieving data from a database.

One in particular I cannot get to work:

In my routes.php, I have

Route::get('/', function()
{
  $bottle = DB::table('bottle')->find(1);
  dd($bottle);
});

The only output is the "Whoops, looks like something went wrong." page. In the bottle table of my database, the primary key has the name bottle_ID. I would guess this has something to do with the problem, but I cannot find any information on how to change the find() parameter. So how do I use 'find' to return an object from my database?

The following code does work:

// returns everything from bottle table
$bottles = DB::table('brewery')->get();
return $bottles;

// returns all data for the bottle with an ID of 10
$bottle = DB::table('bottle')->where('bottle_ID', '=', 10)->get();
return $bottle;

// returns all ales from the database
$bottles = DB::table('bottle')->where('beer_type', '=', 'Ale')->get();
return $bottles;

1 Answer 1

3

When used in the query builder (DB::table()...) the find() method has the primary key column hardcoded as id:

public function find($id, $columns = array('*'))
{
    return $this->where('id', '=', $id)->first($columns);
}

What you should do instead is use where() and first():

$bottle = DB::table('bottle')->where('bottle_ID', 1)->first();

Or if you decide to use Eloquent Models you can specify the key column name:

class Bottle extends Eloquent {
    protected $primaryKey = 'bottle_ID';
}

And retrieve the model like this:

$bottle = Bottle::find(1);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I tried both of your suggestions and got both of them to work! It looks like I was on the right track in suspecting my column names, but I really had no idea what to do about it. I had previously been investigating MAMP / Laravel configuration issues, but that was a dead end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.