Foreign key is now null and when mapping through the data it say "Attempt to read property "$category_name" on null" - laravel

I deleted a category which is an f-key of the items table. Now the view has an error saying 'Attempt to read property "category_name" on null'. How do I render a null foreign key?
I tried if-else:
#if({{$item->category->category_name}} === 'null')
<h2>no category</h2>
#else
{{ $item->category->category_name}}
#endif

Try this:
#if ($item->category)
{{ $item->category->category_name }}
#else
<h2>no category</h2>
#endif
Or simply
<h2>{{ $item->category?->category_name ?? 'no category' }}</h2>

In PHP8 or Larvel 8
simple use this one
<h2>{{ $item->category->category_name ? 'no category' }}</h2>

Related

How does Laravel turn this code into a link?

Consider this block of code from a Laravel blade file:
<div class="result-content">
<h6>{{ $item->name }}</h6>
<div>{!! Str::limit($item->desccription, 120) !!}</div>
#if($item->type == 'lot')
<div>{{ $item->info ? "Current Bid: $".number_format($item->info, 2) : 'No bids yet' }}</div>
<div>{{ \Carbon\Carbon::parse($item->start)->setTimezone($_COOKIE['timezone'])->format('n/j/y g:ia T') }} - {{ \Carbon\Carbon::parse($item->end)->setTimezone($_COOKIE['timezone'])->format('n/j/y g:ia T') }}</div>
#else
<div>{{ $item->info }} Lot{{ $item->info > 1 ? "s" : '' }}</div>
<div>{{ \Carbon\Carbon::parse($item->start)->setTimezone($_COOKIE['timezone'])->format('n/j/y T') }} - {{ \Carbon\Carbon::parse($item->end)->setTimezone($_COOKIE['timezone'])->format('n/j/y T') }}</div>
#endif
<a href="{{ $item->search_url }}" title="">
View: {{ $item->search_title }}
</a>
</div>
Somehow or other, this renders in a browser as a block of text that is all included in a link tag, and "$item->search_url" becomes the link url. But the link is wrong - it just points back to the page this text is appearing on. I need to figure out where "search-url" is assigned its value, so I can fix it. But I am entirely new to Laravel, and I can't figure out where or how "search-url" is getting assigned a value. I've searched the entire system with Visual Code, and that name doesn't appear anywhere else. It's not a variable, it's not a property name, it's not a database field name.
Where is that variable getting assigned?

Laravel - ERROR: Trying to get property 'depthead' of non-object

In my Laravel-5.8 blade that has this code:
#foreach($employees as $key => $employee)
<li class="list-group-item">
<b>Line Manager:</b>
#if(!$employee->linemanager)
<a class="float-right">N/A</a>
#else
<a class="float-right">{{ $employee->linemanager->fullName() ?? 'None' }}</a>
#endif
</li>
<li class="list-group-item">
<b>HOD:</b>
#if(!$employee->department->depthead)
<a class="float-right">N/A</a>
#else
<a class="float-right">{{isset($employee->department->depthead) ? $employee->department->depthead->first_name. ' ' .$employee->department->depthead->last_name : 'None'}}</a>
#endif
</li>
#endforeach
and its pointing to this line:
#if(!$employee->department->depthead)
How do I resolve it?
Thanks
The root cause of your issue is that $employee->department is either null or not an Object (Instance of Department, assuming you have Model and Relationships setup properly). You've got a check in place, but it's in the wrong spot. Check for $employee->department and $employee->department->depthead:
#if($employee->department)
#if($employee->department->depthead)
{{ $employee->department->depthead->first_name. ' ' .$employee->department->depthead->last_name }}
#else
None
#endif
#else
N/A
#endif
The defaults returned from a properly formed relationship will remove the need for string checks, meaning that #if($employee->department) and #if($employee->department->depthead) will be "truthy" or "falsey" enough to handle your use case.
Sidenote, this complexity is best moved to a Model function. In your Employee model, add this function:
public function getDepartmentHeadAttribute(){
if ($this->department) {
if ($this->department->depthead) {
return "{$this->department->depthead->first_name} {$this->department->depthead->last_name}";
} else {
return 'None';
}
} else {
return 'N/A';
}
}
Then, in your .blade.php file, you can simply do:
#foreach($employees as $employee)
{{ $employee->department_head }}
#endforeach
And it will perform the required if checks inside your Model and output First/Last, None or N/A as requird.
#if(!$employee->department->depthead)
look like the employee->department is not null, but it is not an object too ...
may be it is a string or number ....
#if(!$employee->department->depthead)
you could use 'is_object' method to determine that ...
#if( is_object($employee->department))
#if(!$employee->department->depthead)
....
#endIf
#endIf
but i don't think that the problem ...
the problem maybe you miss loading the relation,
if the property 'department' is a field of type 'json'
don't forget to cast it in model to 'array'

Laravel #foreach and #forelse

I have a problem with my view of laravel. I have a field that executes a loop, and if it has data in the field it list, but if it does not it only shows me nothing.
I used #forelse but it does not work, any help?
with $prices I can check whether or not it has the value, but in that fieldinfos_home does not.
I used #forelse but it does not work, any help?
<em>{{ $prices->price ?? ' - ' }}</em> <br>
#forelse($prices->infos_home as $info)
<em>{{ $info }}</em> <br>
#empty
<em> - </em>
#endforelse
When I use #forelse I have the following error message.
message: "Method Illuminate\View\View::__toString() must not throw an exception, caught ErrorException: Trying to get property 'infos_home' of non-object (View: C:\wamp64\www\suzuki-cms-backoffice\resources\views\brand\motorcycle\variations\index\column-price.blade.php)"
KISS and just use #if / #else:
<em>{{ $prices->price ?? ' - ' }}</em> <br>
#if($prices && $prices->infos_home)
#foreach($prices->infos_home as $info)
<em>{{ $info }}</em> <br>
#endforeach
#else
<em> - </em>
#endif
#forelse is good when you are sure that variable exists.

Laravel cicle foreach of a litteral object

I have this problem in my project in laravel.
I have a table Optional where $optional->column_name with the name of column of $bookingOptionals.
I have this code:
#foreach($optionals as $optional)
#if( $optional->column_name == 'coffee_break' ||
$optional->column_name == 'permanent_coffee' ||
$optional->column_name == 'permanent_coffeeplus'||
$optional->column_name == 'integrazione_permanentcoffee' ||
$optional->column_name == 'quick_lunch')
<div class="col-lg-3">
<fieldset>{{ $optional->nome }}</fieldset>
<input type="text" name="{{ $optional->column_name }}" value="{{ $bookingOptionals['0']->$optional->column_name }}">
</div>
#else
#endif
#endforeach
I have this error:
Trying to get property 'column_name' of non-object (View: /home/vagrant/code/prenotazioni/resources/views/dashboard/optional_booking_edit.blade.php)
use
#php
print_r($optional)
#endphp
inside your loop to see what fields it has and make sure column_name is exists,
and is $optional an object? or is it array? then you should remove raw php and probably use
$optional['column_name']
instead

Laravel Blade - check if data array has specific key

I need to check if the data array has a specific key, I tried it like this:
#if ( ! empty($data['currentOffset']) )
<p>Current Offset: {{ $currentOffset }} </p>
#else
<p>The key `currentOffset` is not in the data array</p>
#endif
But I always get <p>The keycurrentOffsetis not in the data array</p>.
You can use #isset:
#isset($data['currentOffset'])
{{-- currentOffset exists --}}
#endisset
I think you need something like this:
#if ( isset($data[$currentOffset]) )
...
Use following:
#if (array_key_exists('currentOffset', $data))
<p>Current Offset: {{ $data['currentOffset'] }} </p>
#else
<p>The key `currentOffset` is not in the data array</p>
#endif
ternary
#php ($currentOffset = isset($data['currentOffset']) ? $data['currentOffset'] : '')

Resources