LARAVEL

Displaying data from models in views


In Laravel, you can display data from models in views using Blade templating engine. Here's a step-by-step guide on how to do this

 

Pass Data to the View from the Controller

In your controller, retrieve the data from your model and pass it to the view. For example:

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    public function index()
    {
        // Retrieve all users
        $users = User::all();

        // Pass users to a view
        return view('users.index', ['users' => $users]);
    }
}

 

Access the Data in the View:

 In your view file (usually located in the resources/views directory), you can access the data using Blade syntax. For example, in users/index.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>User List</title>
</head>
<body>
    <h1>User List</h1>
    <ul>
        @foreach ($users as $user)
            <li>{{ $user->name }}</li>
        @endforeach
    </ul>
</body>
</html>

In this example, we're looping through each user retrieved from the controller and displaying their names. You can access any attribute of the user model using $user->attribute_name.

 

Render the View: 

Finally, you need to render the view. This is often done using the view() helper function in your controller method. In the example above, the controller method index() returns the view with the users data.

That's it! When you visit the route associated with this view, you'll see a list of users displayed on the page. Make sure your route points to the appropriate controller method that renders this view.


LARAVEL