mardi 21 juin 2016

Unable to catch exceptions in Laravel 5.1

Unable to catch exception in laravel 5.1

      $companyID = $userprofile->company_id;                      
       try{                       
           $companies=Company::find($companyID)->first()->name;                   
        }catch (\Illuminate\Database\QueryException  $ex){
           dd($ex->getMessage());
       }



via Chebli Mohamed

lundi 20 juin 2016

Check particular role's permission in Vue JS and Laravel 5.1 + Entrust

I am using Zizaco/entrust in Laravel 5.1. I want explicitly give permissions to particular role by using checkboxes. This is my code: `

Fetching Roles:

fetchRoles: function(){
        this.$http.get('api/role',function(data){
            this.$set('roles',data);
        });
    }

Fetching Permissions:

fetchPermissions: function(){
            this.$http.get('api/permission',function(data){
                this.$set('permissions',data);
            });
        }

Here is the table for assigning roles and permissions:

<table class="table table-bordered table-responsive">
    <thead>                                                        
       <th>Permissions/Roles</th>
       <th v-for="role in roles">
           @
       </th>
    </thead>
    <tbody>
       <tr v-for="permission in permissions">
           <td>@</td>
           <td v-for="role in roles">
               <input type="checkbox" value="@" name="roles[@][permissions][]">
           </td>
       </tr>
    </tbody>
    <tfoot>
       <tr>
          <td>
              <button type="submit" class="btn btn-primary">Alter Permission</button>
          </td>
       </tr>
    </tfoot>
</table>

The output is like: Screenshot of Output

Permissions are also assigned successfully by following method:

public function changePermission(Request $request){
        $input = $request->all();
        $roles = Role::all();

        foreach($roles as $role)
        {
            $permissions_sync = isset($input['roles'][$role->id])? $input['roles'][$role->id]['permissions'] : [];
            $role->perms()->sync($permissions_sync);
        }
        Flash::success('Successfully modified permissions!');
        return redirect()->back();
    }

Only thing I am stucked in is making the checked boxed checked if the the role has particular permission.

I could do the following if it was in php object:

   @if(count($permissions)>0)
     @foreach($permissions as $permission)
     <tr>
     <td></td>
         @if(count($roles)>0)                                                          
            @foreach($roles as $role)
            <td><input type="checkbox" value="" name="roles[][permissions][]" @if($role->hasPermission($permission->name)) checked="checked" @endif></td>@endforeach @endif </tr> @endforeach @endif

How can I can hasPermission() method in Vue JS?



via Chebli Mohamed

How to create multi language menu in Laravel 5

What is the best way to create a multi language (main)menu in Laravel 5? And how to show menu items only when an user is logged-in?



via Chebli Mohamed

how to assign a hasMany role check in Laravel

In my website

I have a InitiatorController which looks like thi

class InitiatorController extends Controller
{

 use ExchangerateTrait;
 public function __construct(){

    $this->middleware('auth');
    $this->middleware('role:sales'); // replace 'collector' with whatever role you need.
}

 public function getIndex(){


            return redirect('initiator/home');
 }

}

Right now After authenticating I am checking if the user role is sales or not in Role middleware .

My role middleware looks like this.

class Role
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
        public function handle($request, Closure $next, $role){

            if ($request->user()->role != $role){

                    if($role=="collector" || $role=="admin" )
                    return Redirect::to('/');  
                    if($role=="director" || $role=="admin" )
                    return Redirect::to('/');  
                    if($role=="admin1" || $role=="admin" )
                    return Redirect::to('/');
                    if($role=="admin2" || $role=="admin" )
                    return Redirect::to('/');
                    if($role=="sales" || $role=="admin" )
                     return Redirect::to('/');
                    if($role=="developer" || $role=="admin" )
                     return Redirect::to('/');


            }

            return $next($request);
        }

}

Now I have a situation where role is director but he is also a sales man , How do i tackle this.

First Idea in controller

if I some how send an array of roles to the middleware something like this

$roles = array('director,sales,teamlead');
$this->middleware('role:$roles');

and then in Middle ware I can check like

if(in_array ($request->user()->role,$roles)){
      //do some thing
}
else
{
   //redirect to login 
}



via Chebli Mohamed

Protecting routes

I am trying to figure something out. I am using the following library It basically connects to LDAP so I can pull all my users from Active Directory. It is however just an extension of the built in Auth class.

What I do is get my users from LDAP. I then get my departments from LDAP. Finally, I link a user to a single department. To get all users for a particular department I can then do something like this

$department = Department::where('departmentName', 'Department A')->first();
$sdUsers = $department->user;

Now I only want to give access to some routes for users in Department A. I could pass these users to the view and do it this way but I think it will be messy. How can I use Middleware to restrict access based on a particular department?

Thanks



via Chebli Mohamed

Laravel 5.1 - Crud with ajax

Hi i'm doing a CRUD with ajax, i have a problem with store comment submited. I have this error:

QueryException in Connection.php line 655: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into comments (content, user_id, product_id, article_id, updated_at, created_at) values (my comment, , , , 2016-06-20 10:37:57, 2016-06-20 10:37:57))

i tryed to store a comment with text "my comment". My input "content" pass to my controller but my input hidden like "article_id", "user_id", "product_id" are not passing to my controller.

CommentController:

public function store(Request $request)
    {

        if($request->ajax()){
            $comment = new Comment();
            $comment->content = $request->input('content'); 
            $comment->user_id = $request->input('user_id'); 
            $comment->product_id = $request->input('product_id');
            $comment->article_id = $request->input('article_id');  

            $comment->save(); 


            return response()->json([

                "message" => "Comment pubblished!"
            ]);
        }
}

Form Comment article:

{!! Form::open(['route'=>'comment.store'] )!!}   



                                <div class="form-group">
                                    <label for="reply-text" class="sr-only">Commenta</label>


                                    {!! Form::textarea('content', null, ['id'=>'content','class'=>'form-control','rows'=>'3', 'placeholder'=>'Commenta','required'])!!}


                                </div>
                                <input type="hidden" id="token" name="_token" value="">
                                {!! Form::hidden('user_id', Auth::user()->id, null,['id'=>'user_id','class' =>'form-control'])!!}

                                {!! Form::hidden('article_id', $article->id, null,['id'=>'article_id','class' =>'form-control'])!!}

                                {!! Form::hidden('article_slug', $article->slug, null,['id'=>'article_slug','class' =>'form-control'])!!}

                                {!!link_to('#', $title='Comment post', $attributes =['id'=>'commento', 'class'=>'btn btn-lg btn-dark btn-outline'], $secure = null)!!} 

{!! Form::close()!!}

comment.js :

$("#commento").click(function(){

    var dato= $("#content").val();
    var dato2= $("#user_id").val();
    var dato3= $("#article_id").val();
    var dato4= $("#product_id").val();
    var route = "http://localhost:8000/comment";
    var token = $("#token").val();

    $.ajax({
        url: route,
        headers:{'X-CSRF-TOKEN':token},
        type: 'POST',
        dataType: 'json',
        data:{
            content: dato, 
            user_id: dato2, 
            article_id: dato3, 
            product_id: dato4
        },


    });

});



via Chebli Mohamed

Filtering on Laravel

i have project, in there i want to add filter fiture in there. i can make it but i have bug in my script. when i create new data booking in same title/post the filter list is increase and have same title/post. but in there i just want to make list of them. its my error

wrong

its should be :

  • Kost Alpha Charlie Delta Echo
  • Kost Fanta Bintaro
  • Home Test

here my controller :

public function getIndex()
    {
        $list = DB::table('data_kos')
        ->orderBy('id','asc')
        ->get();

        $limit = 10;
        $result = DB::table('data_kos')
        ->orderBy('id','asc');
        if(Request::get('q')) {
            $q = Request::input("q");
            $posts->where('title','like','%'.Request::get('q').'%');
            $posts->orwhere("sex","like","%".Request::get("q")."%");
            $posts->orwhere("price","like","%".Request::get("q")."%");
        }
        if(Request::get('title')) {
            $result = $result->where("title",Request::get("title"));
        }
        $data['list'] = $list;
        $data['posts'] = $result->paginate($limit);
        return view('kost', $data);
    }

and this my view :

@foreach($list as $row)
        <li><a href=''></a></li>
        @endforeach

have someone give me solution ? what i need to change in my code.



via Chebli Mohamed