Laravel Eloquent addSelect() Method Example

By Hardik Savani April 16, 2024 Category : Laravel

Hello Friends,

In this short guide, 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, laravel 9, laravel 10 and laravel 11 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:

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);

}

}

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);

}

}

Output:

I hope it can help you...

Tags :
Shares