Select all from table with Laravel and Eloquent
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.
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');