skip to Main Content

It may sound as a duplicate question. Please I have not found a working solution.I want to add additional field to my query in laravel but I am getting error. This is the php implementation

select id, "extra_column as type" from cases

have tried

 DB::table('cases')
         ->select(['id'])
         ->selectSub(function($query){
            $query->selectRaw('extra_column');
           },'type')
           ->get();

but I keep getting error

4

Answers


  1. Chosen as BEST ANSWER

    I later found out the solution. the extra_column was missing a double quote

    DB::table('cases')
             ->select(['id'])
             ->selectSub(function($query){
                $query->selectRaw('"extra_column"');
               },'type')
               ->get();
    

  2. You need to use like this:

    DB::table('cases')
        ->select(['id', 'extra_column as type'])
        ->get();
    
    Login or Signup to reply.
  3. Please try addSelect('extra_column as type').

    DB::table('cases')
         ->select(['id'])
         ->addSelect(`<additional column>`)   // We can able to use variable as well $value = 'extra_column as type';
         ->get();
    
    Login or Signup to reply.
  4. You can find that scenario in Laravel docs like so,

    $query = DB::table('users')->select('name');
     
    $users = $query->addSelect('age')->get();
    

    OR you can do something like this also:

    DB::table('users')->select('name')
        ->addSelect('email as user_email');
    

    and in case this triggers an issue as you told, please make sure that this column exists in your database.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search