Laravel - Working With Database

In this topic, we will learn about laravel database.

Laravel makes interacting with databases extremely simple across a variety of database backends using either raw SQL, the fluent query builder, and the Eloquent ORM. Currently, Laravel supports four databases:

  • MySQL
  • PostgreSQL
  • SQLite
  • SQL Server

Using Multiple Database Connections

When using multiple connections, you may access each connection via the connection method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file:

$users = DB::connection('foo')->select(...);

Running Raw SQL Queries

Once database connection configured, we may run queries using the DB facade. The DB facade provides methods for each type of query: select, update, insert, delete, and statement.

Using Named Bindings

$results = DB::select('select * from users where id = :id', ['id' => 15]);

Running An Insert Statement

DB::insert('insert into users (id, name) values (?, ?)', [1, 'Smith']);

Running An Update Statement

$affected = DB::update('update users set age = 32 where name = ?', ['Smith']);

Running An Delete Statement

$deleted = DB::delete('delete from users');

Running A General Statement

DB::statement('drop table users');