Latest

Monday, July 10, 2017

How to ignore html if data is empty in Laravel?

Asked by: Than Htut Oo


I am trying to retrieve data from database and check if the data is empty or not. What problem I am facing is that html is showing even if the data is empty. I want to ignore the html tag like example ul li. Here how i tried is like

@if(!empty($jobseekers->skill_1))
   <li> My Skill is : {{ \App\skill::where('id',$jobseekers->skill_1)->pluck('name')->first() }}</li><br/>
@endif

I want to ignore "My Skill is " if the data is empty. I don't want to show anything.


Answers

Answered by: Patrick_design at 2017-07-10 11:36PM



Check if the variable is empty or not, and set the display of your li to none as appropriate.



Answered by: Mohammad b at 2017-07-11 12:56AM



If you get $jobseekers with get() method you can not use empty($jobseekers )

instead of empty you can use other conditions :

@if($jobseekers->skill_1 != '')

in this condition you check skill_1 as empty string

also

@if($jobseekers->skill_1)

and etc

replace your code with below code and check it:

@if($jobseekers->skill_1 != '')
   <li> My Skill is : {{ \App\skill::where('id',$jobseekers->skill_1)-pluck('name')->first() }}</li><br/>
@endif


Answered by: Mina Shaigan at 2017-07-11 03:13AM



you should use isset()

@if(isset($jobseekers->skill_1))
    <li> My Skill is : {{ \App\skill::where('id',$jobseekers->skill_1)->pluck('name')->first() }}</li><br/>
@endif


Answered by: Sagar Gautam at 2017-07-11 08:00AM Accepted



When using ->get() you can't simply use any of the below:

if (empty($jobseekers->skill_1)) { }

if (!$jobseekers->skill_1) { }

if ($jobseekers->skill_1) { }

But, When you are getting data with first() method, You can simply use all above methods.

Because if you dd($jobseekers->skill_1); you'll notice an instance of Illuminate\Support\Collection is always returned, even when there are no results.

I think you are using !empty() on data with ->get() method which will always return true even data is empty. You need to use other way.

To determine if there are any results you can do any of the following:

if (!$jobseekers->skill_1->isEmpty()) { }

if ($jobseekers->skill_1->count()) { }

if (count($jobseekers->skill_1)) { }


Answered by: Kuldeep Mishra at 2017-07-11 01:07PM



**you can use count **
@if(count($jobseekers->skill_1)>0)

  • My Skill is : {{ \App\skill::where('id',$jobseekers->skill_1)->pluck('name')->first() }}

  • @endif




    Source

    No comments:

    Post a Comment

    Adbox