Foreach循环if和else条件无法正常工作

时间:2019-05-23 08:23:28

标签: php laravel laravel-5

我被该代码所困扰,代码正常工作,但是在index.blade.php foreach循环中无法正常工作。我尝试显示一个用户是否阻止了多个用户,然后“取消阻止”按钮仅在该用户的个人资料中显示给该用户,否则显示阻止按钮给所有人。

这是我的UserController

public function blockUser(Request $request, $username){

         $blocked = User::where('id', Auth::user()->id)->first();
            if (blockuser::where("block_username", "=", $username)->first())
          {
              $blocked = blockuser::where('block_username', $username)->first();
                 $blocked->delete();

          }else{

               $blocked = new blockuser;
                 $blocked->user_username = $request->user_username;
                 $blocked->block_username = $request->block_username;
                 $blocked->b_status = '1';
                 $blocked->save();
                }
               $user = User::where('username', $username)->first();
               $userprofile = userprofile::where('user_id', Auth::user()->id)->first();
               $blocked = blockuser::where('user_username', Auth::user()->username)->get();
               return view('profile.index',compact('user', 'userprofile', 'blocked'));


   }

如果数据为空,则显示阻止按钮,并且一个用户阻止了另一个用户的“取消阻止”按钮,也显示正确,但是单击取消阻止按钮后 否则条件不起作用,阻止按钮不显示。 我该怎么办,请帮帮我。

这是profile / index.blade.php

    @foreach($blocked as $block)
                   @if(empty($block->user_username ))
                     <a href="#0" class="cd-popup-trigger">Block</a>

                   @else
                        @if(Auth::user()->username == $block->user_username and $user->username == $block->block_username)
                         <a href="#0" class="cd-popup-trigger">Unblock</a>
                         @else
                            <a href="#0" class="cd-popup-trigger">Block</a>
                        @endif
                    @endif
   @endforeach  

这是我的block_users表

id    user_username   block_username
1      
2
3
4

1 个答案:

答案 0 :(得分:0)

First Make it Sure blockuser is Correct Model Name
//First Solution 
$blocked = User::where('id', Auth::user()->id)->first();
$get_blockuser= blockuser::where("block_username", "=", $username)->first();
            if($get_blockuser)// Or Use if(!empty($get_blockuser))
          {
              $blocked = blockuser::where('block_username', $username)->first();
              $blocked->delete();
          }
//Second Solution
$blocked = User::where('id', Auth::user()->id)->first();
$get_blockuser= blockuser::where("block_username", "=", $username)->get();
            if(count($get_blockuser)>0)
          {
              $blocked = blockuser::where('block_username', $username)->first();
              $blocked->delete();
          }