只在Laravel中显示loged-in用户的按钮

时间:2017-10-12 07:12:22

标签: javascript php laravel laravelcollective

如果我以John身份登录,我怎样才能显示John的红色按钮而不是Susan的红色按钮?

测试系统环境: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 个答案:

答案 0 :(得分:3)

使用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

答案 1 :(得分:2)

据我所知,您只想在属于该用户的行上显示该按钮。

这是一个轻微的假设,但我假设在该作业行上存在某种用户标识符 - 理想情况下类似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_name(我认为这是唯一的?):

@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

答案 2 :(得分:0)

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