3

CONCAT Two Columns in Laravel with Example

 2 years ago
source link: https://www.laravelcode.com/post/concat-two-columns-in-laravel-with-example
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

CONCAT Two Columns in Laravel with Example

  92 views

  2 weeks ago

Laravel

When working with Laravel query, you may want to get two column values to single column. This is helpful where you need full name of user combining first name and last name.

This can be done through MySQL CONCAT method as well as Laravel accessors. We will use both ways to group two column into single column.

CONCAT method

Laravel provides DB::raw() method to inject MySQL query into database. you can use MySQL CONCAT method to combine two columns into single virtual column. Here is the below example.

/**
 * return users details.
 *
 * @param  void
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $users = DB::table('users')
        ->select(
            "users.*",
            \DB::raw("CONCAT(users.first_name,' ',users.last_name) AS full_name")
        )
        ->get();

    return view('users',compact('users'));
}

And in the blade template, you can access full_name property.

@foreach ($users as $user)
    {{ $user->full_name }}
@endforeach

Laravel accessors

An accessor converts an model data when it is accessed. To create accessor, you can create get{Attribute}Attribute method on your model into studly cased name of the column you wish to access.

For the above method, if you want to receive full_name from first_name and last_name column, first create method in User model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get full name.
     *
     * @return string
     */
    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }
}

Now you will have full_name virtual column whenever you use model to fetch data from the database. You can use it same as first one way.

There is also one simple PHP way you can use string concatenation full name. But you have to use concatenation everytime when you have to get full name which is not DRY(Don't Repeat Yourself) code way.

@foreach ($users as $user)
    @php
        $full_name = $user->first_name. " " .$user->last_name;
    @endphp
    {{ $full_name }}
@endforeach

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK