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()
{
}
}
using DB facade you can perform SQL queries
public function index()
{
return DB::table('table_name')->get();
}
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);
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
This worked for me.
$posts = Blog::get()->all();
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
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.
}
});
public function getAllPosts()
{
return Blog::all();
}
Have a look at the docs this is probably the first thing they explain..
There are 3 ways that one can do that.
1.
$entireTable = TableModelName::all();
eg,
$posts = Posts::get();
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
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');
Well, to do it with eloquent you would do:
Blog:all();
From within your Model you do:
return DB::table('posts')->get();
Source: Stackoverflow.com