Home > Software design >  How to display content if data is empty in laravel?
How to display content if data is empty in laravel?

Time:11-09

I'm using Laravel 8. I'm trying to display a <section> if the User's littlelink_pixiv field is empty. I'm getting error: Call to a member function isEmpty() on null. Does anyone know how to fix this? The IF condition I used is:

@if(!$info->littlelink_pixiv->isEmpty())
<section>
  <main class="card__wrapper">
  </main>
</section>
@endif

UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

use Auth;
use DB;

use App\Models\User;
use App\Models\Button;
use App\Models\Link;


class UserController extends Controller
{

    //Statistics of the number of clicks and links 
    public function index()
    {
        $userId = Auth::user()->id;

        $littlelink_name = Auth::user()->littlelink_name;

        $links = Link::where('user_id', $userId)->select('link')->count();

        $clicks = Link::where('user_id', $userId)->sum('click_number');

        return view('studio/index', ['littlelink_name' => $littlelink_name, 'links' => $links, 'clicks' => $clicks]);
    }

    //Show littlelink page. example => http://127.0.0.1:8000/ admin
    public function littlelink(request $request)
    {
        $littlelink_name = $request->littlelink;
        $id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');

        if (empty($id)) {
            return abort(404);
        }
        
        $information = User::select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->where('id', $id)->get();
        
        $links = DB::table('links')->join('buttons', 'buttons.id', '=', 'links.button_id')->select('links.link', 'links.id', 'buttons.name')->where('user_id', $id)->orderBy('up_link', 'asc')->get();

        return view('littlelink', ['information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
    }

    //Show buttons for add link
    public function showButtons()
    {
        $data['buttons'] = Button::select('name')->get();
        return view('studio/add-link', $data);
    }

    //Save add link
    public function addLink(request $request)
    {
        $request->validate([
            'link' => 'required|url',
            'button' => 'required'
        ]);

        $link = $request->link;
        $button = $request->button;

        $userId = Auth::user()->id;
        $buttonId = Button::select('id')->where('name' , $button)->value('id');

        $links = new Link;
        $links->link = $link;
        $links->user_id = $userId;
        $links->button_id = $buttonId;
        $links->save();

        return back()->with('message', 'Link Added');
    }

    //Count the number of clicks and redirect to link
    public function clickNumber(request $request)
    {
        $link = $request->link;
        $linkId = $request->id;

        if(empty($link && $linkId))
        {
            return abort(404);
        }

        Link::where('id', $linkId)->increment('click_number', 1);

        return redirect()->away($link);
    }
    
    //Show link, click number, up link in links page
    public function showLinks()
    {
        $userId = Auth::user()->id;
        
        $data['links'] = Link::select('id', 'link', 'click_number', 'up_link')->where('user_id', $userId)->orderBy('created_at', 'desc')->paginate(10);
        return view('studio/links', $data);
    }

    //Delete link
    public function deleteLink(request $request)
    {
        $linkId = $request->id;

        Link::where('id', $linkId)->delete();
        
        return back();
    }

    //Raise link on the littlelink page
    public function upLink(request $request)
    {
        $linkId = $request->id;
        $upLink = $request->up;

        if($upLink == 'yes'){
            $up = 'no';
        }elseif($upLink == 'no'){
            $up = 'yes';
        }

        Link::where('id', $linkId)->update(['up_link' => $up]);

        return back();
    }

    //Show link to edit
    public function showLink(request $request)
    {
        $linkId = $request->id;

        $link = Link::where('id', $linkId)->value('link');

        $buttons = Button::select('name')->get();
       
        return view('studio/edit-link', ['buttons' => $buttons, 'link' => $link, 'id' => $linkId]);

    }

    //Save edit link
    public function editLink(request $request)
    {
        $request->validate([
            'link' => 'required|url',
            'button' => 'required',
        ]);

        $link = $request->link;
        $button = $request->button;
        $linkId = $request->id;

        $buttonId = Button::select('id')->where('name' , $button)->value('id');

        Link::where('id', $linkId)->update(['link' => $link, 'button_id' => $buttonId]);

        return redirect('/studio/links');
    }

    //Show littlelinke page for edit
    public function showPage(request $request)
    {
        $userId = Auth::user()->id;

        $data['pages'] = User::where('id', $userId)->select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->get();

        return view('/studio/page', $data);
    }

    //Save littlelink page (name, description, logo)
    public function editPage(request $request)
    {
        
    $request->validate([
        'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
        'pageName' => 'nullable|alpha_dash',
        'pageColor' => 'nullable',
        'pageFontcolor' => 'nullable',
        'pageDescription' => 'nullable|regex:/^[\w.\- ] $/i',
        'pagePixiv' => 'nullable|url',
        ]);
        
        $userId = Auth::user()->id;
        $littlelink_name = Auth::user()->littlelink_name;

        $profilePhoto = $request->file('image');
        $pageName = $request->pageName;
        $pageColor = $request->pageColor;
        $pageFontcolor = $request->pageFontcolor;
        $pageDescription = $request->pageDescription;
        $pagePixiv = $request->pagePixiv;
        
        User::where('id', $userId)->update(['littlelink_name' => $pageName, 'littlelink_color' => $pageColor, 'littlelink_fontcolor' => $pageFontcolor, 'littlelink_pixiv' => $pagePixiv, 'littlelink_description' => $pageDescription]);

        if(!empty($profilePhoto)){
        $profilePhoto->move(public_path('/img'), $littlelink_name . ".png");
        }

        return back()->with('message', 'Saved');
    }

    //Show user (name, email, password)
    public function showProfile()
    {
        $userId = Auth::user()->id;

        $data['profile'] = User::where('id', $userId)->select('name', 'email')->get();

        return view('/studio/profile', $data);
    }

    //Save user (name, email, password)
    public function editProfile(request $request)
    {
        $request->validate([
            'name' => 'required|unique:users',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8',
        ]);

        $userId = Auth::user()->id;

        $name = $request->name;
        $email = $request->email;
        $password = Hash::make($request->password);

        User::where('id', $userId)->update(['name' => $name, 'email' => $email, 'password' => $password]);

        return back();
    }
}

littlelink.blade.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
@foreach($information as $info)
<style>
    body {background-color:<?php echo $info->littlelink_color ?>}
    </style>
</head>

<body>
<!DOCTYPE html>
<html lang="en">
<head>

  <!-- Page Information
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta charset="utf-8">
  <title>{{ $littlelink_name }} ?? {{ config('app.name') }} </title>
  <meta name="description" content="Find us online!">
  <meta name="author" content="Seth Cottle">

  <!-- Mobile Specific Metas
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- FONT
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
    <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" rel="stylesheet">

  <!-- CSS
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="stylesheet" href="{{ asset('littlelink/css/normalize.css') }}">
  <link rel="stylesheet" href="{{ asset('littlelink/css/skeleton-light.css') }}">
  <link rel="stylesheet" href="{{ asset('littlelink/css/brands.css') }}">

  <!-- Favicon
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="icon" type="image/png" href="{{ asset('littlelink/images/avatar.png') }}">

</head>
<body>

  <!-- Primary Page Layout
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <div class="container">
    <div class="row">

      <div class="column" style="margin-top: 10%">
        <!-- Your Image Here -->
          @if(file_exists(public_path("img/$littlelink_name" . ".png" )))
          <div class="image-cropper">
          <img src="{{ asset("img/$littlelink_name" . ".png") }}" srcset="{{ asset("img/$littlelink_name" . "@2x.png 2x") }}" hljs-string">" width="200px" height="200px">
          </div>
          @else
          <div hljs-string">">
          <img src="{{ asset('littlelink/images/profiledefault.png') }}">
          </div>
          @endif

        
        <!-- Your Name -->
        <h1>{{ $info->littlelink_name }}</h1>
        <!-- Short Bio -->
        <p>{{ $info->littlelink_description }}</p>
        
        <!-- Pixiv Info -->
        <script>
var apidata = "<?php echo $info->littlelink_pixiv ?>";
var pixid = apidata.replace( /^\D /g, '');
const url = 'https://api.adoreanime.com/api/pixiv/?type=member_illust&id='   pixid   '&page=1';
fetchData(url);
function fetchData(url) {
  fetch(url).then((response) => response.json()).then(function(data) {
    var p = data.illusts.slice(0, 6).map(art => {
      var imgSrc = art.image_urls.medium.replace('i.pximg.net', 'img.adoreanime.com');
      var nsfw = art.x_restrict ? "blur" : ""
      return `<div hljs-string">">
          ${nsfw && '<span hljs-string">">R-18</span>'}
          <div hljs-string">"><a href="https://www.pixiv.net/en/artworks/${art.id}" target="_blank" rel="noopener noreferrer"><img src=${imgSrc} alt="image"/></a></div>
          </div>`
    })
    var x = document.getElementsByClassName('card__wrapper');
    var y = p.join(' ');
    x[0].innerHTML = y;
  })
}
</script>

@if(!$info->littlelink_pixiv->isEmpty())
<section>
  <main class="card__wrapper">
  </main>
</section>
@endif
        
        @endforeach
        <!-- Buttons -->
        @foreach($links as $link)
         @php $linkName = str_replace('default ','',$link->name) @endphp
        <a class="button button-{{ $link->name }}" href="{{ route('clickNumber') . '/' . $link->id . '/' . $link->link}}" target="_blank"><img hljs-string">" src="{{ asset('\/littlelink/icons\/') . $linkName }}.svg">{{ ucfirst($linkName) }}</a>
          <br>
        @endforeach

        <span hljs-string">">Powered by <img hljs-string">" src="{{ asset('littlelink/images/logo.svg') }}"></span>
          
      </div>
    </div>
  </div>

<!-- End Document
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
</body>
</html>
</body>
</html>

CodePudding user response:

Because null is a falsy value:

@if(!$info->littlelink_pixiv)

CodePudding user response:

You can write this code {{ $info->littlelink_pixiv ?? '' }} to make variable optional in the blade template and print the variable if it has a value

CodePudding user response:

use this it may be work for you. !$info->littlelink_pixiv == null

  • Related