74

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

    }

}

12 Answers 12

135

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.

4
  • 12
    Be careful using ::all() as it reads everything from the table into memory. If you table has many records, you can quickly exceed PHP's memory limit that way. The solution is apparently to use Builder::cursor() or Builder::chunk().
    – beporter
    Commented Jun 21, 2017 at 13:15
  • 2
    You will get 500 error message with this Blog::all(); if you reach maximum memory limit with apache
    – Elshan
    Commented May 17, 2018 at 7:49
  • 1
    Slight update to the code there: you need closing brackets and semicolon so: $posts->each(function($post) { //do something });
    – Drewster
    Commented May 24, 2018 at 22:17
  • any comments on how to check if the $posts is empty. Commented May 8, 2020 at 5:41
54

There are 3 ways that one can do that.

1 - Use all() or get();

$entireTable = TableModelName::all();

eg,

$posts = Post::get(); // both get and all  will work here

or

$posts = Post::all();

2 - Use the DB facade

Put this line before the class in the controller

use Illuminate\Support\Facades\DB; // this will import the DB facade into your controller class

Now in the class

$posts = DB::table('posts')->get(); // it will get the entire table

or a more dynamic way would be -

$postTable = (new Post())->getTable(); // This will get the table name
$posts = DB::table($postTable)->get();

The advantage of this way is that in case you ever change the table name, it would not return any error since it gets the table name dynamically from the Post model. Make sure to import Post model at the top like DB fadade.

3 - Use the DB facade with select

Put this line before the class in the controller

*Same import the DB facade like method 2*

Now in the controller

$posts = DB::select('SELECT * FROM posts');
10

go to your Controller write this in function

public function index()
{
  $posts = \App\Post::all();

  return view('yourview', ['posts' => $posts]);
}

in view to show it

@foreach($posts as $post)
  {{ $post->yourColumnName }}
@endforeach
0
6

Well, to do it with eloquent you would do:

Blog:all();

From within your Model you do:

return DB::table('posts')->get();

http://laravel.com/docs/queries

1
  • Why not just $this->all()? That seems really roundabout.
    – Sturm
    Commented Feb 19, 2014 at 20:43
4

How to get all data from database to view using laravel, i hope this solution would be helpful for the beginners.

Inside your controller

public function get(){
        $types = select::all();
        return view('selectview')->with('types', $types);}

Import data model inside your controller, in my application the data model named as select.

use App\Select;

Inclusive of both my controller looks something like this

use App\Select;
class SelectController extends Controller{                             
    public function get(){
    $types = select::all();
    return view('selectview')->with('types', $types);}

select model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Select extends Model
{
    protected $fillable = [
        'name', 'email','phone','radio1','service',
    ];


    protected $table = 'selectdata';
    public $timestamps = false;
}

inside router

Route::get('/selectview', 'SelectController@get');

selectview.blade.php

@foreach($types as $type)
    <ul>
    <li>{{ $type->name }}</li>
    </ul>

    @endforeach
0
3
Query
// Select all data of model table
Model::all();
// Select all data of model table
Model::get();

Model::where('foo', '=', 'bar')->get();

Model::find(1);
Model::find([1, 2, 3]);
Model::findOrFail(1);
1
  • 1
    Welcome to SO. Code-only answers are improved by including an explanation of how you’ve answer addresses the question.
    – Nick
    Commented Apr 30, 2019 at 18:02
2

This worked for me.

$posts = Blog::get()->all();
1
1
 public function getAllPosts()
 {
   return  Blog::all();        
 }

Have a look at the docs this is probably the first thing they explain..

1

using DB facade you can perform SQL queries

 public function index()
{
    return DB::table('table_name')->get();
}
1

In Laravel Eloquent you can give the below queries in your controller to get all the data from your desired table:

$posts = Post::all();
return view('post', compact('posts'));

Or

$posts = Post::orderBy('id')->get();
return view('post', compact('posts'));
1
$posts = DB::select('SELECT * FROM table_x');

or to get specific columns:

$posts = DB::select('SELECT col_a, col_b, col_c FROM table_x');
3
  • This goes against the MVC approach that Laravel takes. It will work but i think this is bad practice
    – Morris
    Commented Jun 11, 2021 at 13:12
  • Thanks Morris, please feel free to enhance the method Commented Jun 12, 2021 at 21:04
  • Well it's simple. Instead of making queries inside of your controller just call your model and let it execute database commands for you.
    – Morris
    Commented Jun 12, 2021 at 21:43
0

If your table is very big, you can also process rows by "small packages" (not all at oce) (laravel doc: Eloquent> Chunking Results )

Post::chunk(200, function($posts)
{
    foreach ($posts as $post)
    {
        // process post here.
    }
});
1
  • @Kamlesh write you comment as separate question on stack overflow - with more details Commented Jun 3, 2021 at 10:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.