How to display data from the Laravel model

Learn how to extract data from Laravel models with an example.

Displaying Data from a Laravel Model

Displaying data from a Laravel model can be achieved in many different ways. In this example, we will look at the most common approach: using Eloquent. Eloquent is the ORM (Object-Relational Mapping) that comes with Laravel and it allows developers to interact with their database in an easy and intuitive way.

To begin, we will create a model for our data. A model is a class that represents a specific table in the database. We will call it Product and it will contain information about products:

class Product extends Model
    protected $fillable = [

Now that we have a model, we can use Eloquent to query the database and get the data that we need. To retrieve all products, we can use the all() method:

$products = Product::all();

This will retrieve all the products from the database and store them in a collection. We can then loop through the collection and display the data using Blade templates:

@foreach ($products as $product)
    <h3>{{ $product->name }}</h3>
    <p>{{ $product->description }}</p>
    <p>Price: {{ $product->price }}</p>

This will loop through the collection and display the product name, description, and price. We can also use Eloquent to query the database for specific products. For example, if we wanted to display only products from a certain category, we could use the where() method:

$products = Product::where('category_id', $categoryId)->get();

This will retrieve only the products from the specified category. We can then loop through the collection and display the products as we did before. This is just one example of how we can use Eloquent to retrieve and display data from a Laravel model. There are many other ways of doing this, such as using query builders and raw SQL queries, but Eloquent provides a convenient and intuitive way of interacting with the database.

Answers (0)