ItSolutionStuff.com

Laravel Eloquent addSelect() Method Example

By Hardik Savani β€’ April 16, 2024
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

Laravel Eloquent Sum Multiple Columns Example

Read Now β†’
β˜…

Laravel Eloquent withMin(), withMax() and withAvg() Example

Read Now β†’
β˜…

Delete All Records from Table in Laravel Eloquent

Read Now β†’
β˜…

Laravel Eloquent take() and skip() Query Example

Read Now β†’
β˜…

Laravel Eloquent whereNotNull() Query Example

Read Now β†’
β˜…

Laravel Eloquent whereBetween() Query Example

Read Now β†’
β˜…

Laravel Eloquent Order By Query Example

Read Now β†’
β˜…

Laravel Eloquent whereRaw Condition Example

Read Now β†’
β˜…

Laravel Collection Merge | How to Merge Two Eloquent Collection?

Read Now β†’
β˜…

Laravel Eloquent orWhere() Condition Example

Read Now β†’
β˜…

Laravel Eloquent Relationships Tutorial From Scratch

Read Now β†’
β˜…

Laravel One to Many Eloquent Relationship Tutorial

Read Now β†’
β˜…

Laravel Many to Many Eloquent Relationship Tutorial

Read Now β†’