Laravel Eloquent addSelect() Method Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent Sum Multiple Columns Example
- Laravel Eloquent withMin(), withMax() and withAvg() Example
- Delete All Records from Table in Laravel Eloquent
- Laravel Eloquent take() and skip() Query Example
- Laravel Eloquent whereNotNull() Query Example
- Laravel Eloquent whereBetween() Query Example
- Laravel Eloquent Order By Query Example
- Laravel Eloquent whereRaw Condition Example
- Laravel Collection Merge | How to Merge Two Eloquent Collection?
- Laravel Eloquent orWhere() Condition Example
- Laravel Eloquent Relationships Tutorial From Scratch
- Laravel One to Many Eloquent Relationship Tutorial
- Laravel Many to Many Eloquent Relationship Tutorial