2

i would like to know how can i add extra column in laravel collection, return from database. for instance.

User Model User->id User->name

Reservation Model Reservation->user_id Reservation->id

now

$users = User::all();
$user_reservation = Reservation::all();

    foreach ($users as $user)
    {
        foreach ($user_reservation as $ur) 
        {
            if ($user->id == $ur->user_id) 
            {
            //Add extra column in to the users model
            }
        }
    }
Muhabutti
  • 1,256
  • 2
  • 15
  • 20

3 Answers3

1

Laravel has a something called $appends with Accessors. how to use it

Define $append in the model where you want to add custom collection. in my case User model

    class User extends Model{

    protected $appends = ['user_eservation'];

    public function getUserReservations($id)
    {
        return User::where('id', $id)->first();
    }

    public function getUserReservationAttribute()
    {
        return $this->getUserReservations(Auth::user()->id);
    }
}

and now you can call the custom attribute which is not available in the database , by calling the getUserReservatoin function.

for instance

$users = User::all(); $user_reservation = Reservation::all();

foreach ($users as $user)
{
    foreach ($user_reservation as $ur) 
    {
        if ($user->id == $ur->user_id) 
        {
        $user->getUserReservations();
        }
    }
}
Muhabutti
  • 1,256
  • 2
  • 15
  • 20
0
$user->push(['extra_column' => $value]);
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
0

You should only declare new public property of the model (but not new field in the table).

    class User extends Model{
          public reservation;

than you can set this property for any users collection item.