0

I have a name field in users table. I am storing full name in single field with first name first then last name.

What I want to do is to change the order to last name appearing first and then first name when I call $user->nameRev and orderBy the new name in laravel.

I already use $user->name in many places so cannot change that therefore I want $user->nameRev to reverse the name and use it in orderBy queries

How do I achieve this ?

Raj
  • 1,928
  • 3
  • 29
  • 53
  • So how do you decide which part of full name is first and second? – u_mulder Jul 06 '18 at 09:37
  • well the name entered is assumed to be first name then last name. So I want to reverse it when I call $user->nameRev – Raj Jul 06 '18 at 09:39
  • If your single field value is `John Smith` okay, you explode by space and reverse. And if field value is `Jon Paul Jones` - how do you process it? – u_mulder Jul 06 '18 at 09:42
  • name field will only have two words: first name and last name – Raj Jul 06 '18 at 09:44
  • 1
    So create a function `nameRev()` in your user model and use it. – u_mulder Jul 06 '18 at 09:45
  • Similar problem here https://stackoverflow.com/questions/17232714/add-a-custom-attribute-to-a-laravel-eloquent-model-on-load – u_mulder Jul 06 '18 at 09:47
  • 1
    Possible duplicate of [Add a custom attribute to a Laravel / Eloquent model on load?](https://stackoverflow.com/questions/17232714/add-a-custom-attribute-to-a-laravel-eloquent-model-on-load) – u_mulder Jul 06 '18 at 09:48
  • the cleanest way is to break your name field to first_name, middle_name and last_name so you dont have to write dirty code anymore. then you can solve your problem with less effort. – Ranjan Adhikari Jul 06 '18 at 10:45

1 Answers1

0

I hope this can be help you.

Public function reversName()
 {
    $user = Auth::user();
    $str = $user->name;
    list($first, $last) = (explode(" ",$str));
    $nameRev = $last. ''. $first;
    $user->nameRev = $nameRev;

    $user->save() ;

 // Or

    DB::table(users)->where('user_name')->insert($nameRev);
   ... 
  } 
JsWizard
  • 1,663
  • 3
  • 21
  • 48