CONCAT columns with Laravel 5 eloquent



PHP Snippet 1:

$comp = Component::select(DB::raw("CONCAT('name','id') AS ID"))->get()

PHP Snippet 2:

$comp = Component::select(DB::raw("CONCAT('name','id') AS display_name"),'id')->get()->pluck('display_name','id');
// dump output to see how it looks.
dd($comp);// array key should be the arrray index, the value the concatted value.

PHP Snippet 3:

class UserProfile extends Model
{

  /**
   * Get the user's full concatenated name.
   * -- Must postfix the word 'Attribute' to the function name
   *
   * @return string
   */

  public function getFullnameAttribute()
  {
      return "{$this->first_name} {$this->last_name}";
  }

}

PHP Snippet 4:

| id | first_name | last_name |
-------------------------------
| 1  | John       | Doe       |


$user = App\UserProfile::first(); 

$user->first_name;   /** John **/
$user->fullname;    /** John Doe **/

PHP Snippet 5:

DB::raw('CONCAT(member.last_name, \' \', member.first_name) as full_name')

PHP Snippet 6:

public function scopeFindUserByName($query,$name) {
    // Concat the name columns and then apply search query on full name
    $query->where(DB::raw(
            // REPLACE will remove the double white space with single (As defined)
            "REPLACE(
                /* CONCAT will concat the columns with defined separator */
                CONCAT(
                    /* COALESCE operator will handle NUll values as defined value. */
                    COALESCE(name_first,''),' ',
                    COALESCE(name_middle,''),' ',
                    COALESCE(name_last,'')
                ),
            '  ',' ')"
        ),
    'like', '%' . $name . '%');
}

PHP Snippet 7:

UserModel::findUserByName("Max Begueny");

PHP Snippet 8:

$query = UserModel::query();
$query->findUserByName("Max Begueny");

PHP Snippet 9:

foreach($resultsArray AS $row){
    $row['fullname'] = trim($row['firstname']).' '.trim($row['lastname']);
}

PHP Snippet 10:

$text = "other";
$limit = 100
public function get_data($text, $limit)
{
    
    $result = $this->select('titulo', 'codigo', DB::Raw("CONCAT(codigo, ' ', titulo_long) AS text_search"))
                ->where('tipo', '=', 2)
                ->having('text_search', 'LIKE', "%$text%")
                ->limit($limit)
                ->get();
    return $result;

}