Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()     {      }  } 
like image 613
RSM Avatar asked Feb 19 '14 20:02

RSM


People also ask

How do I remove all records from a table in Laravel eloquent?

In the first example, we are going to use the truncate() function, which is used to delete all the records. In the second example, we will delete records on the basis of the id. So we will specify some id and use the delete() function to delete all the records of that particular id.

What is view Laravel?

What are the views? Views contain the html code required by your application, and it is a method in Laravel that separates the controller logic and domain logic from the presentation logic. Views are located in the resources folder, and its path is resources/views.

What is pluck in Laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.


2 Answers

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.

like image 77
Sturm Avatar answered Sep 25 '22 12:09

Sturm


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'); 
like image 42
Koushik Das Avatar answered Sep 25 '22 12:09

Koushik Das