Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
communitycreator

How to avoid errors while using the get() in Laravel

Chinweuba Elijah Azubuike

Introduction

While using the get() function, most of us always encounter errors. In this shot, let’s look at how to avoid such errors if we eventually encounter them.

The get() function is used to fetch data from the database after querying with one or two query builders. The get() will output:

Illuminate\Support\Collection

This class contains the result from the database.

Why do you get errors?

  1. When we chain the get() method to a null instance.

  2. When we try to access data returned from our view or anywhere without looping it.

Example

use Illuminate\Support\Facades\DB;

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

foreach ($users as $user) {
    echo $user->name.',';
}

From the example above, if we remove the foreach() loop and try to echo the $user->name, we would end up getting only the last value of the data from the Collection instance class. Still, we loop through the $users variable, and we would be able to get each user in the table. I hope we learned something new.

Output

John, Tom, Harry, Paul, Josh

RELATED TAGS

laravel
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring