A
A
Alexander Afanasiev2017-09-13 10:47:01
Laravel
Alexander Afanasiev, 2017-09-13 10:47:01

How to correctly display an empty object in laravel?

Hello. I'm starting to learn OOP and Laravel.
I want to select an object from the database:

$worker_info =  DB::table('workers')->select(  DB::raw('   workers.id as wid, workers.first_name, organizations.name as org_name' ) )
->leftJoin('organizations', 'workers.organization_id', '=', 'organizations.id')
->where('workers.id', $worker_id)
->first();

I get an object:
dump($worker_info);
{#194 ▼
  +"wid": 1
  +"first_name": "Петр"
 + "org_name": "Рога и копыта"
}

Output in template:
{{ $worker_info->wid}}
{{ $worker_info->first_name}}
{{ $worker_info->org_name}}

The problem starts when the object is not found, $worker_info=null. output {{ $worker_info->wid}} will not work, since null does not have wid and first_name fields.
Of course, you can write if($worker_info==null) { "No value" },
but the output of information occurs in different places in the template, so the template will be full of ifs, or the if will contain too much of the template.
Is it possible somehow in the controller to set empty values ​​to the fields of the object, that is, to create it? i.e. create exactly the same object? it is natural that $worker_info = new Worker creates another object (other fields, no information about the organization)
I would just like it to display {{ $worker_info->wid}} in the template and if it is set, then the value will be displayed, if not set, the value will be displayed by default or at least the empty string.
Maybe the whole approach is fundamentally wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad, 2017-09-13
@XanderEVG

Hey! Maybe a link will help

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question