Laravel Eloquent addSelect() Method Example - TechvBlogs

Laravel Eloquent addSelect() Method Example

In this article, We will learn about How to use addSelect() in Laravel.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

1 week ago

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 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()
    {
        $posts = Post::select("id", "title")
                        ->addSelect("body")
                        ->addSelect(DB::raw('1 as number'))
                        ->take(10)
                        ->get();
 
        return 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();
  
        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.

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

If you want to manage your VPS / VM Server without touching the command line go and  Checkout this linkServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a  matter of minutes.  You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.

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

Comments (0)

ServerAvatar
Multiple sites on a single VPS/VM/Server Deploy PHP sites on cloud in minutes, simple as that!
ServerAvatar
Generate Free SSL Certificate - SSLForWeb

Generate Free SSL Certificate

  • 90-Day Certificates
  • SSL Monitoring
  • Wildcard Certificates
  • Multiple Domains
  • Certificate Management
  • Expiration Reminders

Comment


Note: All Input Fields are required.