how to communicate with database in laravel
a) query buildr
b) eloquent orm
In Laravel, you can communicate with the database using two main approaches: the query builder and the Eloquent ORM (Object-Relational Mapping).
a) Query Builder: The query builder in Laravel provides a convenient and fluent interface for creating and executing database queries. It allows you to interact with the database using simple methods and provides a wide range of functions for selecting, inserting, updating, and deleting records.
Here's an example of using the query builder to fetch data from a database table:
use Illuminate\Support\Facades\DB; $users = DB::table('users') ->select('name', 'email') ->where('active', true) ->orderBy('created_at', 'desc') ->get();
In this example, the DB
facade is used to access the query builder. The table
method specifies the table name, and subsequent methods such as select
, where
, and orderBy
define the query conditions and sorting. Finally, the get
method retrieves the matching records from the database.
b) Eloquent ORM: Eloquent is Laravel's implementation of the active record pattern, providing an expressive and intuitive way to interact with the database using PHP classes and objects. Each database table is represented by a corresponding model class, allowing you to perform database operations using object-oriented syntax.
Here's an example of using Eloquent to fetch data from a database table:
namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $table = 'users'; } $users = User::select('name', 'email') ->where('active', true) ->orderBy('created_at', 'desc') ->get();
In this example, a User
model class is defined, which extends the base Model
class provided by Eloquent. The $table
property specifies the table associated with the model. Using the model class, you can chain methods like select
, where
, and orderBy
to build the query. Finally, the get
method retrieves the matching records from the database.
Both the query builder and Eloquent ORM provide powerful features for interacting with the database in Laravel. The choice between them depends on your specific use case and preference. The query builder is more suitable for complex queries and raw SQL operations, while Eloquent provides a more convenient and object-oriented way to work with database records.
No comments:
Post a Comment