0

I need to check if any or all of several database table fields are empty and if any of them are return a class in HTML (or Blade).

At the moment I do this:

<body class="app @if (Auth::user()->site_title == '' | Auth::user()->full_name == '' | Auth::user()->country == '' | Auth::user()->city == '') newuser @endif">

If the fields are empty it prompts a modal for the user to complete them.

Everything works great but I'm hoping for a cleaner way to do this as I need to use the same @if statement again to hide/show a modal accordingly at the bottom of the page.

Maybe return something from the User Model?

1
  • I don't see any reason not to extract the if conditions to a User method. Then you could "Auth::user()->isNew()" to shorten it up. Commented Jul 11, 2015 at 19:10

2 Answers 2

2

Define a method on your authentication model that returns a boolean.

Something like this:

public function isNew()
{
    $attributes = ['site_title', 'full_name', 'country', 'city'];
    foreach ($attributes as $attribute) {
        if (empty($this->$attribute)) {
            return true;
        }
    }

    return false;
}

Then in your view you simply check against this method:

 <body class="app @if (Auth::user()->isNew()) newuser @endif">
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks this looks like what I need, how do I assign the field names as attributes?
I did actually work that out, but I get this error Call to undefined function App\Models\is_empty() which I cant work out why. Also tried isEmpty
My bad, the correct function name is empty; mixed it up with is_null
0

You could do this check in the controller, assign the result to a variable and pass it to the view. That way, you can easily use this variable any number of times in the view.

Another (perhaps cleaner) way, would be to do it in the User model. You could put this logic in a method User::isNewUser() and call that from your controller or directly from your view.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.