How to get data from the Laravel database

Learn how to retrieve data from Laravel's database using Eloquent ORM, with a step-by-step example.

Retrieving Data With Queries

Laravel provides a number of ways to retrieve data from a database. One of the most popular methods is using the query builder. The query builder allows you to easily construct complex SQL queries without having to write a single line of SQL.

Let's take a look at an example of using the query builder to retrieve data from a database. We'll start by setting up a simple users table.


CREATE TABLE users (
  id INTEGER AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) NOT NULL,
  PRIMARY KEY (id)
);

Now that we have a table, let's insert some data into it.


INSERT INTO users (name, email) VALUES
('John Doe', '[email protected]'),
('Jane Doe', '[email protected]');

Now that we have some data in the table, let's use the query builder to retrieve it.


$users = DB::table('users')->get();

foreach ($users as $user) {
    echo $user->name . ' has an email address of ' . $user->email . 'n';
}

The above code will output the following:


John Doe has an email address of [email protected]
Jane Doe has an email address of [email protected]

The query builder can also be used to query the database using a variety of different methods. For example, if we wanted to retrieve all users with an email address that ends in .com, we could use the where method.


$users = DB::table('users')->where('email', 'like', '%.com')->get();

foreach ($users as $user) {
    echo $user->name . ' has an email address of ' . $user->email . 'n';
}

The above code will output the following:


John Doe has an email address of [email protected]
Jane Doe has an email address of [email protected]

As you can see, the query builder makes it easy to construct complex queries without having to write a single line of SQL. It can also be used to insert, update, and delete data from the database.

Answers (0)