Hello dev, Today we are going to learn Laravel Eloquent addSelect() Method Example. This tutorial will cover on eloquent addSelect() method in laravel with example.
we will show you laravel eloquent addselect example. we will help you to give an example of how to use addSelect() in laravel. you will learn addselect laravel eloquent. I explained simply about laravel addselect count. Alright, let’s dive into the details.
You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.
Laravel provides addSelect() query builder method to select column with select statement. Sometime we select columns with multiple where and you need to add condition to select more rows then you can use addSelect() method.
So, let’s see the two example below:
Also Read: How to Call External API in Laravel? (2022)
Examples on Laravel Eloquent addSelect() Method Example:
Example 1:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use DB;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$posts = Post::select("id", "title")
->addSelect("body")
->addSelect(DB::raw('1 as number'))
->take(10)
->get();
dd($posts);
}
}
Also Read: Laravel Where Clause with Function Query Example 2022
Example 2:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$posts = Post::select("id", "title");
if($request->page == "detail"){
$posts = $posts->addSelect("body");
}
$posts = $posts->get();
dd($posts);
}
}
Also Read: [ New ] Laravel Google 2FA Authentication Tutorial Example (2022)
Output:

Conclusion:
Today, We had learn Laravel Eloquent addSelect() Method Example. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.
Also Read: How to Use Limit and Offset in Laravel Eloquent? (2022)