Luka

Experience

3,070

0 Best Reply Awards

  • Member Since 2 Years Ago
  • 17 Lessons Completed
  • 0 Favorites

9th August, 2018

Luka left a reply on On Update, Check If Column Changed Before Save() • 1 week ago

@newbie360 -- no luck

8th August, 2018

Luka left a reply on On Update, Check If Column Changed Before Save() • 1 week ago

@ Snapey I tried it but it always shows up as different, even if I have not touched the content.

For example: That is what is being send

 <p><img class="img-fluid" src="/storage/uploads/posts/5b6b68ce795cb/15337658380.png">test</p>

And that is what is in the database, but when I compare it shows that it is different.

test

@jlrdw the reason I don't just want to update everything is that I read out the posted body and check for any images inside it. I then create a filename and a foldername and upload the files to the folder I create dynamically. The first image name in the post gets then added to the db to be used as the default image. If nothing changed on the Post Body, then I could really save this step.

Luka started a new conversation On Update, Check If Column Changed Before Save() • 1 week ago

I have an update form for a Post. I use a Wysiwyg Editor for the Post Body where I can also add images. I was now wondering how I would handle the Update, since I save the tag in the Post Body and upload my images to a folder.

I thought about the option to delete all the images and pull them in again, no matter if the Post Body changed or not or do that only, if something in the Post Body changed. I thought the second option would be better so I looked around if I can actually compare if the field has changed. I came across isDirty() so I tried below, but even if I dont touch it and only change the title, I run into it. If I var_dump it I get a true every time. I must misunderstand the use of it, is there a way to check it or should I just delete it all or is there a better way?

  $post = Post::findOrFail($id);
  $post->body = $request->input('body');
  if($post->isDirty('body')){
    // body has changed

3rd August, 2018

Luka started a new conversation Quill Wysiwyg,Vuejs And Quill-image-resize-module • 2 weeks ago

Hi there,

I wanted to see if somebody is using the Quill Wysiwyg Editor. I use this in a Vue Component. My package.json looks like this:

 "dependencies": {
    "codemirror": "^5.39.2",
    "flexslider": "^2.7.1",
    "node-sass": "^4.9.2",
    "quill": "^1.3.6",
    "vue": "^2.5.16",
    "vue-quill-editor": "^3.0.6",
    "quill-image-resize-module": "^3.0.0",
    "vue-router": "^3.0.1"
}

https://github.com/surmon-china/vue-quill-editor

I then wanted to have a Image Resize option and found below:

https://github.com/kensnyder/quill-image-resize-module

So in my component I have done the following:

import Quill from 'quill'
window.Quill = require('quill');
console.log(Quill);
import { quillEditor } from 'vue-quill-editor' 
import { ImageResize } from 'quill-image-resize-module';
Quill.register('modules/imageResize', ImageResize)

export default{ components: { quillEditor },

    data () { 
            return { 
            name: 'app',
          
            editorOption: {  
                    modules: {
                        toolbar: [
                          ['bold', 'italic', 'underline'],
                          ['blockquote', 'code-block'],
                          [{ 'header': 1 }, { 'header': 2 },{ 'header': 3 }],
                          [{ 'list': 'ordered' }, { 'list': 'bullet' }],

                          [{ 'indent': '-1' }, { 'indent': '+1' }],
                          [{ 'direction': 'rtl' }],
                          [{ 'size': ['small', false, 'large', 'huge'] }],
                          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

                          [{ 'color': [] }, { 'background': [] }],
                          [{ 'align': [] }],
                          ['clean'],
                          ['link', 'image']
                        ],
                        /*
                       imageResize: {
                            displayStyles: {
                              backgroundColor: 'black',
                              border: 'none',
                              color: 'white'
                            },
                            modules: [ 'Resize', 'DisplaySize', 'Toolbar' ]
                                      }   
                                      */
            }},

But I keep getting: window.Quill is undefined I looked at the solutions on Github, but I can not figure out what I need to do in Laravel. Is somebody using it and knows how to get it to run in Laravel?

Luka left a reply on How Can I Use Replace In Query? • 2 weeks ago

:-) Ahhh. Fantastic. Thank you so much !! The change you suggested works.

Luka started a new conversation How Can I Use Replace In Query? • 2 weeks ago

I try to use Replace in my Query because I have categories in the Database, which might have a - inside them and my URL got - so to make sure I can compare, they both need to be the same. In MySQL it would look like this:

select * from posts inner join categories on posts.category_id = categories.id where REPLACE(category,' ','-') = 'Bits-Bobs and others'

So I tried:

$posts = Post::where('posts.public',1) ->join('categories', 'posts.category_id', '=', 'categories.id') ->where(REPLACE(category,' ','-'),$cat) ->orderBy('posts.id', 'desc')->paginate(5);

but I get a Call to undefined function App\Http\Controllers\REPLACE() How I can achieve to have a Replace on the column of the Database?

1st August, 2018

Luka left a reply on Laravel 5.6, Bootstrap 4 + Template, JQuery And Vue • 2 weeks ago

@consil, no, I didn't. My project is not complete yet, but I copied the node_modules to the webserver. I was not happy with it, but was just not sure how to work it out otherwise. I am just reading the reply from skoobi, so I will get back to it and see if I can make it work on the server without the node_modules. But yes you are absolutely right, so much involved and rather complicated to understand and in the end, I am just happy when I get it somehow to work.

@skoobi Thank you for your reply. I will try to get back into it and see if I get it to work as you said.

13th June, 2018

Luka left a reply on How To Set A Checkbox As Set On Edit Form • 2 months ago

I finally managed to have the checkboxes checked on my Edit Form. I had to remove v-model from the checkbox for it to work:

Unfortunately I am now not sure how I get the value when I save the changes.

<input type="checkbox" v-model="user.roles"  v-bind:value="availableRole.id" :checked="isChecked(index,index2)" > 

<input type="checkbox" v-bind:value="availableRole.id" :checked="isChecked(index,index2)" >

 methods: {
            isChecked(index,index2) {
                for (var i=0; i<this.users[index2].roles.length; i++){
                   
                    if (this.users[index2].roles[i].id == this.availableRoles[index].id){
                         return true;
                    }
                }
            },

I have the following method:

 pushFields: function()
    {      
                let uri = '/memberarea/user/update';
             
                var input = this.users;
                    axios.post(uri, input)
                        .then((response) => {
                        })
                        .catch(function () {
                        });
            },

But the roles[] in my User Object is empty. How can I now access my Role Array and assign it to the correct User Object?

Luka left a reply on How To Set A Checkbox As Set On Edit Form • 2 months ago

I appreciate that this would be easier, but it is now set up this way and I have to find a way to get it to work. I think I am actually quite close, the only issue is how to get a checkbox checked. index is for the roles which I read from the db, index2 will be used for the User, so when I got a second User to read out at the same time. Right now I use users[0], but it will be users[index2]. My issue now is that the checkbox is not checked, but my console log shows the correct Role Ids for that User. If return true is wrong to make it checked, what do I need to use?

  isChecked(index,index2) {
                 for (var i=0; i<this.users[0].roles.length; i++){
                    console.log(this.users[0].roles[i].id);
                     if (this.users[0].roles[i].id == this.availableRoles[index].id)
                         return true;
                 }
            },

12th June, 2018

Luka left a reply on How To Set A Checkbox As Set On Edit Form • 2 months ago

I store the ID of the roles in the db the User got so this will not work in the same way, but Thank you. I have used jQuery before, but I now want to learn Vue.js, but I am stuck with this issue.

Luka left a reply on How To Set A Checkbox As Set On Edit Form • 2 months ago

Thank you. I have seen the youtube video before I think this is actually with what I started with, but it does not answer how I would assign Checkboxes to be set on an Edit Form. Stackoverflow says "To set the value of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. " So I guess that is similar to what I was told in the other forum, but I still do not get it to work so I must do something wrong somewhere. Ca you see my mistake?

Luka left a reply on How To Set A Checkbox As Set On Edit Form • 2 months ago

.... and you can believe me that I have done a lot of reading, but have still not found a solution. Maybe it is covered somewhere and I either overread it or did not understand the solution proper, since I am still a total beginner to Vue.js, so if you could pount me in the right direction then I would really appreciate it. Thank you very much in advance.

Luka left a reply on How To Set A Checkbox As Set On Edit Form • 2 months ago

I'm still trying to fix this issue. In a different forum I was advised that I should bind checked via a method or computed property that checks if the availableRole matches the item in user.roles at the same index, but I just do not get it to work. No checkbox gets checked. So I have 2 issues here, I might have up to 2 Users returned so I would guess I need index2 for the loop through the User, that should be ok and I could have multiple Roles for each User, but most important right now is to get any Checkbox pre-checked. So in my below example, if I print out this.users[0].roles[0].id then I get "2"

Any advice from anyone?

 <ul>
 <li v-for="(availableRole, index) in availableRoles">
   <input type="checkbox" v-model="user.roles" :value="availableRole.id" :id="availableRole.id" :checked="isChecked(index)">
   <label :for="availableRole.id">{{ availableRole.name }}</label>
 </li>
</ul>

    
methods: {
   isChecked(index) {
      return this.availableRoles[index].id === this.user.roles[index].id
  }
}

As I said, my User Object looks like the following:

|JSON||

|---|---| |0|{…}| |id|10| |firstname|Joe| |lastname|Bloggs| |username|joeb| |email|[email protected]| |no|111| |parent_no|null| |roles|[…]| |0|{…}| |id|2| |name|User Admin| |pivot|{…}| |model_id|10| |role_id|2|

  |1|{…}|
    |id|3|
    |name|News Admin|
    |pivot|{…}|
    |model_id|10|
    |role_id|3|

|1|{…}|

22nd May, 2018

Luka started a new conversation How To Set A Checkbox As Set On Edit Form • 2 months ago

I have got a Edit Form and use Vue.js for the first time. I have now got a checkbox Array and need to check the checkboxes which were already selected previously, but I can not get it to work. How can I achieve this and what do I need to add to my below Sourcecode?

My JSON Object I return from the Controller looks like this:

firstname: Joe
lastname: Bloggs
username: joe.bloggs
roles: 
    0: {…}
       id: 1
       name: Super-Admin
   1: {…}
       id: 5
       name: News Editor

I create the Checkboxes like this:

  <li v-for="role in roles">
            <input type="checkbox" v-model="user.checkedRoles" :value="role.id" id="role" >
            {{role.name}}
  </li>


 export default{
      data () { 
            return { 
     "users": [{     
                    firstname: '',
                    lastname: '',
                    password:'',
                    username:'',
                    email:'',
               
                    checkedRoles:[],
                }],  
    
     roles: [],     

 methods: {
   getVueItems: function() {
      axios.get('/memberarea/user/details/'+this.$route.params.id).then(response => {
                        this.users = response.data;
                        console.log(response.data[0].roles[0].id);
       });
  }  

29th April, 2018

Luka left a reply on Use Spatie Permission To Protect API Routes Cause A User Not Logged In • 3 months ago

Thank you. I have not thought about that option. Is that because they could manipulate a de-activated Checkbox otherwise?

Luka left a reply on Use Spatie Permission To Protect API Routes Cause A User Not Logged In • 3 months ago

Thank you for the advice. I have now moved it into the Controller. I just have one last question, I was thinking to maybe still show the roles, but deactivate the checkboxes, if you are not a Super Admin. I thought to return a Status from the Controller so something like:

 $roles = Role::get();
 if(auth()->user()->hasRole('Super-Admin'))
 {
     $status = true;
  } else{
     $status = false;
  }

   $data = array(
                    'activated' => $status,
                    'roles' => $roles);
  return response()->json($data); 

So I would return the status to the Vue Component and depending if it is true, the Checkboxes can be set or if false the Checkboxes would be de-activated and and just the Checkbox "Member" would be checked by default. Could that be manipulated through the Front-end somehow or is it secure enough? I would still have a check on the Back-end when saving, but still I do not want to give the option to manipulate it on the Front-end.

28th April, 2018

Luka left a reply on Use Spatie Permission To Protect API Routes Cause A User Not Logged In • 3 months ago

Thank you. I have checked the RouteServiceProvider, but the only difference I can see is that mapApiRoutes() got Route::prefix('api') in front, do you mean that?

I have now followed your advice and moved the route into web routes. Still so much to learn...

Luka started a new conversation Use Spatie Permission To Protect API Routes Cause A User Not Logged In • 3 months ago

I use Spatie Permissions and Roles Package. I have now implemented Vue.js for adding Users. A User Admin can add Users, but only a Super-Admin can assign specific roles to that User otherwise it will just be an ordinary Member. I thought of doing an Ajax Request in my Vue.js to return the roles, if the logged in User is a Super-Admin. I then thought to use an API call for it and have added the below in api.php:

Route::group(
   ['middleware' => ['role:super-admin']],
       function () {
            Route::get('roles', function() {
            return App\Role::get();
 });
}

);

In my Vue component I use:

 mounted: function () {
            
             axios.get('/api/roles')
                         .then((response) => {
                             console.log('test');
                        })
                        .catch(function () {
                        });          
        },

I would have thought that this is enough, but I get a "User is not logged in." even if I am logged in. So my RoleMiddleware somehow throws an Exeption. Any idea what I do wrong?

26th April, 2018

Luka started a new conversation How To Use Blade Variable In My Vue.js Component Template • 3 months ago

I have a User Form to add a new User. A User with the role Super Admin is able to assign a User Role and I use the below for it.

 @hasrole('Super-Admin')

    @foreach ($roles as $role)
        {{ Form::checkbox('roles[]',  $role->id, $user->roles ) }}
        {{ Form::label($role->name, ucfirst($role->name)) }}<br>
    @endforeach

@endhasrole

All that works very well, till I decided to use Vue.js. I re-created the form and created a component where I got my template with the form inside. Of course @hasrole('Super-Admin') is not available anymore, but how would I achieve that? Any hints would be highly appreciated. Of course it needs to be save so that it can not be manipulated via Javascript and then roles assigned from User without the correct role.

11th April, 2018

Luka left a reply on Laravel Validation For Array Causes Problem • 4 months ago

ok, I have found the Problem and a solution. The problem is the '*. so if I use below instead it works. I am just not sure if there would have been a nicer solution then below, but it works.

  for($counter = 0; $counter<$registeredMembers; $counter++){
                 
        if(isset($input[$counter]['id']) && $input[$counter]['id'] != ''){
            $id = $input[$counter]['id'];
           
            $user = User::findOrFail($id); //Get role specified by id
         
            $this->validate($request, [
                $counter.'.firstname'=>'required|max:120',
                $counter.'.lastname'=>'required|max:120',
                $counter.'.email'=>'required|unique:users,email, '.$id,
                $counter.'.username'=>'required|unique:users,username, '.$id,
              
           ]);
           
        }else{
           
            $this->validate($request, [
                $counter.'.firstname'=>'required|max:120',
                $counter.'.lastname'=>'required|max:120',
                $counter.'.email'=>'unique:users,email',
                $counter.'.username'=>'required|unique:users,username',
                $counter.'.password'=>'required|min:5'
            ]);
            
            $user = new User;
        }

Luka left a reply on Laravel Validation For Array Causes Problem • 4 months ago

No, it is the User which gets updated on the Form. I have tried it directly with $id as well, but that was not working. As you can see in my first post, I use the following:

 $id = $input[$counter]['id'];      
 $user = User::findOrFail($id); 

Luka left a reply on Laravel Validation For Array Causes Problem • 4 months ago

Thank you Cronix, that fixed that issue but to be honest I have now got the exact same outcome as I got with my original Sourcecode.

What I did notice, if I hardcode the userId then it does ignore the specific record so if I write f.e

'*.username'=>'required|unique:users,username, 12'

then it works, but if I use the Variable instead it doesn't. I have checked the Variable Value of course and it is in my case 12 so it is fine. How strange is that?

Luka left a reply on Laravel Validation For Array Causes Problem • 4 months ago

Ok I have tried now:

 $this->validate($request, [
                '*.email' => ['required', 'email', Rule::unique('users')->ignore($user->id)],
                '*.username' => ['required','username', Rule::unique('users')->ignore($user->id)],       
]);

but get the Error Message:

Method Illuminate\Validation\Validator::validateUsername does not exist. If I remove '*. and just do it as above then I receive the Validation Error that Email and Username is required, I guess because it does not look for the Array.

Luka started a new conversation Laravel Validation For Array Causes Problem • 4 months ago

I have the following set up. I have a page to add a User. A User can also have a Friend attached to them, so I allow to add that Friend to be added on the same form by clicking on a Button and the second part of the Form shows up. I use Vue, which I am still very new to. I have now got a strange Problem with the Validation on an Update. My Object looks like this:

0 {…} email [email protected] firstname Bob id 12 lastname Smith username bobby 1 {…}

email [email protected] firstname Marie lastname Smith password intdr9143 username bobby

What I am doing here is that my first User already exist in the database and I now wanted to add a Friend to that one. So any change on the first User would be an update record and Validation for Unique should be ignored, if it is the same User Id, the second would now be an Add Record. The Validation for unique works fine, when I just update the first User, but as soon I add another one the "Ignore Unique on its own record" does not work anymore.

As you can see, both picked the same Username and Validation should fail, which it does, but I also get an Error about the Email caused by the first User:

"message":"The given data was invalid.","errors":{
    "0.email":["The 0.email has already been taken."],
    "0.username":["The 0.username has already been taken."],
    "1.username":["The 1.username has already been taken."],
    "0.password":["The 0.password field is required."]
 }


 public function update(Request $request) {
  $input = $request->all();
    $registeredMembers = count($input);
    
    for($counter = 0; $counter<$registeredMembers; $counter++){
                 
        if(isset($input[$counter]['id']) && $input[$counter]['id'] != ''){
            $id = $input[$counter]['id'];
           
            $user = User::findOrFail($id); 
          
            $this->validate($request, [
                '*.firstname'=>'required|max:120',
                '*.lastname'=>'required|max:120',
                '*.email'=>'required|unique:users,email, '.$user->id,
                '*.username'=>'required|unique:users,username,'.$user->id,
                '*.password'=>'required|min:5'
            ]);
           
        }else{
           
            $this->validate($request, [
                '*.firstname'=>'required|max:120',
                '*.lastname'=>'required|max:120',
                '*.email'=>'unique:users,email',
                '*.username'=>'required|unique:users,username',
                '*.password'=>'required|min:5'
            ]);
            
            $user = new User;
        }

Why is this not working? Any idea?

29th March, 2018

Luka started a new conversation How To Implement Input Field From A Component In An Excisting Form • 4 months ago

I am creating a part dynamic User Form with a Password Generator. I still struggle with Vue, but found a Password Generator which I now try to implement into my exciting Vue Form. Unfortunately, the value of the Password Field get's not send when I send of the form and I am not quite sure what the issue is. I found 2 scripts in the net and I tried to combine them.

What do I do wrong with this? Why is password not available? I see the input field and I can create a random password, but it is not available when I send off the form.

app.js

// register Component
    Vue.component('vue-password', {
      template: '<div class="input-group"><span class="input-group-addon"><span class="fa fa-lock"></span></span><input :v-model="vmodel" :name="name" :type="type" class="form-control" :placeholder="placeholder" :value="password" /><span class="input-group-btn"><button type="button" class="btn btn-primary" @click="generate()"><span class="fa fa-refresh"></span></button></span></div>',
      props : {
        type: {
          type: String,
          default: 'text'
        },
        vmodel: {
          type: String,
          default: 'apartment.password'
        },
        name: {
          type: String,
          default: 'apartments[][password]'
        },
        size: {
          type: String,
          default: '6'
        },
        characters: {
          type: String,
          default: 'a-z,A-Z,0-9'
        },
        placeholder: {
          type: String,
          default: 'Password'
        },
        auto: [String, Boolean],

      },
      data: function() {
        return {
          password: this.value
        }
      },
      mounted: function() {
        if(this.auto == 'true' || this.auto == 1) {
          this.generate();
        }
      },
      methods: {

        generate: function() {
          let charactersArray = this.characters.split(',');  
          let CharacterSet = '';
          let password = '';

          if( charactersArray.indexOf('a-z') >= 0) {
            CharacterSet += 'abcdefghijklmnopqrstuvwxyz';
          }
          if( charactersArray.indexOf('A-Z') >= 0) {
            CharacterSet += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
          }
          if( charactersArray.indexOf('0-9') >= 0) {
            CharacterSet += '0123456789';
          }
          if( charactersArray.indexOf('#') >= 0) {
            CharacterSet += '![]{}()%&*$#^<>[email protected]|';
          }

          for(let i=0; i < this.size; i++) {
            password += CharacterSet.charAt(Math.floor(Math.random() * CharacterSet.length));
          }
          this.password = password;
        }

      }
    });


const appFrInput = new Vue({
        el: '#vue-wrapper-dyn-input',

      data: {
        apartment: {
          firstname: '',
          password:'',
        },
          hasError: false,
          apartments: []
      },
        mounted: function () {
        /*
         * The "data-apartments" could come from serverside (already saved apartments)
         */

      },
        methods: {
            addNewApartment:function (e) {
                e.preventDefault();
                this.apartments.push(Vue.util.extend({}, this.apartment));
            },
            sendForm:function(){

                let uri = '/memberarea/user/save';
                var input = this.apartment;

                alert (this.apartment.password);

                axios.post(uri, input).then((response) => {
                           console.log("ok");
                        })
                        .catch(function () {
                });
                 this.hasError = true;
            }
        }
    });

mybladeviewfile

<form id="vue-wrapper-dyn-input" @submit.prevent="handleSubmit" action="/user/save" method="post" data-apartments='[{ "price": "23000", "rooms": "12" }, { "price": "42000", "rooms": "32" }]'>
   
    <p class="text-center alert alert-danger" v-if="hasError">Please enter some value!</p>                
    
    <div class="form-group">
        {{ Form::label('firstname', 'First Name') }}
        <input v-model="apartment.firstname" 
               type="string"
               name="apartments[][firstname]" class="form-control" placeholder="First Name"> 
    </div>

    <div class="form-group">
        <label>Generate Password</label>
        <vue-password size="6" auto="true" characters="a-z,A-Z,0-9"></vue-password>
    </div>

    <div v-for="(apartment, index) in apartments">
        <h3>Partner/Friend Details</h3>
        <div class="form-group">
            {{ Form::label('firstname', 'First Name') }}
            {{ Form::text('firstname', '', array('class' => 'form-control')) }}
        </div>
    </div>

    <div id="">
     <button type="submit" class="btn btn-primary"> Add Partner/Friend</button>
    </div> 
    <button type="button" v-on:click="sendForm" class="btn btn-success"> Save User</button>
</form>

Luka left a reply on How To Check Role In __construct() From Controller When Using Spatie/Permission Package • 4 months ago

It is working now, the Problem was the space between role: and Super-Admin. The other Space does not cause a Problem, but thank you very much.

27th March, 2018

Luka left a reply on How To Check Role In __construct() From Controller When Using Spatie/Permission Package • 4 months ago

Ok the last issue was easy. I just had to create a View for Error 403 and now it shows a proper Error Page.

Luka left a reply on How To Check Role In __construct() From Controller When Using Spatie/Permission Package • 4 months ago

I can't believe the Error. The issue was the space after role: SuperAdmin. As soon I remove that it works. The only issue I now got is that I get the Spatie \ Permission \ Exceptions \ UnauthorizedException User does not have the right roles.

shown and not the Page with a proper Error Message for the User saying Access Denied. It comes from the below file, so I have to find out how to change this.

\spatie\laravel-permission\src\Exceptions\UnauthorizedException.php

    public static function forRoles(array $roles): self
    {
        $message = 'User does not have the right roles.';

        if (config('permission.display_permission_in_exception')) {
          $permStr = implode(', ', $roles);
          $message = 'User does not have the right roles. Necessary roles are '.$permStr;
        }

        $exception = new static(403, $message, null, []);
        $exception->requiredRoles = $roles;
   
    return $exception;
}

Luka left a reply on How To Check Role In __construct() From Controller When Using Spatie/Permission Package • 4 months ago

I am not sure I understand your answer 100%. I have got a Role Controller with the below Constructor and that works fine. I get a Access denied, if I am not a Super Admin. The only difference is that in my User Controller I want to give 2 Roles Access, Super-Admin and User Admin with a restriction in my destroy method for the User admin, but that is already working anyway.

class RoleController extends Controller {

    public function __construct() {
        $this->middleware(['auth', 'isSuperAdmin']);//isSuperAdmin middleware lets only users with a //specific permission to access these resources
    }

Luka started a new conversation How To Check Role In __construct() From Controller When Using Spatie/Permission Package • 4 months ago

Hi all,

I am still fighting with my Spatie/Permission in my first Laravel project. I needed a Role/Permission set up and have installed Spatie Permission. I have created different roles and each role got different permissions.

I am now starting with the User Controller. I have got a role called "User Admin" and I got a role called "Super Admin". Only these 2 roles should have access to the User Controller. The Super Admin can access all the Methods in the User Controller, the User Admin can not access the delete Method.

I thought to implement a check in the Constructor of the Controller to check if the logged in User got at least 1 of the specific roles if not it will be an Access denied instead of checking the permission in each Method. But how would I achieve this?

I have created 2 Models Role.php and Permission.php

Role.php

namespace App;
class Role extends \Spatie\Permission\Models\Role 
{

}

UserController.php

use App\User;
use App\Role;
use Auth;

class UserController extends Controller {
   public function __construct() {
     $this->middleware(['role: Super-Admin|User Admin']); 
   }
 }

But I get > Spatie \ Permission \ Exceptions \ UnauthorizedException User does not have the right roles.

What do I do wrong and how can I do the simple check in the constructor? The logged in User got the Role Super-Admin.

26th March, 2018

Luka left a reply on Where To Store Store Global Information ? • 4 months ago

Thank you Cronix. artisan config:clear fixed it. Such a nice and easy solution. Excellent. Thank you very much !

Luka left a reply on Where To Store Store Global Information ? • 4 months ago

Thank you all for the advices.

> Create a config file. All they do is return an array, like all of the other laravel config files. Access in your code like config('positions.Chairman') or just $positions = config('positions'); to get the entire array.

That sounds very easy, but do I not have to register it somewhere because I tried it out, but get no result, so I suppose I have to let Laravel know to process my new conf file, don't I?

Luka started a new conversation Where To Store Store Global Information ? • 4 months ago

I am just creating a Contact Form with a Dropdown to select to which Position this Form should be send. I don't want the Email Address displayed instead Positions which then should be mapped. Question now, I want to create an Array which is simply showing Chairman=> [email protected] Secretary=> [email protected]

I would like this configured somewhere to use it all around the Page. The Mapping will then happen in the Controller, when the Email gets generated. Where would I store this information in Laravel?

13th March, 2018

Luka started a new conversation Create Checkbox Array With Vue.js For A Table Grid • 5 months ago

I am stuck. I have finally created my editable grid with vue.js and there is just 1 problem left. I have a checkbox for "Weekdays" and "Weekends". Unfortunately in my console.log I do not get weekdays or weekends shown instead I get true or false. The other issue is that when I click on 1 checkbox, both get selected. What do I do wrong?

my index.blade.php @{{ user.availability }} Weekdays Weekends

my app.js

  data: {

        users: [
        {
        availability:[]
    }
     
  ],

  saveData: function(user) {    
        console.log(user.availability); 
      
       axios.post('/memberarea/userlist/update/'+user.id, user).then(() => {
               this.editedUser = true;
        });
    },

7th March, 2018

Luka left a reply on How To Create An Editable Table With Vue.js • 5 months ago

Everytime I think I am nearly there I run into a new problem. I have now figured out how to make the input field visible to change the entry, but then I realised that I will face a problem, when I have multiple columns. Right now it is obvious that when I doubleclick on name, postcode also turns into an input field. That makes perfect sense since I check for item.edit and I use the same for both. As you can see, I inject this in my getVueItems method with the default value false. I don't want to make up multiple edit now and inject them, is there any nicer way to achieve this?

  <td>
            <div v-show = "item.edit == false">
                <label @dblclick = "item.edit = true"> @{{item.name}} </label>
            </div>
            <input name="name" 
                               v-show = "item.edit == true" 
                               v-model = "item.name" 
                               v-on:blur= "item.edit=false;" 
                               @keyup.enter = "item.edit=false; update(item.name,$event)">
  </td>
                    
  <td>   
            <div v-show = "item.edit == false">
                <label @dblclick = "item.edit = true"> @{{item.postcode}} </label>
            </div>
            <input name="postcode" 
                               v-show = "item.edit == true" 
                               v-model = "item.postcode" 
                               v-on:blur= "item.edit=false;" 
                               @keyup.enter = "item.edit=false; update(item.postcode,$event)">
  </td>

6th March, 2018

Luka left a reply on How To Create An Editable Table With Vue.js • 5 months ago

Thanks, I can see that your solution would be good if it is a full grid with lots of changes. But mine will be a list of maybe 20-30 rows and maybe 10 columns. On the bottom of the list will be the option to enter a new User to the list and then each row got a delete button so you can remove the User again from that list and then it might be the odd change specially when you discover that you made a mistake while you added the person. The change can only be done when you double-click on the cell so it should not happen my accident as well. I just wonder how to achieve that.

Luka left a reply on How To Create An Editable Table With Vue.js • 5 months ago

Not sure that I understand you right, but I think you suggest to have a "Save" Button at the end? I am not sure about it since people might forget that they have to click this button otherwise their changes are lost. There shouldn't be too many changes anyway, just maybe the Phone Number or when the Admin sees he made a mistake... so if it updates straight after clicking enter would be fine.

Luka left a reply on How To Create An Editable Table With Vue.js • 5 months ago

Thank you to both of you. I have somehow worked out below. This now turns my td cell into an input field, but how would I now identify which field I clicked on? I need to know the recordId I have to update and which field because in the end I will have multiple cells which I might update and I suppose I should update my db as soon I click enter so I need the recordID and which column to update or is there a better way? should I give the a class which contains the id and the name of the column?

        <tr v-for="item in items">
                    <td id="item.id">@{{ item.id }}</td>
                    <td>
                        <div v-show = "item.edit == false">
                            <label @dblclick = "item.edit = true"> @{{item.name}} </label>
                        </div>
                        <input v-show = "item.edit == true" 
                               v-model = "item.name" 
                               v-on:blur= "item.edit=false;" 
                               @keyup.enter = "item.edit=false; update(item.name)">
                    </td>
                    <td>@{{ item.postcode }}</td>
                    <td @click.prevent="deleteItem(item)" class="btn btn-danger">
                        <span class="glyphicon glyphicon-trash"></span>
                    </td>   
            </tr>


   methods : {
        editTodo: function(todo) {
            this.editedTodo = todo;
        },
  
        getVueItems: function(){
           axios.get('/vueitems').then(response => {

        $.each(response.data, function(i, v) {
             response.data[i].edit =  false;
        });
        this.items = response.data;
        
        });
      },
        update: function(item){
         var $row = $(item).prev('td');  
         console.log($row.id);
      },

2nd March, 2018

Luka left a reply on Example.vue Problem • 5 months ago

I have just started with Vue.js myself, so I am not sure that I understand you right and that my answer is correct, but don't you need the following in your view to be able to show the component?

 <div id="app">
    <example></example>
</div>

Luka started a new conversation How To Create An Editable Table With Vue.js • 5 months ago

I have recently started to learn Laravel and try to now get into Vue.js at the same time. My project got a page,which displays a list of Users which get read out from the database. I now thought that it would be nice to be able to add a new User directly on that page so I looked around how I could achieve this with Vue and found a nice script. I now decided that it would be nice to have the option to "Edit" as well, so I tried to look around how to achieve this and got totally lost. I thought that a click on a column should maybe add a input field with the cell value in it, but how is this possible to achieve? How could I let my clickList function know which table cell I clicked and how would I add the input field back? And would I not need to send a form tag back as well to be able to save it ? Should I add a Form tag to around the and add a submit button next to the "trash" so that you have to click on that after you are finish to save the changes? Or is there a better solution? Does anyone know of a Tutorial I should read?

my view index.blade.php

 <div id="vue-wrapper">
<div class="content">
    <p class="text-center alert alert-danger" v-if="hasError">Please enter some value!</p>
    {{ csrf_field() }}
    <p class="text-center alert alert-success" v-if="hasDeleted">Deleted Successfully!</p>
    <div class="table table-borderless" id="table">
        <table class="table table-borderless" id="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Postcode</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tr v-for="item in items">
                    <td v-on:click="clickList(item)">@{{ item.id }}</td>
                    <td v-on:click="clickList(item)">@{{ item.name }}</td>
                    <td>@{{ item.postcode }}</td>
                    <td @click.prevent="deleteItem(item)" class="btn btn-danger">
                        <span class="glyphicon glyphicon-trash"></span></td>
            </tr>
            <tr> 
            <div class="form-group row">
                <th></th>
                <th><input type="text" class="form-control" id="name" name="name" required v-model="newItem.name" placeholder=" Enter some name"></th>
                <th><input type="text" class="form-control" id="name" name="postcode" required v-model="newItem.postcode" placeholder=" Postcode"></th>
                <th><button class="btn btn-primary" @click.prevent="createItem()" id="name" name="name">
                <span class="glyphicon glyphicon-plus"></span> ADD </button>
                </th>
            </div>          
            </tr>
        </table>
    </div>
</div>
</div> 

resources\assets\js\app.js

const app = new Vue({
el: '#vue-wrapper',

data: { items: [], hasError: false, hasDeleted: false, but: '', newItem : {'name':''} }, mounted : function(){ this.getVueItems(); }, methods : { getVueItems: function(){ axios.get('/vueitems').then(response => { this.items = response.data; }); }, createItem: function(){ this.hasDeleted = false; var input = this.newItem; if(input['name'] == ''){ this.hasError = true; this.hasDeleted = false; } else{ this.hasError = false; axios.post('/vueitems',input) .then(response => { this.newItem = {'name':''}; this.getVueItems(); }); this.hasError = false; } },

   deleteItem: function(item){
    axios.post('/vueitems/'+item.id).then((response) => {
        this.getVueItems();
        this.hasError = false,
        this.hasDeleted = true
    },
    
    clickList: function (item) {
            console.log("clickList fired with " + $row +item.id);
    },
   
    editItem: function(){
          
    },
    
    saveItem: function(item){
    
    },
);
  },

} });

22nd February, 2018

Luka left a reply on Problem To Create Dependable Dropwdown With Ajax And Vue.js • 5 months ago

Sorry Bobby, done it now. I did not see that option.

21st February, 2018

Luka left a reply on Problem To Create Dependable Dropwdown With Ajax And Vue.js • 5 months ago

@bobbybouwmann Thank You !!! That works indeed. I tried it with int and that was wrong. You were right, the URL showed false and true before, it now works fine. Thank you so much for your help !!

Luka left a reply on Problem To Create Dependable Dropwdown With Ajax And Vue.js • 6 months ago

Ok, I see what you mean. I have tried different ways, but I can not find a way to cast my boolean into an integer. This is my vue component: What do I need to change?

  <form action="/tasks" method="post">
       Public
        <input type="checkbox" name="publicval" v-model="publicval" @change="loadCategories" >
        <br>
      Member
        <input type="checkbox" name="memberval" v-model="memberval" @change="loadCategories" >           
        <select  name="category_id">
            <option value="">Select Category</option>
            <option v-for="category in categories" :value="category.id">{{ category.category }}</option>
        </select>
        <button type="submit" class="btn btn-primary">Submit</button>
</form>

  export default {
    data(){
        return {
            categories:[],
            publicval: 0,
            memberval: 0,
        }
    },
    mounted() {       
       // this.loadCategories()
    },
    methods:{
        loadCategories(){
           let url = '/categories/'+this.publicval+'/'+this.memberval
           this.dynamicDropdown(url,'categories')
        },
        dynamicDropdown(url,data){
            axios.get(url)
                 .then(response=>this[data]=response.data)
                 .catch(error=>console.log(error))
        }
    }
}

19th February, 2018

Luka left a reply on Problem To Create Dependable Dropwdown With Ajax And Vue.js • 6 months ago

I am not sure I understand what you mean. The

  $publicval = true;
  $memberval = false;

is just an example to test if that works. Where do I have to do the change?

Luka left a reply on Problem To Create Dependable Dropwdown With Ajax And Vue.js • 6 months ago

Is this a real thing? this[data]?? To be honest? No idea. I found it on internet. The URL works.

If I do the below as an example, then I get the right values from my db. What does not seem to work is sending over the state of the 2 checkboxes. In my db I use 0 and 1. So is this an error in my vue component?

public function categories($publicval,$memberval)

{ $publicval = true; $memberval = false; return Categories::where('public','=', $publicval)->where('memberarea','=', $memberval)->get(); }

Luka started a new conversation Problem To Create Dependable Dropwdown With Ajax And Vue.js • 6 months ago

I am trying to program a dependable dropdown with Vue, Ajax and Laravel. The dropdown is depending on 2 checkboxes. I have created a Vue component:

<template>
<div class="container">
   
    <div class="row">
    <form action="/tasks" method="post">
    Public
        <input type="checkbox" name="publicval" value="1" v-model="publicval" @change="loadCategories" >
        <br>
      Member
        <input type="checkbox" name="memberval" value="1" v-model="memberval" @change="loadCategories" >           
        <select  name="category_id">
            <option value="">Select Category</option>
            <option v-for="category in categories" :value="category.id">{{ category.category }}</option>
        </select>
        <button type="submit" class="btn btn-primary">Submit</button>
</form>
    </div>

export default { data(){ return { categories:[], publicval: '0', memberval: '0' } }, mounted() {
       // this.loadCategories()
    },
    methods:{
        loadCategories(){
           let url = '/categories/'+this.publicval+'/'+this.memberval
           this.dynamicDropdown(url,'categories')
        },
        dynamicDropdown(url,data){
            axios.get(url)
                 .then(response=>this[data]=response.data)
                 .catch(error=>console.log(error))
        }
    }
}

I have the following route:

Route::get('categories/{publicval}/{memberval}', '[email protected]');

In my Controller I have the following method:

public function categories($publicval,$memberval)
{
    return Categories::where('public','=', $publicval)->where('memberarea','=', $memberval)->get();
}

Unfortunately it does not work. When I check the Headers the Request URL show /categories/true/false when I click on the first checkbox, but the result is wrong. What do I do wrong? Is it the Route or Vue.js? This is my first approach with Vue, so it is very likely that I do it wrong....

14th February, 2018

Luka left a reply on Laravel 5.6, Bootstrap 4 + Template, JQuery And Vue • 6 months ago

Now I am lost. I assumed that with using:

npm install package name
npm run dev 

The packages are then available to use in my project so I wont have to link to them via CDN. What is the node_modules folder with all the libraries then for?

Luka left a reply on Laravel 5.6, Bootstrap 4 + Template, JQuery And Vue • 6 months ago

Ok, that is actually what I thought and it means I will have to upload the node_modules folder to the webserver as well in the end. So just to confirm, any files in node_modules I can just leave in there and do not need to copy them into any other folder? And I do not need to use:

  <script src="https://cdnjs.cloudflare.com/ajax/libs/flexslider/2.7.0/jquery.flexslider.min.js"></script>

or

in my blade layout file? I still get the "popper is not defined" error and I think jQuery is still not working, so right now flexslider is not working so I can not test if I need to add that link or now. Do I have to do anything else after the below 2 to be able to use a package?

npm install package name
npm run dev

13th February, 2018

Luka left a reply on Laravel 5.6, Bootstrap 4 + Template, JQuery And Vue • 6 months ago

@Heyaj05, Thank you so much for your help. I just don't understand what the nodes_modules folder does. For example I have done a npm install flexslider. After that I had a folder called Flexslider in my nodes_modules folder, but what do I now actually do? Do I copy the folder from there into my public/js folder or is it supposed to do that automatically when I run npm run dev? Is there anything I have to change in rescources/assets/js/app.js to call up flexslider or is it just in the blade template?

Luka left a reply on Laravel 5.6, Bootstrap 4 + Template, JQuery And Vue • 6 months ago

As described in my first post, I created a new Laravel Project. I then went into that directory and run npm install. This created me a folder called node_modules with all the packages.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.