Search code examples
phpmysqllaravellaravel-4eloquent

Select all from table with Laravel and Eloquent


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()
    {

    }

}

Solution

  • 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.