This laravel eloquent about subquery select. How to select a column from relational table with main model or table data by addSelect() method.
Laravel Subquery Selects method
Laravel Subquery Selects use a method addSelect() for getting extra column data with the main model it may be dummy data or relational table data. subquery select is advanced subquery support that is used to get data from related tables in a single query. More explain by below examples
Example 1 simple subquery select which have a column for dummy data<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Student; use DB; class StudentController extends Controller{ public function index(){ $students = Student::select() ->addSelect(DB::raw('5 as total')) ->where('status','1') ->get(); dd($students); } }
In above example students all columns data print and an extra column add total with value 5.
Example 2 add a column from relational table by eloquent model<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Student; use App\Models\ExtraDetail; class StudentController extends Controller{ public function index(){ $students = Student::addSelect(['roll_no' => ExtraDetail::select('roll_no') ->whereColumn('student_id', 'students.id') ->limit(1) ]) ->where('status','1') ->get(); dd($students); } }
here extra_details table have more information about student so we get a roll_no column with student model than use addSelect() query.
You read this tutorial on advanced web tutorial. here we provide laravel beginners to advanced tutorial.
Anmol Sharma
I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.
Related tutorial links
- What is laravel eloquent model and introduction
- part 1 laravel eloquent model all configuration hindi
- part 2 laravel insert and create data by eloquent model tutorial
- part 3 laravel data retrieve method
- part 4 first, find, findOrFail and firstOrFail method
- part 5 laravel delete vs truncate method
- part 6 laravel save vs update method
- part 7 laravel updateOrCreate and upsert
- part 8 laravel chunk vs cursor method
- part 9 laravel eloquent subquery select
- part 10 laravel findOrFail vs firstOrFail
- part 11 laravel create and retrieve data
- part 12 laravel eloquent aggregate functions
- part 13 laravel isDirty vs isClean vs wasChanged method