Home > Enterprise >  Laravel crud show on empty
Laravel crud show on empty

Time:09-30

I have a laravel crud with relations. but when i want to load the page some table rows dont have a value. and this gives the error: 'Attempt to read property "name" on null'

But how do i ignore this message and keep loading in the page?

index.blade:

    @foreach($files as $file)
        <tr>
            <td>{{$file->id}}</td>
            <td>{{$file->title}} </td>
            <td>{{$file->description_short}} </td>
            <td>{{$file->description_long}} </td>
            <td>{{$file->file}}</td>
            <td>{{$file->language->name}} </td>
            <td>{{$file->subfolder->name}} </td>
          
            <td>{{$file->role->name}} </td>
            <td>
                <a href="{{ route('admin.file.edit',$file->id)}}" >Edit</a>
            </td>
            <td>
                <form action="{{ route('admin.file.destroy', $file->id)}}" method="post">
                  @csrf
                  @method('DELETE')
                  <button  type="submit">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </tbody>
  </table>

controller:

 public function index()
    {
        $files = File::with('subfolder', 'language', 'tag')->get();
        $languages = Language::all();
        $tags = Tag::all();
        $subfolders = Subfolder::all();
        $users = User::all();    
        return view('admin.file.index', compact('files', 'languages', 'tags', 'users', 'subfolders'));
    }

i want the index to ignore all the NULL properties

CodePudding user response:

Using the @ before your php Variable will work for you like below.

{{@$file->language->name}} 

CodePudding user response:

And also, by using

{{ $file->language->name ?? '' }}

CodePudding user response:

There are various ways:

  • Error control operator:

    @$file->language->name the @ operator suppress the errors messages (imho not very clean :) , but same result)

    From documentation:

    // Note: The @-operator works only on expressions. A simple rule of thumb   is: if one can take the value of something, then one can prepend the @ operator to it.
    // For instance, it can be prepended to variables, functions calls, certain language construct calls (e.g. include), and so forth. 
    // It cannot be prepended to function or class definitions, or conditional structures such as if and foreach, and so forth.
    

  • Classical ternary operator way

    $file->language ? $file->language->name : null;


  • From PHP7 : Null Coalescing Operator

    $file->language->name ?? null;


  • From PHP8 : null safe Operator

    $file->language?->name; (amazing! :-))


  • Related