[php] 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()
    {

    }

}

This question is related to php mysql laravel laravel-4 eloquent

The answer is


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(); 
  1. 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
  1. 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();

http://laravel.com/docs/queries


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-4

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel Can I do Model->where('id', ARRAY) multiple where conditions? how to fix stream_socket_enable_crypto(): SSL operation failed with code 1 Rollback one specific migration in Laravel How can I resolve "Your requirements could not be resolved to an installable set of packages" error? Define the selected option with the old input in Laravel / Blade Redirect to external URL with return in laravel laravel the requested url was not found on this server

Examples related to eloquent

Eloquent: find() and where() usage laravel How to select specific columns in laravel eloquent Laravel Eloquent where field is X or null Laravel Eloquent limit and offset laravel collection to array Eloquent get only one column as an array Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0 Laravel 5.2 - pluck() method returns array Eloquent ORM laravel 5 Get Array of ids eloquent laravel: How to get a row count from a ->get()