Search code examples
phplaravellaravel-7laravel-collection

Laravel replace collection value based on other collection


Two collections:

$users = User::select('id','name')->get();

//outcome  [{"id":"1","name":"John"},{"id":"2","name":"Peter"}]

$orders = Orders::all();

//outcome  [{"id":"1","userid":"1"},{"id":"2","userid":"2"}]

How to modify $orders collection "userid" value to replace with real names instead of numeric? I would like to send that to view without modifying database.

Expected outcome of $orders:

//outcome  [{"id":"1","userid":"John"},{"id":"2","userid":"Peter"}]

Solution

  • $orders = Orders::with('user')->get();
    

    In Your Order Model:

    public function user(){
    return $this->belongsTo(User::class,'userid');
    }