Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel class access in Vue.js

I have the following class where I defined my Minimum/Maximum length values:

class MinMaxValuesUser {
    const Min_UserName = 6;
    const Max_UserName = 30;
}

Below is the rule in request class where the min max values are used instead of hardcoding it.

public function messages() {
    return [

        "Min_UserName.min" =>  trans("Profile.Min_UserName"),
        "Max_UserName.max" =>  trans("Profile.Max_UserName")
    ];
}

public function rules() {

    return [
        "UserName" =>  "min:" . MinMaxValuesUser::Min_UserName 
                          . "|max:" . MinMaxValuesUser::Max_UserName
    ];
}

and below is the JQuery Validate code where I used the same server-side class.

$('form#frmProfile').validate({
    rules: {
        UserName: {
            minlength: {!! \App\MinMaxValues\MinMaxValuesUser::Min_UserName !!},
            maxlength: {!! \App\MinMaxValues\MinMaxValuesUser::Max_UserName !!}
        }
    }
});

Issue

As I am writing a lot of code, so I have started to use Vue.js which is already embedded in Laravel. Everything works great here

but as we know vue.js is a front-end framework and loads in client side so will not be able to use the above server-side classes to keep the min max numbers centralized.

Kindly suggest how to get rid of this issue.

like image 378
Pankaj Avatar asked Sep 18 '18 12:09

Pankaj


1 Answers

put your user configurations in a /config/user.php file like this

<?php

return [
  'Min_UserName' => 4,
  'Max_UserName' => 10
];

You can now access it anywhere in your php like this

config('user.Min_userName'); // specific value
config('user'); // array of both values

And you can place it into your view files like this:

@json(config('user'))

If your view component is defined in a blade file you can put this in your data definition:

'user_requirements': @json(config('user'))

If your vue component is buried down further in a js file then you'll want to define a js variable in your blade template (probably your layout) like this

let MyUserReqs = @json('user');

And then you can define it in your vue component using the js variable MyUserReqs.

like image 75
wheelmaker Avatar answered Sep 28 '22 06:09

wheelmaker