Laravel 9 Eloquent AddSelect() Query Example

Hello Artisan,

In this short tips tutorial, I will show you laravel eloquent addselect example. I will help you to show an example of how to use addSelect() in laravel eloquent query. From this addSelect tutorial, we will learn addselect laravel eloquent. I will show you two simple query about laravel addselect count.

We can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions. Laravel allows the addSelect() query builder method to select columns with a select statements. Sometimes we select columns with multiple where and you need to add a condition to select more rows then you can use addSelect() method.

 

Example 1:

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

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

 

Read also: How to Update Multiple Records in Laravel 9?

 

Hope it can help you.

 

#laravel #laravel-9x