Ad

Return Result According To Authenticated User In Laravel

- 1 answer

I have a list of users where there are four different user types('SA','Admin','User','Candidate') and I am displaying them using yajrah datatable and what i am trying to do is that when the SA is logged in then the list should have only Admin,User and Candidate.

Similarly when Admin logins then the list should return only Candidate and Users.

My Front-end: Front-End

I don't know how to pass query for that

my Users datatable

class UsersDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {       
        return datatables()
            ->eloquent($query)
            ->addColumn('action', function($data){
                            $button = '<a target="_blank" rel="nofollow noreferrer" href="'.route('user.edit',$data->id).'"><button type="submit"  name="edit" id="'.$data->id.'" 
                             class="edit btn btn-primary btn-sm">Edit</button></a>';
                            $button .= '<a><form action="user/'.$data->id.'
                            " method="post">
                            '.csrf_field().'
                            '.method_field('DELETE').'
                            <button type="submit"  name="delete" id="'.$data->id.'" 
                            class="delete btn btn-danger btn-sm">Delete</button></form></a>';
                            return $button;
                    });
    }   

    /**
     * Get query source of dataTable.
     *
     * @param \App\User $user
     * @return \Illuminate\Database\Eloquent\Builder
     */

    public function query(User $user)
    {   
       return $user->newQuery();
       }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */

    public function html()
    {    
        return $this->builder()
                    ->setTableId('user')
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->dom('frltip');

    }

    /**
     * Get columns.
     *
     * @return array
     */

    protected function getColumns()
    {
        return [
            Column::make('id'),
            Column::make('name'),
            Column::make('email'),
            Column::make('usertype'),
            Column::make('created_at'),
            Column::make('action'),
        ];
    }

My controller :

  /**
     * Display a list of the users
     *
     * @param  \App\DataTable\UsersDataTable  $dataTable
     * @return \Illuminate\View\View
     */

    public function index(UsersDataTable $dataTable)
    {   
        return $dataTable->render('users.index');
    }

my migration:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->softemail();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->enum('usertype', ['super admin','admin', 'user','candidate']);
            $table->rememberToken();
            $table->timestamps();
        });
    }

Any help will be appreciated.

Ad

Answer

Datatable

<?php

namespace App\DataTables;

use App\User;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;

class UsersDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {      

        return datatables()
            ->eloquent($query)
            ->addColumn('action', function($data){
                            $button = '<a target="_blank" rel="nofollow noreferrer" href="'.route('user.edit',$data->id).'"><button type="submit"  name="edit" id="'.$data->id.'" 
                             class="btnedit btn btn-primary btn-sm">Edit</button></a>';
                            $button.= '<form action="user/'.$data->id.'
                            " method="post">
                            '.csrf_field().'
                            '.method_field('DELETE').'
                            <button type="submit"  name="delete" id="'.$data->id.'" 
                            class="btndelete btn btn-danger btn-sm">Delete</button></form>';
                            return $button;
                    });
    }  

    /**
     * Displays the list of users according to the usertype
     * 
     * @param \App\User $user
     */

    public function getUserByType($user)
    {

        if($user->usertype === 'super admin')
        {
            $users=$user->isSuperAdmin();
        }
        elseif($user->usertype === 'admin')
        {
            $users=$user->isAdmin();
        }
        elseif($user->usertype === 'user')
        {
            $users=$user->isUser();}
        else
        {
            abort(404);
            //throw new Exception('Not Authorized');    
        }

        return $users;
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\User $user
     * @return \Illuminate\Database\Eloquent\Builder
     */

    public function query(User $user)
    {   

       $user=auth()->user();
       $users=$this->getUserByType($user);
       return datatables()->of($users);

    }   

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */

    public function html()
    {    

        return $this->builder()
                    ->setTableId('user')
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->dom('frltip');

    }

    /**
     * Get columns.
     *
     * @return array
     */

    protected function getColumns()
    {
        return [
            Column::make('id'),
            Column::make('name'),
            Column::make('email'),
            Column::make('usertype'),
            Column::make('created_at'),
            Column::make('action')->width('20%'),
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        //return 'Users_' . date('YmdHis');
    }

}

There are no changes in the controller , it remains the same , however the problem is solved using function in which i filtered out the query according to the authenticated user

you have to add the following in the model, u can also do it your way, this is not necessary.

/**
     * Shows the list of users when super admin is logged in
     *
     */   

    public function isSuperAdmin()
    {
        return $this->where('usertype','<>','Super Admin');
    }

    /**
     * Shows the list of users when  admin is logged in
     *
     */   

    public function isAdmin()
    {
        return $this->where('usertype','<>','Super Admin')->where('usertype','<>','Admin') ;
    }

    /**
     * Shows the list of users when user is logged in
     *
     */   

    public function isUser()
    {
        return $this->where('usertype','candidate');
    }

Ad
source: stackoverflow.com
Ad