Laravel find() – Use in a different way

Tram Ho

1. Introduction

In this article, I would like to introduce to you one of Laravel’s built-in methods, find() and the most effective ways to use find() .

2. Parameters of the find() method

The find($id, $columns = ['*']) method takes 2 parameters and requires at least 1 parameter to use:

  • $id : The primary_key column value you want to find, can pass 1 or 1 array of values.
  • $columns : Columns want to query (default value $columns will be all columns * ).

Return value: if $id is passed as an array, the result will be an array of records whose primary key is in the $id array, and otherwise, only one record with a primary key equal to $id will be returned.

Source code of the find() method .

For example:

3. Other related methods

In addition to the find() method, laravel also provides other methods:

  • findMany($ids, $columns = ['*']) : Find multiple records by primary key array $ids .
  • findOrFail($id, $columns = ['*']) : Find records by $id , if not found, return exception .
  • findOrNew($id, $columns = ['*']) : Find records by $id , if not found, create a new instance of model .

4. References

5. Conclusion

On the Laravel website, there are detailed instructions on all the methods that laravel supports. There is also a Laravel source github page where you can read more as well as test many cases to be able to use them correctly. effective in the best case.

Hope this sharing will help you newbie a bit in the process of learning about Laravel. If you find it useful, please give me 1 vote to let more people know and share this.

I’m Cong Thanh, thank you for following my article, if you have any questions, please comment below.

Share the news now

Source : Viblo