Select all from table with Laravel and Eloquent

RSM picture RSM · Feb 19, 2014 · Viewed 194.9k times · Source

I am using Laravel 4 to set up my first model to pull all the rows from a table called posts.

In standard MySQL I would use:

SELECT * FROM posts;

How do I achieve this in my Laravel 4 model?

See below for my complete model source code:

<?php

class Blog extends Eloquent 
{

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'posts';

    public function getAllPosts()
    {

    }

}

Answer

Sturm picture Sturm · Feb 19, 2014

You simply call

Blog::all();

//example usage.
$posts = Blog::all();

$posts->each(function($post) // foreach($posts as $post) { }
{
    //do something
}

from anywhere in your application.

Reading the documentation will help a lot.