mvn.2047
mvn.2047

Reputation: 362

Laravel PHP: how to join each element of collection after update?

I have Clients collection in Laravel. $clients = Client::all();

I need to update it with a user's name for each item inside a collection. This is my code:

$clients = Client::all();

$clients->each(function ($item, $key) {

    if ($item->user()->first()) 
    {
        $user = $item->user()->first();
        $name = $user->name;
    } else $name = '';

    $client = collect($item);
    $client = $client->union(['user' => $name]);
});

The question is what is a proper way to form $clients Collection with $client updated.

So I need to return $clients whith user name included.

Models:

 // Client Model

public function user()
{
    return $this->belongsTo('App\User');
}

// User Model
public function clients()
{
    return $this->hasMany('App\Client');
}

Migration:

Schema::create('clients', function (Blueprint $table) {
$table->bigIncrements('id');
$table->char('name', 200)->nullable();
$table->char('city', 100)->nullable();
$table->char('type', 20)->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamps();
$table->softDeletes();

Upvotes: 2

Views: 134

Answers (1)

Salman Zafar
Salman Zafar

Reputation: 4035

You can do something like below:

$clients = Client::all();

$clients->each(function ($item, $key) {

    $name = $item->user ? $item->user->name : "";
    return $name; // will append name in this client collection

});

return $clients

To read more about each method visit

Hope it helps.

Thanks

Upvotes: 1

Related Questions