lundi 17 mai 2021

Add v-select in Tabulator

I am using tabulator in my project along with vue3. I have successfully added tabulator and now I want to add v-select in tabulator. So how is it possible and what are the ways to achieve it?



via Chebli Mohamed

Return array of grouped results

Note: I'm using Laravel 5.3.

I have a table, comments, that looks like this:

+====+=========+
| id | message |
+====+=========+
|  1 |      Hi |
|  2 |   World |
+====+=========+

I have a second table, comment_stats, which keeps track of the total number of votes on each comment, that looks like this:

+====+============+=======+
| id | comment_id | votes |
+====+============+=======+
|  1 |          1 |    10 |
|  2 |          2 |     0 |
+====+============+=======+

And lastly, I have a third table, comment_votes, which keeps track of each individual user's vote for each comment, that looks like this:

+====+============+=========+=========+
| id | comment_id | user_id |    type |
+====+============+=========+=========+
|  1 |          1 |      10 |       0 |
|  2 |          1 |       9 |       0 |
|  3 |          1 |       8 |       1 |
|  4 |          1 |       7 |       2 |
|  5 |          1 |       6 |       1 |
|  6 |          1 |       5 |       5 |
|  7 |          1 |       4 |       3 |
|  8 |          1 |       3 |       3 |
|  9 |          1 |       2 |       1 |
| 10 |          1 |       1 |       0 |
+====+============+=========+=========+

As you can see, each comment can be voted on by other users (comment_votes) and the total votes are kept track of in comment_stats. Each vote has a type. There are a total of 6 possible types (0-5).

My current Comment.php class looks like:

class Comment extends Model
{
    protected $with = [
        'votes', 'stats'
    ];

    public function votes()
    {
        return $this->hasMany('App\Vote');
    }

    public function stats()
    {
        return $this->hasOne('App\Stat');
    }
}

My Stat.php class looks like:

class Stat extends Model
{
    protected $with = [
        'topTypes'
    ];

    public function comment()
    {
        return $this->belongsTo('App\Comment');
    }

    public function topTypes()
    {
        // Need to return an array of the top 3 types here
    }
}

And my Vote.php class looks like:

class Vote extends Model
{
    public function comment()
    {
        return $this->belongsTo('App\Comment');
    }
}

I'd like to retrieve the top 3 vote types for each comment. So for comment_id = 1, the output would be [0, 1, 3] (as an array), in that order. 0 appears 3 times, 1 appears 3 times, and 3 appears twice. If there is a tie, it should get the lower integer type.

I'm trying to get the JSON to end up looking something like this, so that the top_types is part of stats:

{
    "id": 1,
    "message": "Hi",
    "stats": {
        "id": 1,
        "comment_id": 1,
        "votes": 10,
        "top_types": [0, 1, 3]
    }
}

How could I achieve this? All of these relationships are driving me insane.



via Chebli Mohamed

Upload multiple images in Vue.js and Laravel

I'm trying to upload multiple files at once in vue.js and laravel, Code that i'm using is :

Vue.js code:

 <input type="file" v-validate="'required'" multiple @change="uploadDegree" name="uploadDegree" placeholder="Upload Degree"/>

  uploadDegree(e)
            {
                for (let file of e.target.files) {
                    try {
                        let reader = new FileReader();
                         reader.onloadend = file => {
                         this.user.degree_attachment= reader.result;
                        };
                        reader.readAsDataURL(file);                      
                    } catch {}
                }
              }

Laravel Code:

 $files = $request->input('degree_attachment');
           foreach($files as $file) {
               $degreename = time() . '.' . explode('/', explode(':', substr($file, 0, strpos($file, ';')))[1])[1];
                $pathDegreeExist = public_path("img/degree_img/"); 
                if(!File::exists($pathDegreeExist)) File::makeDirectory($pathDegreeExist, 777);
                $img = \Image::make($file);
                $img->save(public_path('img/degree_img/').$degreename); 
                $newUser->degree_attachment = $degreename;
            }

I'm getting this error :

Invalid argument supplied for foreach()

where i'm trying to get image,



via Chebli Mohamed

Checkbox does not work when clicking on it

I change this code: Demo1

<li class="nav-item">
   <span class="nav-switch" href="#">
     <span class="language" id="eg">EG</span>
       <label class="switch">
           <input type="checkbox">
           <span class="slider round"></span>
      </label>
    <span  class="language" id="ar">AR</span>
  </span>
</li>

To this code: Demo2

<li class="nav-item">
   <span class="nav-switch" href="#">
     <span class="language" id="eg">EG</span>
       <a class="switch">
           <input type="checkbox">
           <span class="slider round"></span>
       </a>
    <span  class="language" id="ar">AR</span>
  </span>
</li>

To be able to take action when changing from one language to another using the checkbox but after making that change, the color of the checkbox does not change as in Demo1, I need to take action because I use PHP/Laravel



via Chebli Mohamed

dimanche 16 mai 2021

Query returns when selecting *, but not when selecting specific column

In one of my model classes, I have the following relationship/query:

public function topTypes()
{
    return $this->votes()
        ->selectRaw('*, COUNT(comment_votes.type_id) as types_count')
        ->groupBy('comment_votes.type_id')
        ->orderBy('types_count', 'desc');
}

public function votes()
{
    return $this->hasMany('App\CommentVote', 'comment_id', 'comment_id');
}

When this gets executed, it returns successfully:

            "top_types" : [
              {
                "comment_id" : 461,
                "id" : 536,
                "type_id" : 0,
                "types_count" : 1,
                "user_id" : 58
              }
            ],

But really what I want it to return is just:

            "top_types" : [0],

Where 0 is the type_id.

When I try changing the selectRaw portion of the query to:

public function topTypes()
{
    return $this->votes()
        ->selectRaw('comment_votes.type_id, COUNT(comment_votes.type_id) as types_count')
        ->groupBy('comment_votes.type_id')
        ->orderBy('types_count', 'desc');
}

It just outputs an empty array:

            "top_types" : [

            ],

What am I doing wrong here?



via Chebli Mohamed

Laravel server side form validation, Validate field length(Size) with more than one option

I'm using ajax to make a server side form validation in laravel. All my validations are working fine except for one which i can figure out how to do it. Actually i have a field in my form for the ID number, which can take either 7 caracters for passport number, 9 caracters for ID card number or 20 caracters for temporary ID card number. How can i set a validation for size or lenght with 3 differents options?

function validation(e, f) {
  var x = document.getElementsByClassName("alert-danger");
  var y = "false";
  var i;
  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });

  $.ajax({
    url: "/membre/modalValidation",
    method: "post",
    data: (e == 1) ? new FormData(document.getElementById("modal-danger4")) :
      new FormData(document.getElementById("modal-danger8")),
    processData: false,
    dataType: 'json',
    async: false,
    contentType: false,
    beforeSend: function() {
      $(document).find('.alert-danger').text('');
    },
    success: function(data) {
      if (data.status == 0) {
        $.each(data.error, function(prefix, val) {
          $('.m' + f + ' .' + prefix + '_error').text(val[0]);
        });
      } else {

      }
      for (i = 0; i < 30; i++) {
        if (x[i].innerHTML) {
          y = "true";
        }
      }
    }
  });
  return y;
}
public function modalValidation(Request $request)
    {
        $newDate = Carbon::now()->subYears(10);
        $validator = Validator::make($request->all(), [
            'firstname' => ['required'],
            'email' => ['required', 'unique:users', 'digits:9'],
            'phone' => ['nullable', 'unique:users', 'email:rfc,dns'],
            'email1' => ['required', 'unique:client__ents,email', 'digits:9'],
            'phone1' => ['nullable', 'unique:client__ents,phone', 'email:rfc,dns'],
            'name' => ['required'],
            'job' => ['required'],
            'CNI_number' => ['required', 'unique:users', 'digits_between:7,20'],
            'CNI_date' => ['required', 'date_format:d/m/Y', 'after:'.$newDate],
            'CNI_place' => ['required'],
            'raison_sociale' => ['required'],
            'forme_juridique' => ['required'],
            'siteWeb' => ['nullable', 'url'],
            'activité' => ['required'],
            'num_contribuable' => ['required', 'unique:client__ents,Numero_contribuable', 'between:13,14'],
            'NC_date' => ['required', 'date_format:d/m/Y', 'after:'.$newDate],
            'siège' => ['required'],
            'email2' => ['required', 'unique:responsable_ents,email', 'digits:9'],
            'phone2' => ['nullable', 'unique:responsable_ents,phone', 'email:rfc,dns'],
            'CNI_number1' => ['required', 'unique:responsable_ents,CNI_number', 'digits_between:7,20'],
            'password' => ['required', 'min:8'],
            'confirm_password' => ['same:password'],
            'checkbox' => ['accepted'],
        ],
        ['confirm_password.same' => 'Ne correspond pas',
        'accepted'=>'Veuillez cocher la case avant de continuer',
        'required'=>'Ce champ est obligatoire',
        'phone.unique'=>'Un utilisateur avec ce mail existe déjà',
        'email.unique'=>'Un utilisateur avec ce numéro existe déjà',
        'phone1.unique'=>'Un utilisateur avec ce mail existe déjà',
        'email1.unique'=>'Un utilisateur avec ce numéro existe déjà',
        'phone2.unique'=>'Un responsable avec ce mail existe déjà',
        'email2.unique'=>'Un responsable avec ce numéro existe déjà',
        'CNI_number.unique'=>'Un utilisateur avec ce numéro de CNI existe déjà',
        'CNI_number1.unique'=>'Un responsable avec ce numéro de CNI existe déjà',
        'num_contribuable.unique'=>'Un utilisateur avec ce numéro de contribuable existe déjà',
        'digits'=>'Veuillez saisir un numéro valide à 9 chiffres',
        'digits_between'=>'Numéro CNI(Passeport) non-conforme',
        'email'=>'Ce mail est invalide. Doit inclure @',
        'date_format'=>'Invalide. Veuillez saisir une date',
        'CNI_date.after'=>'Votre CNI ou Passeport ou Récépissé est expiré',
        'NC_date.after'=>'Votre Numéro de contribuable est expiré',
        'url'=>'Invalide. Veuillez saisir un URL',
        'password.min'=>'Minimum 8 caractères',
        'num_contribuable.between'=>'Numéro de contribuable non-conforme',
    ]);
   
        if ($validator->fails())
        {
            return response()->json(['status'=>0, 'error'=>$validator->errors()->toArray()]);
        }
    }
<div class="modal-body step-2 m2">
  <center>
    <h4>Pièce d'identité</h4>
  </center>
  <div class="form-group">
    <label>Numéro CNI(ou Passeport)<i style="color:#FF0000">*</i> :</label>

    <input type="number" name="CNI_number" class="form-control" placeholder="Entrer le numéro CNI">
    <div class='alert-danger CNI_number_error'></div>
  </div>
  <div class="form-group">
    <label>Date de délivrance<i style="color:#FF0000">*</i> :</label>

    <input id="demo-one-input" name="CNI_date" class="form-control" placeholder="Entrer la date">
    <div class='alert-danger CNI_date_error'></div>
  </div>
  <div class="form-group">
    <label>Lieu de délivrance<i style="color:#FF0000">*</i> :</label>

    <input type="text" name="CNI_place" class="form-control" placeholder="Entrer le lieu">
    <div class='alert-danger CNI_place_error'></div>
  </div>
  <div class="form-group">
    <label>Votre photo :</label>

    <input type='file' accept="image/*" name="photo" class="form-control" placeholder="image portrait">
  </div>
  <div class="form-group">
    <i style="color:#FF0000">*</i> Champs obligatoires
  </div>
</div>


via Chebli Mohamed

Laravel 8: Redirecting Forbidden Users To Their Respective Home Pages

Good Day

I'm new to laravel, and I'm building a website that has multiple users (Student, Supervisor, HOD). I am making use of the laratrust package to manage my users. If a student tries to access a url belonging to a supervisor, for example, laratrust throws an exception that says "USER DOES NOT HAVE ANY OF THE NECESSARY ACCESS RIGHTS". I would like to redirect the student back to their home page instead of this exception.

Here are my routes:

web.php

// Routes For Students
Route::group([
    'name' => 'student.',
    'prefix' => 'student',
    'namespace' => 'App\Http\Controllers',
    'middleware' => ['auth', 'role:student']
], function () {
    Route::get('home', 'StudentController@index')->name('student-home');
    Route::get('proposal', 'StudentController@proposal')->name('student-proposal');
    Route::get('thesis', 'StudentController@thesis')->name('student-thesis');
});

// Routes For Supervisors
Route::group([
    'name' => 'supervisor.',
    'prefix' => 'supervisor',
    'namespace' => 'App\Http\Controllers',
    'middleware' => ['auth', 'role:supervisor']
], function () {
    Route::get('home', 'supervisorController@index')->name('supervisor-home');
    Route::get('proposal', 'supervisorController@proposal')->name('supervisor-proposal');
    Route::get('thesis', 'supervisorController@thesis')->name('supervisor-thesis');
});

// Routes For HOD
Route::group([
    'name' => 'hod.',
    'prefix' => 'hod',
    'namespace' => 'App\Http\Controllers',
    'middleware' => ['auth', 'role:hod']
], function () {
    Route::get('home', 'hodController@index')->name('hod-home');
    Route::get('proposal', 'hodController@proposal')->name('hod-proposal');
    Route::get('thesis', 'hodController@thesis')->name('hod-thesis');
});

I have researched that in order to do this, I need to edit this specific part of the laratrust.php file:

    'middleware' => [

        'register' => true,

        'handling' => 'abort', // This needs to change to redirect

        'handlers' => [
            /**
             * Aborts the execution with a 403 code and allows you to provide the response text
             */
            'abort' => [
                'code' => 403,
                'message' => 'User does not have any of the necessary access rights.'
            ],

            // Redirect User To Their Respective Home Based On Their Role.
            'redirect' => [
                'url' => '/home',
                'message' => [
                    'key' => 'error',
                    'content' => ''
                ]
            ]
        ]
    ],

The home url is different based on the user type, so I want to know how I can check determine the type of user, then based on that assign their respective home url. Please let me know if you require more code or better explanation.



via Chebli Mohamed