У меня есть коллекция клиентов в Laravel. $clients = Client::all();
Мне нужно обновить имя пользователя для каждого элемента в коллекции. Это мой код:
$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]);
});
Вопрос в том, как правильно сформировать $clients Collection
с обновленным $ client.
Так что мне нужно return $clients
с включенным именем пользователя.
Модели:
// Client Model
public function user()
{
return $this->belongsTo('App\User');
}
// User Model
public function clients()
{
return $this->hasMany('App\Client');
}
Миграция:
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();