Laravel 8: MySQL Database Query Tip Sheet #4

Eloquent

Case Scenario

1. Inserts

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use App\Models\Student;
class StudentController extends Controller
{
public function store(Request $request)
{
$student = new Student();
$student->email = "someaone@gmail.com";
$student->name = "Sherlock Holmes";
$student->address = "221B Baker St.";
$student->age = 98;
$student->save();

}
}

2. Updates

Updating a single row

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use App\Models\Student;
class StudentController extends Controller
{
public function update(Request $request)
{
$student = Student::find(2);
$student->name = "Kenpachi Zaraki";
$student->email = "newemail@gmail.com";
$student->save();
}
}

Update Multiple Columns

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use App\Models\Student;
class StudentController extends Controller
{
public function update(Request $request)
{

$student = Student::where('name', "Sherlock Holmes")
->update(['email' => "trainstation@gmail.com"]);
}
}

3. Deletes

Deleting a single row

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use App\Models\Student;
class StudentController extends Controller
{
public function destroy(Request $request)
{

$student = Student::find(1);
$student->delete(); }
}

Delete Multiple row

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use App\Models\Student;
class StudentController extends Controller
{
public function destroy(Request $request)
{

$student = Student::where('name', 'Sherlock Holmes')->delete();
}
}

4. Selects

Fetching all rows in a table

Student::all();

Selects and the query builder

Student::select('name', 'email')->first();Student::select('name', 'email')->get();Student::where('name', 'Kenpachi Zaraki')->get();Student::where('name', 'Kenpachi Zaraki')
->orWhere('name', 'Tyler Harvey')
->get();

Related Articles