0

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.

geeth
  • 704
  • 2
  • 14
  • 42
  • Is your model setup correct? Does it use the trait? Are you sure `$slider->product` is not null? – brombeer Dec 27 '18 at 09:11
  • @kerbholz for some products `$slider->product` is empty because it is not a mandatory field. So what modifications needed in my code. I am new to laravel – geeth Dec 27 '18 at 09:25

2 Answers2

2

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;
Ahmad Elkenany
  • 575
  • 5
  • 23
0

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;
        }
    }
?>
geeth
  • 704
  • 2
  • 14
  • 42