How to get data from database Laravel 9

How to get data from database to view Laravel 9

Posted by Raquel Crist on July 6, 2022

How to get data from database Laravel 9

How to get data from database to view Laravel 9

Posted by Raquel Crist on July 6, 2022

Here is how you can get data from database in Laravel 9.

In this demonstration we will use a posts table. Before you start, make sure your Laravel project is connected to a database and the posts table is created. If you need to know more about database connection and creating tables, here is a tutorial that might help you https://wecode101.com/how-to-create-a-table-in-the-database-in-laravel-9

Step 1. Create the posts model

Execute command:

php artisan make:model Post

Step 2. Edit Post model

Go to app/Models/Post.php and paste below snippet:

/**
 * Fillable fields.
 *
 * @var array
*/
protected $fillable = [
   'title',
   'description',
   'author',
];

the columns from the database that you want to be displayed is specified in the fillable array. 

Post model now looks like this:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    /**
     * Fillable fields.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'description',
        'author',
    ];
}

Step 3. Create post controller

Execute command below:

php artisan make:controller PostController

Go to app/Http/Controllers/PostController.php and paste below snippet:

public function index()
{
   $post = Post::all();
   return view('post', compact('posts', $posts));
}

In the above snippet, you can see the Post model method all() is being called in the index method. All the rows in the column will now get displayed as it gets passed in the view using the variable $posts.

Post controller now looks like this:

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
      $post = Post::all();
      return view('post', compact('posts', $posts));
    }
}

Step 4. Create route

Go to /routes/web.php:

Route::get('/post', [PostController::class, 'index']);

Step 5. Create view file

Go to /resources/views and create view file post.blade.php. Then copy and paste below snippet:

@foreach($posts as $post)
    <ul>
        <li><h1>{{$post->title}}</h1></li>
        <li><div>{{$post->description}}</div></li>
        <li><div>{{$post->author}}</div></li>
    </ul>
@endforeach

You should now see the data displayed 

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question