TimRiva
TimRiva

Reputation: 3

Creating a empty collection throwing an error in Laravel

I'm returning a collection to a view and that collection is not always full. But in my view I'm accessing a value from that collection. And if the given collection is empty it crashes.

So my idea was to, if the collection was empty, populate it my self with keys and empty values like this.

Controller:

if ($collection->isEmpty()) {
    $collection->put('key1', "");
    $collection->put('key2', "");
    $collection->put('key3', "");
}else{

Blade:

<input type="text" class="form-control" name="key1" value="{{$collection->key1}}">

But it just keeps giving me this error:

Property [key1] does not exist on this collection instance. (View: C:\xampp\htdocs\Laravel...

If I dd($collection) using put I get

Collection {#510 ▼
  #items: array:3 [▼
    "key1" => ""
    "key2" => ""
    "key3" => ""
  ]
}

dd() with $collection['key1']; won't even get to the die and dump part.

Upvotes: 0

Views: 1000

Answers (2)

Fabian Bettag
Fabian Bettag

Reputation: 810

You can't access collection keys directly on the collection object.

Instead, you have to use the array access syntax like this:

$collection['key1']

or by using the get method like this:

$collection->get('key1')

The get method has the advantage of not throwing an error if the key is undefined. Instead, it will return a default value. Normally, this would be null, but it can be overridden by using the second parameter of the function:

$collection->get('key1', 'default')

Assuming you are using PHP 7 or above, you can achieve a similar functionality with the Null coalescing operator like this:

$collection['key1'] ?? 'default'

For further information, take a look at the documentation: https://laravel.com/docs/7.x/collections#method-get

Upvotes: 2

Jerodev
Jerodev

Reputation: 33186

A Collection is basically a wrapper over an array, so you need to use array access to get to the underlying values:

$collection['key1']

Also, don't overuse collections. Yes, they can help out a lot with complex array manipulation, but they also come with an overhead. If you only use it to set or access keys, consider using a basic array or an object.

Upvotes: 1

Related Questions