Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unset/Remove relation object from Laravel Eloquent collection

I've a fetch a Laravel Eloquent collection by:

$product = Product::query()->with(['merchant', 'picture'])->where('id', $id)->first();

and get the dump of $product is

Product {
  #casts: ...
  #dates: ...
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:1 [
    "id" => 27
  ]
  #original: ...
  #changes: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:2 [
    "merchant" => Merchant {...}
    "picture" => Picture {...}
    }
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: ...
}

I need to unset the relation object merchant and picture from this collection.

I've tried following options but failed:

unset($product['merchant']);
unset($product->merchant);

Any help will be appreciate.

Thanks in advance

like image 957
Ajay Makwana Avatar asked Sep 11 '18 14:09

Ajay Makwana


3 Answers

In Laravel 5.6.25, you can use unsetRelation():

$product->unsetRelation('merchant')->unsetRelation('picture');

Before that:

$relations = $product->getRelations();
unset($relations['merchant'], $relations['picture']);
$product->setRelations($relations);
like image 82
Jonas Staudenmeir Avatar answered Nov 07 '22 08:11

Jonas Staudenmeir


I have to tables with the same fields.. So I need to check the different column based on value. So if the value of foreign key is same then need to unset that relation

If you have merchant property in the model (merchant column in the table) you can get it value using $product->getOriginal('merchant') or $product->getAttribute('merchant')

like image 1
Andrey Lutskevich Avatar answered Nov 07 '22 09:11

Andrey Lutskevich


you can unset it

unset($product->merchant);
like image 1
Yevgeniy Afanasyev Avatar answered Nov 07 '22 08:11

Yevgeniy Afanasyev