代码之家  ›  专栏  ›  技术社区  ›  JsWizard

仅向Laravel中登录的用户显示按钮

  •  4
  • JsWizard  · 技术社区  · 8 年前

    如果我以约翰的身份登录,我怎么能只显示约翰的红色按钮而不是苏珊的按钮?

    测试系统环境:Win10、Laravel5.4、Mysql5.7.19。

    enter image description here

    <table class="table table-responsive" id="jobs-table">
        ...
        @foreach($jobs as $job)
            <tr>
                <td>{!! $job->user_name !!}</td>
                ...
                <td>{!! $job->created_at !!}</td>
                <td>
                    {!! Form::open(['route' => ['jobs.destroy', $job->id], 'method' => 'delete']) !!}
                    <div class='btn-group'>
                        <a href="{!! route('jobs.show', [$job->id]) !!}" class='btn btn-default btn-xs'><i class="glyphicon glyphicon-eye-open"></i></a>
                        <a href="{!! route('jobs.edit', [$job->id]) !!}" class='btn btn-default btn-xs'><i class="glyphicon glyphicon-edit"></i></a>
                        {!! Form::button('<i class="glyphicon glyphicon-stop"></i>', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs', 'onclick' => "return confirm('Are you sure to Stop?')"]) !!}
                    </div>
                    {!! Form::close() !!}                  
                </td>
            </tr>
        @endforeach
    
    3 回复  |  直到 8 年前
        1
  •  4
  •   Alexey Mezenin    8 年前

    使用Laravel policies 特点:

    @can('delete', $job)
        {!! Form::button('<i class="glyphicon glyphicon-stop"></i>', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs', 'onclick' => "return confirm('Are you sure to Stop?')"]) !!}
    @endcan
    

    @if (auth()->user()->can('delete', $job))
        {!! Form::button('<i class="glyphicon glyphicon-stop"></i>', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs', 'onclick' => "return confirm('Are you sure to Stop?')"]) !!}
    @endif
    
        2
  •  3
  •   James    8 年前

    这只是一个小小的假设,但我假设该作业行上有某种用户标识符-理想情况下类似于 user_id 将行链接到关联用户的。

    如果是这样的话,那么你可以对这个按钮使用一个简单的If语句。

    以下内容适用于您所拥有的:

    @if ($job->user_id == Auth::id())
        {!! Form::button('<i class="glyphicon glyphicon-stop"></i>', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs', 'onclick' => "return confirm('Are you sure to Stop?')"]) !!}
    @endif
    

    如果您不使用用户标识符,而只存储用户名,那么下面类似的内容可以使用-使用user\u名称(我假设这是唯一的?):

    @if ($job->user_name == Auth::user()->user_name)
        {!! Form::button('<i class="glyphicon glyphicon-stop"></i>', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs', 'onclick' => "return confirm('Are you sure to Stop?')"]) !!}
    @endif
    
        3
  •  0
  •   user8763858 user8763858    8 年前

    添加角色系统将使这更容易,因此请考虑添加角色系统

    推荐文章