2views

how to retrieve data from database in laravel and display it in html.

To retrieve data from a database in Laravel and display it in HTML, you can follow these general steps:

  1. Create a database table and define its columns. You can use Laravel’s migration system to create and manage your database schema.
  2. Create a model class for your table. This class will represent the data in your table and allow you to interact with it in your application.
  3. Define a controller method that retrieves the data from the database using the model and returns it to a view.
  4. Create a view file that displays the data in HTML.

Here’s an example of how you can retrieve data from a “users” table and display it in an HTML table:

  1. Create a migration to create a “users” table:
php artisan make:migration create_users_table --create=users

In the migration file, define the columns you want in the “users” table:

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Run the migration to create the “users” table:

php artisan migrate
  1. Create a model class for the “users” table:
php artisan make:model User

In the model class, define the table name and any relationships with other models:

class User extends Model
{
    protected $table = 'users';
}
  1. Define a controller method that retrieves the data from the “users” table using the model and returns it to a view:
public function index()
{
    $users = User::all();
    return view('users.index', ['users' => $users]);
}

In this example, the “index” method retrieves all the users from the “users” table using the “all” method on the User model. It then passes the users to a view called “users.index”.

  1. Create a view file that displays the data in HTML:

Create a new file called “index.blade.php” in the “resources/views/users” directory. In this file, you can use the Blade templating language to loop through the users and display them in an HTML table:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($users as $user)
            <tr>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

In this example, the view file loops through the $users variable passed from the controller and displays each user’s name and email in a table row.

Finally, you can navigate to the URL that calls the “index” method on your controller to see the users displayed in an HTML table.

https://youtu.be/vreZ9o72kZM