mysqllaravel-5laravel-collection

how to add extra element in laravel collection


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
            }
        }
    }

Solution

  • 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();
            }
        }
    }