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() { } }
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 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.
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.
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.
$entireTable = TableModelName::all();
eg,
$posts = Post::get(); // both get and all will work here
or
$posts = Post::all();
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With