Luka

Luka

Member Since 2 Years Ago

Experience Points 3,450
Experience
Level
Lessons Completed 17
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

10 Nov
3 days ago

Luka started a new conversation Laravel 5.6 GetClientMimeType() Is Not Working For MS Office

Hi there, I use Laravel 5.6 and PHP 7.2. I have created a document upload and want to be able to identify what type of document was uploaded. It could be old MS Office documents like .doc or docs. could be Excel or Powerpoint. I used

$docData->mime_type = $document->getClientMimeType();
$docData->document_type = $document->guessClientExtension();

but in my Database I get "application/octet-stream" as the MimeType and "bin" as the document type. A

 dd($_FILES["file"]["type"]); 

gives me the same. So I would assume it's a PHP issue, since it is not even able to recognise it via plain PHP.

The below comes with the right result

dd(\File::mimeType($_FILES['file']['tmp_name']));

"application/vnd.openxmlformats-officedocument.wordprocessingml.document"

Question now, is it possible to get PHP to recognise the correct mimeType for Office documents or what do I do wrong and second how do I achieve it since I also need the file ending. I also need it for validation which I have not even touched yet.

05 Sep
2 months ago

Luka left a reply on Update A One-to-many Relation With Possibly Additional Data Attached

Thank you. Your solution works, but it still leaves my question if this is a good approach, since it now always deletes even if it could just update. Is there no other option?

Luka left a reply on Update A One-to-many Relation With Possibly Additional Data Attached

Yes.

 Schema::create('event_dates', function (Blueprint $table) {
        
        $table->increments('id');
        $table->integer('event_id')->unsigned();
        $table->date('event_date');
        $table->string('event_starttime');
        $table->string('event_endtime');
        $table->timestamps();
    });
    
    Schema::table('event_dates', function($table) {
         $table->foreign('event_id')->references('id')->on('events');

Luka left a reply on Update A One-to-many Relation With Possibly Additional Data Attached

Is that the correct approach or is there a better way?

Luka left a reply on Update A One-to-many Relation With Possibly Additional Data Attached

As far as I understand, only ManytoMany got the sync() method and yes event dates is an array.

Luka started a new conversation Update A One-to-many Relation With Possibly Additional Data Attached

I'm currently trying to update a one-to-many relation in Eloquent. I have got an Event Model and the Event can have Many Event Dates.

class Event extends Model
{

protected $fillable = ['event_name', 'event_description'];

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

}

  class EventDates extends Model
  {

  protected $fillable = [ 'event_date','event_starttime','event_endtime','event_id'];

  protected $dates = ['event_date'];

  public function event()
  {
     return $this->belongsTo('App\Event', 'event_id');
  }
 }

  class Image extends Model
 {
   public $fillable = ['image_name'];

   public function events()
   {
      return $this->hasOne('App\Event','event_image_id');
   }
 }

The Problem is now the update.

I have done the following in my Controller:

  public function update(Request $request, $id)
  {
   
    $event = Event::findOrFail($id);
    $input = $request->all();
    $event->update($input);
    
    $rows =  $request->input('event_date'); 
    
    for($i=0; $i <count($rows);$i++)
    {
        $eventDates = [
          //  'event_id' => $event->id,
            'event_date' =>   \Carbon\Carbon::createFromFormat('d-m-Y', $request->event_date[$i]),
            'event_starttime' => $request->event_starttime[$i],
            'event_endtime' => $request->event_endtime[$i]   
        ];
        
         $event->eventdates()->update($eventDates);
    }

This works fine, when you have a date in the database and you update that. But, my form offers the option to add additional date fields dynamic. It could be that you entered just 1 date originally, but now you realise the event goes over 2 days so you have to add a date, which means you have to insert instead of update. It might also happen that you have to update the first date + insert an additional date.

I found updateOrCreate and tried that but it seems to Create 2 new records, when I update the existing record and add 1 date. I obviously got a logical error here, but how to achieve that?

04 Sep
2 months ago

Luka started a new conversation How To Use Form Model Binding With Related Data And Image On Edit Form

I am still at my Upcoming Event Function. i have now got an issue with the Edit Form. I use Form Model Binding, hope this is how it is called. It works well on my Events Table, pulls in the Data and displays it in my Form, but I do not get my related data. i thought to add the with('eventdates') but the dates are not added. I allow to add multiple Dates with a dynamic created input field so I can not even say if 1 or multiple fields should be created. The image also needs to be displayed of course. Is this actually possible to do with Form Model Binding or rather not?

EventController:

public function edit($id) { $event = Event::findOrFail($id); return view('memberarea.events.edit', compact('event')); }

class Event extends Model {

protected $fillable = ['event_name', 'event_description'];

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

}

class EventDates extends Model {

protected $fillable = [ 'event_date','event_starttime','event_endtime','event_id'];

protected $dates = ['event_date'];

public function event()
{
     return $this->belongsTo('App\Event', 'event_id');
}

}

class Image extends Model { public $fillable = ['image_name'];

public function events()
{
    return $this->hasOne('App\Event','event_image_id');
}

}

My edit form looks like this:

{!! Form::model($event, ['method' => 'PATCH', 'action' => ['[email protected]',$event->id]]) !!}

        <div class="form-group row">
            {{ Form::label('eventname', 'Event Name:',array('class'=>'required col-sm-2 col-form-label')) }}    
            <div class="col-sm-4">
                {{ Form::text('event_name', null, array('class' => 'form-control')) }}
                @if ($errors->has('event_name'))
                    <span class="text-danger">{{ $errors->first('event_name') }}</span>
                @endif
            </div>
        </div>
{{ Form::label('Date/Time:', '',array('class'=>'required col-sm-2 col-form-label')) }}
            <div class="col-sm-2">        
            <div class="input-group mb-4">

            <div class="input-group">
                {{ Form::text('event_date[]', null, array('id' => '', 'class' => 'eventDate form-control','placeholder' => 'Date')) }}
                  <div class="input-group-append">
                    <span class="input-group-text"><i class="fa fa-calendar"   onclick="$('#eventDate').focus();"></i></span>
                  </div>
                @if ($errors->has('event_date'))
                    <span class="text-danger">{{ $errors->first('event_date') }}</span>
                @endif
            </div> 
            </div> 
            </div>

Please upload a valid image file. Size of image should not be more than 2MB.

        {{ Form::submit('Save Details', array('class' => 'btn btn-success btn-lg btn-block')) }}
        {{ Form::close() }}
29 Aug
2 months ago

Luka started a new conversation Looking For Image Upload Package

Hi there,

I am just creating my first Laravel Project. My next task is to create an Events Section. When creating an event, I also allow to upload an Image, so I have now created an image table in there I store the filesize, the original name, the folder where it will be stored, the new name, the thumbnail filename and the filetype. I then realised that I will actually use the same table when I program the Gallery which will come next. So all images which are uploaded through the Gallery will be stored in the same table so I will add a column image_location which will either say event or gallery. The Gallery Image will be part of an Album, but the Album names should be stored in a different table and then a 1:n so 1 Album got many Photos. Images uploaded through the Gallery should also have a Thumbnail created and Images should be resized in General obviously with the correct ratio kept. I think I also want to be able to add a possible small text to the image. As a last thing I want to program a Document Upload which could be PDF files for example or a word document. I had a look at any available Packages and found Spatie’s Media Library. I saw the migration file and it will obviously create me a database table called media with fields like model_type, model_id which I find rather confusing in comparison to what I wanted to save so I am not sure if that package is actually of any use for me.

Does anyone know of any package I should maybe use for what I am trying to achieve? The documents I might upload should go into a documents db table I thought, I suppose in Spatie everything goes into the media table which somehow would make sense aswell.

I really not sure what is advisable to do. As I said Events, single Image, Gallery multiple Images with additional text added to each Photo and thumbnails created. Is there any package I should use?

Hope to get some tipps. Thanks all in advance.

23 Aug
2 months ago

Luka left a reply on Save HasMany Relationship With Data Field In Second Table

Ok, you are right, I have to format the date before I can hand it to the Related Model. I was actually hoping it would be done in the Model somehow, but could not figure it out. If anyone else got a suggestion please let me know. Now I have to find out how to handle multiple dates.

    $event = Event::create($request->all());

    $formatedDay = \Carbon\Carbon::parse($request->event_date);
    $event->eventdates()->create(
            ['event_date' => $formatedDay->format('Y-m-d'),
             'event_starttime' => $request->event_starttime,
             'event_endtime' => $request->event_endtime   
            ]
    );

Luka left a reply on Save HasMany Relationship With Data Field In Second Table

No change if I add the field directly. If I use below in the EventDates Model then I get

 protected $dates = ['event_date'];

Data missing
 InvalidArgumentException

…\vendor\nesbot\carbon\src\Carbon\Carbon.php 775

If I remove it then I get a SQL Error because of the wrong format.

Luka left a reply on Save HasMany Relationship With Data Field In Second Table

I want to be able to dynamically create additional dates, but I wanted to first try to get one added.

The Error I am getting is

 InvalidArgumentException
 Data missing  

Luka left a reply on Save HasMany Relationship With Data Field In Second Table

Oh ok, I was not aware of this and will have a look into it. But is there is no better way to get it sorted on the Server side with Laravel? I think it could turn very messy since I want to allow multiple Dates to be added to the Form so it would be best if it could be done on the server side, but I struggle to figure out how to save the hasMany relationship after saving the event.

Luka started a new conversation Save HasMany Relationship With Data Field In Second Table

I have got 2 Tables. events and event_dates Its a 1:n Relationship. So I have set up my realtionship in both Models:

class Event extends Model
{

    protected $fillable = ['event_name', 'event_description'];
 
    public function eventdates()
    {
        return $this->hasMany('App\EventDates');
    }

}

class EventDates extends Model
{

    protected $fillable = [ 'event_date','event_starttime','event_endtime','event_id'];

    protected $dates = ['event_date'];
 
    public function event()
    {
        return $this->belongsTo('App\Event');
    }
 }

In my EventsController I now want to save the Event and 1 or multiple Event Dates if the Event goes over multiple days. So I have the following:

 public function store(Request $request)
 {
   
    $data = request()->validate([
        'event_name' => 'required',
        'event_date' => 'required',
    ]);

    $event = Event::create($request->all());
    $event->eventdates()->create($request->all());
}

First of all, is it correct to hand over the $request->all() to my relationship? I do have a problem with the date, but rest works. The event_date column is of type date which needs the format 21-08-2018 but my format from the timepicker is 2018-08-20. How do I format my date in between? Any suggestions?

09 Aug
3 months ago
08 Aug
3 months ago

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

@ 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()

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
03 Aug
3 months ago

Luka started a new conversation Quill Wysiwyg,Vuejs And Quill-image-resize-module

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?

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

Luka started a new conversation How Can I Use Replace In Query?

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?

01 Aug
3 months ago

Luka left a reply on Laravel 5.6, Bootstrap 4 + Template, JQuery And Vue

@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.

13 Jun
5 months ago

Luka left a reply on How To Set A Checkbox As Set On Edit Form

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

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;
                 }
            },
12 Jun
5 months ago

Luka left a reply on How To Set A Checkbox As Set On Edit Form

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

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

.... 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

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|{…}|

22 May
5 months ago

Luka started a new conversation How To Set A Checkbox As Set On Edit Form

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);
       });
  }  
29 Apr
6 months ago

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

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

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.

28 Apr
6 months ago

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

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

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?

26 Apr
6 months ago

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

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.

11 Apr
7 months ago

Luka left a reply on Laravel Validation For Array Causes Problem

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

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

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

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

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?

29 Mar
7 months ago

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

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

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.

27 Mar
7 months ago

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

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

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

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

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.

26 Mar
7 months ago

Luka left a reply on Where To Store Store Global Information ?

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 ?

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 ?

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?

13 Mar
8 months ago

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

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;
        });
    },
07 Mar
8 months ago

Luka left a reply on How To Create An Editable Table With Vue.js

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>
06 Mar
8 months ago

Luka left a reply on How To Create An Editable Table With Vue.js

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

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.