Home » Laravel: Add New Column With A Value In Select Query

Laravel: Add New Column With A Value In Select Query

Last updated on June 11, 2021 by

Sometimes, we want to add a new custom/temporary column with a value in a select query or in collections in Laravel. In this article, we will see how to add a new custom column with value in the Laravel collection. Let’s just dive into it.

Add New Column With A Value In Select Query In Laravel

Let’s take a simple example to add a new custom column with the value in Collection. For e.g. Let’s suppose we have a Document model in our project which returns the documents stored into the database. You can see the original collection look like below:

Original Collection

App\Models\Document {#4400
     id: 4,
     document_id: 4,
     uuid: "708ee062-2d9a-44f4-8eb7-8e13af6b2fa7",
     name: "Example Document",
     original_name: "My Photo",
     extension: "jpg",
     description: "This is my photo demo",
     path: "documents/nC25hiiS8lBhofW5Aq6Eh3cNsnwWIfRS2qM0NCwl.jpeg",
     created_at: "2021-06-07 07:21:31",
     updated_at: "2021-06-07 11:55:26",
   }

Now, we need to pass the additional custom column named "url" based on the path column. And when you access the $document->url column then it will return the full URL of the document in Controller or in blade file. Hope you are getting it.

Let’s now add the new "url" column to the Document model. To do that you need to first add the protected $appends accessor.

app/Models/Document.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Document extends Model
{ 
     /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */

    protected $appends = ['url'];
}

Then we need to define an accessor method with get{Attribute}Attribute in your model where {Attribute} is the “studly” cased name of the column you wish to access.

So our method name will be getUrlAttribute() as per our example. If your custom column is path_name then your method name will be getPathNameAttribute(). Let’s add our method in the model and our full model look like below:

app/Models/Document.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class Document extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'document_id', 'name', 'original_name', 'extension', 'description', 'path'
    ];

     /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */

    protected $appends = ['url'];
 
    public function getUrlAttribute()
    {
        return Storage::url($this->path);
    }
}

Then it’s time to fetch the data and access our newly created custom column in Laravel. You can do it in the controller or test it using Tinker.

app/Http/Controllers/DocumentController.php

<?php

namespace App\Http\Controllers;

use App\Models\Document;

class DocumentsController extends Controller
{
    public function index()
    {   
        $document = Document::find(4);

        dd($document->url);
    }
}

Using Tinker:

>>> $d = Document::find(4)
[!] Aliasing 'Document' to 'App\Models\Document' for this Tinker session
.
=> App\Models\Document {#4404
     id: 4,
     document_id: 4,
     uuid: "708ee062-2d9a-44f4-8eb7-8e13af6b2fa7",
     name: "My photo u",
     original_name: "Mayank D",
     extension: "jpg",
     description: "This is my photo testing from client u",
     path: "documents/nC25hiiS8lBhofW5Aq6Eh3cNsnwWIfRS2qM0NCwl.jpeg",
     created_at: "2021-06-07 07:21:31",
     updated_at: "2021-06-07 11:55:26",
   }
>>> $d->url
=> "http://demo.local/storage/documents/nC25hiiS8lBhofW5Aq6Eh3cNsnwWIfRS2qM0NCwl.
jpeg"

Output:

"http://demo.local/storage/documents/nC25hiiS8lBhofW5Aq6Eh3cNsnwWIfRS2qM0NCwl.jpeg"

Additionally, read our guide:

  1. Base Table Or View Already Exists In Laravel Migration
  2. Add Column After A Column In Laravel Migration
  3. Laravel: Change Column Type In Migration
  4. Laravel: Change Column Name In Migration
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Update Pivot Table In Laravel
  11. How To Dynamic iFrame URL In Elementor
  12. How To Handle Failed Jobs In Laravel
  13. How To Remove WooCommerce Data After Uninstall
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. Laravel Run Specific Migration
  18. How To Fix Elementor Icons Not Showing

That’s it from our end. We hope this article helped you to add new custom column with value in select Eloquent query in Laravel.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!Laravel: Add New Column With A Value In Select Query

 
 

Leave a Comment

*

code