CRUD Operations
/.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=testuser
DB_PASSWORD=pwd
/routes/web.php
/.env
use App\Http\Controllers\StudentController;
..
Route::get('/db-select', [StudentController::class, 'db_select']);
Connect Database
/app/Http/Controllers/Student.php
use DB;
..
Insert Row
public function db_insert() {
$data = array(
'name' => 'Kayla',
'email' => 'kayla@example.com',
'gender' => 'Female'
);
DB::table('students')->insert($data);
}
Insert ID Row
public function db_insert_id() {
echo DB::table('students')->insertGetId([
'name' => 'Kayla',
'email' => 'kayla@example.com',
'gender' => 'Female'
]);
}
Update Row
public function db_update() {
DB::table('students')
->where('id', 106)
->update(['name' => 'Smith Adams']);
}
Delete Row
public function db_delete() {
DB::table('students')->where(['id' => 106])->delete();
}
Select Raw SQL
public function db_select_raw() {
$sql = 'SELECT * FROM students ORDER BY name';
$students = DB::select($sql);
print_r($students);
echo $students[0]->name
}