How to fetch data from database in Laravel
In Laravel, you can fetch data from a database using the built-in Query Builder or Eloquent ORM.
To use Query Builder, you need to import the DB facade at the top of your file:
To use Eloquent ORM, you need to define a model for your table. You can generate a model using the make:model Artisan command:
Using Query Builder:
To use Query Builder, you need to import the DB facade at the top of your file:
use IlluminateSupportFacadesDB;Then, you can use the select , where , orderBy , and get methods to build a query. Here's an example:
$users = DB::table('users') ->select('name', 'email') ->where('active', 1) ->orderBy('name', 'asc') ->get();In this example, we select the name and email columns from the users table where the active column equals 1. We also order the results by name in ascending order. Finally, we call the get method to execute the query and retrieve the results.
Using Eloquent ORM:
To use Eloquent ORM, you need to define a model for your table. You can generate a model using the make:model Artisan command:
php artisan make:model UserThis will create a User model in the app/Models directory. Then, you can use the all, find, where, orderBy, and other methods to query the model. Here's an example:
$users = AppModelsUser::where('active', 1) ->orderBy('name', 'asc') ->get();
In this example, we retrieve all User
models where the active
column equals 1
. We also order the results by name
in ascending order. Finally, we call the get
method to execute the query and retrieve the results.
These are just some examples of how to fetch data from a database in Laravel. You can also use other methods like first, pluck, count, and so on. Check out the Laravel documentation for more information.
Comments (0)