John Davidson

php - Laravel Collection map - cannot set property to null or false

0 comments
Message:


I encountered a very weird issue with Laravel collections. Basically I want to set the url and keywords properties to NULL if they are empty string.


But for some reason cannot set keywords to NULL or boolean false.


$this->feeds = NewsFeed::select(
['url', 'keywords']
)->orderBy('created_at', 'desc')->get();

$this->feeds->map(function ($item, $key) {
$item->url = null;
$item->keywords = null;

return $item;
});

dd($this->feeds);

And the feeds after the map:



Why the value of keywords is not changing? I can set it to a random string but not null or false. The url property is exactly the same type in the DB (VARCHAR, NULL by default).



My Answer:
collection->map(function ($item) {
if ($item->url === '') {
$item->url = null;
}

if ($item->keywords === '') {
$item->keywords = null; // This line does not work
}

return $item;
});

Rate this post

4 of 5 based on 9301 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us