Laravel Eloquent addSelect() Method Example

Laravel Eloquent addSelect() Method Example

In this post we will give you information about Laravel Eloquent addSelect() Method Example. Hear we will give you detail about Laravel Eloquent addSelect() Method Example And how to use it also give you demo for it if it is necessary.

In this article, We will learn about How to use addSelect() in Laravel. You will learn addSelect() the method which is a method of Laravel Eloquent. Well, let’s go into more detail.

Laravel provides addSelect() query builder method to select a column with a select statement. Sometimes we select columns with multiple where and you need to add a condition to select more rows, you can use addSelect() the method.

Laravel Eloquent addSelect() Method Example

So, let’s see both examples below:

Example 1:

<?php
   
namespace AppHttpControllers;
  
use IlluminateHttpRequest;
use AppModelsPost;
use DB;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $posts = Post::select("id", "title")
                        ->addSelect("body")
                        ->addSelect(DB::raw('1 as number'))
                        ->take(10)
                        ->get();
 
        return posts;
    }
}

Example 2:

<?php
  
namespace AppHttpControllers;
  
use IlluminateHttpRequest;
use AppModelsPost;
  
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();
  
        return $posts;
  
    }
}

Output:

[
  {
    "id": 1,
    "title": "Prof.",
    "body": "Tempore et omnis ut et. Dolore sunt similique vitae repellat corrupti. Consequuntur minus dolore eius reprehenderit neque. Officiis facilis sed aut ea."
  },
  {
    "id": 2,
    "title": "Dr.",
    "body": "Ea expedita autem consequatur quia. Corrupti est sapiente fugit itaque laboriosam ipsum. Vero voluptatem sed nostrum quam repudiandae doloremque."
  },
  {
    "id": 3,
    "title": "Ms.",
    "body": "Sed est nihil unde tempora distinctio. Consectetur omnis at doloribus dolor nisi dolor. Et accusantium ipsa omnis quam voluptas aperiam. Voluptas dolores voluptatum optio quas."
  },
  {
    "id": 4,
    "title": "Mr.",
    "body": "Voluptas aut odio quis quasi facere laborum reiciendis. Totam officia est at ut aliquam architecto. Fuga eligendi consectetur deleniti ducimus ut eos."
  },
  {
    "id": 5,
    "title": "Mr.",
    "body": "Et non esse non sapiente suscipit corporis at. Cumque veritatis ut ratione. Laboriosam tenetur rerum qui adipisci quae ipsa excepturi. Voluptas aut unde saepe veritatis voluptatum officiis rem velit."
  },
  {
    "id": 6,
    "title": "Dr.",
    "body": "Voluptatem qui deleniti magni sequi at. Ut quo sapiente quis autem. Provident fugit facere corporis. Est rem sequi et."
  },
  {
    "id": 7,
    "title": "Miss",
    "body": "Unde laboriosam et necessitatibus beatae et aut atque. Reprehenderit qui ad sed sequi. Atque quibusdam aut magni eum in sequi deleniti. Quas voluptatem dignissimos et est rem."
  },
  {
    "id": 8,
    "title": "Prof.",
    "body": "Beatae maxime et omnis minima hic velit ut. Culpa corrupti nulla repellendus qui a quis. Ab dolorem sed voluptatem atque consequuntur enim eum."
  },
  {
    "id": 9,
    "title": "Dr.",
    "body": "Voluptas ad laboriosam suscipit quaerat tempora. Fugiat ea placeat itaque fugit. Ut provident aliquam cupiditate eaque aut. Nesciunt natus voluptatem ullam nostrum est."
  },
  {
    "id": 10,
    "title": "Dr.",
    "body": "Facere occaecati id repudiandae numquam dolorem repudiandae doloribus. Beatae soluta eos vitae illum id ut eum. Quidem eum et ut sit."
  },
  {
    "id": 11,
    "title": "Dr.",
    "body": "Quo accusamus quia quaerat cupiditate assumenda tempora voluptatum minima. Laborum blanditiis ipsum pariatur id rem nesciunt. Quod voluptatem voluptates non blanditiis inventore."
  },
  {
    "id": 12,
    "title": "Dr.",
    "body": "Nisi aut sint ut quia ut. Voluptatem impedit consectetur non et sed omnis. Unde voluptatem laudantium voluptates. A asperiores dolorum pariatur quasi sunt."
  },
  {
    "id": 13,
    "title": "Mr.",
    "body": "Facilis officia laboriosam sed tenetur et consequatur voluptate. Illo officiis corporis ex ducimus quaerat culpa eos."
  },
  {
    "id": 14,
    "title": "Miss",
    "body": "Eum sunt veniam est. Quia saepe in ut distinctio libero. Necessitatibus sed possimus quas quisquam id delectus aut. Doloremque molestiae vel voluptatibus quia."
  },
  {
    "id": 15,
    "title": "Prof.",
    "body": "Sint cupiditate nostrum ut nobis. Sed animi veritatis culpa vel. Nemo unde accusantium est voluptatem sit. Iure odio omnis vel omnis qui odit sit."
  }
]

Also, if you use a real column name in add select and if you don’t select the related column, for example, if you use addSelect('some string') then you’ll get no related records either because you’ve also to select the related column that makes the relationship in this case, you may try something like this:

$postWithComments = Post::with(['comments'])->addSelect(['title', 'body']))->get();

Thank you for reading this article.

Also see: How to get the raw SQL query from the Laravel Query Builder

  .       .

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.

Hope this code and post will helped you for implement Laravel Eloquent addSelect() Method Example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US