Reputation: 714
I am using Laravel Translatables. But when I execute I got an error like Call to a member function hasTranslation() on null
. Here is my code.
<?php
if($slider->product->hasTranslation($locale))
{
$type = $slider->product->translate($locale)->product_name;
}
else{
$type = $slider->product->translate('en')->product_name;
} //echo $type; exit;
?>
$slider->product
is not null and $locale
has value 'en'
This code is working fine yesterday, the only change I made is, from the admin panel I just removed the required validation from add product field.
Upvotes: 0
Views: 2926
Reputation: 585
Check the setup of your relation $slider->product
is not null
and the model has use Translatable
trait
there is a helper method called optional()
optional($slider->product)->hasTranslation($locale)
this method will avoid to throw an exception.
NOT RECOMMENDED TO USE IT (optional()) IF $slider->product MUST HAVE A VALUE
just shortcut for clean code
if(optional($slider->product)->hasTranslation($locale))
$type = optional($slider->product)->translate($locale)->product_name;
else
$type = optional($slider->product)->translate('en')->product_name;
Upvotes: 2
Reputation: 714
I fixed this problem with another if
condition. Modified code is
<?php if(!empty($slider->product)) {
if($slider->product->hasTranslation($locale))
{
$type = $slider->product->translate($locale)->product_name;
}
else{
$type = $slider->product->translate('en')->product_name;
}
}
?>
Upvotes: 0