Luka

Luka

Member Since 3 Years Ago

Experience Points 3,900
Experience Level 1

1,100 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 17
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

06 Sep
1 week ago

Luka left a reply on Laravel 6 On Shared Hosting Not Working

You mean the Hosting company?

Luka left a reply on Laravel 6 On Shared Hosting Not Working

5.6 worked fine. 5.7 and 5.8 came up with a very strange issue that it would send Mailables, but not the "resend Verification" Notification. The "Forgot Password" Notification works as well. When I change the Mail settings to use maitrap, then the Resend Verification would be send. I am trying to find a solution for this since 4 month, but no luck so today I tried to install Laravel 6 to see if that would work, but now got that issue. I tried it before with a fresh install of 5.7 and then the notification was send, but why it would work with maitrap but not with the Mailserver settings from the Hosting company? I really don't understand it.

Luka left a reply on Laravel 6 On Shared Hosting Not Working

Yes, 5.8 was working.

Luka left a reply on Laravel 6 On Shared Hosting Not Working

No, I have installed everything locally and then uploaded all the files to the shared hosting, but when I open the Website I get that error shown.

Luka started a new conversation Laravel 6 On Shared Hosting Not Working

I have installed Laravel 6 all day long and just moved it onto a Shared Hosting Server. Unfortunately I get the error "The Process class relies on proc_open, which is not available on your PHP installation." It is actually disabled and Customer support did tell me that this can not be changed for security reasons.

Is there any way to get around it or does it mean I can not use Laravel 6 on Shared Hosting?

30 Aug
2 weeks ago

Luka left a reply on How To Replace Laravel 5.7 Verify Email Notification With View

I have to dig this out again, since I never solved it. My "Verify Email" is actually a HTML "Welcome Email" with Username and Password inside and a lot of blah. I also have the "Verify Email" Button inside of it. All this is a Mailable and I use a HTMl View.

The problem I still have is to create a temporarySignedRoute. When I use the built in Verify Email Notification then it uses the Notification ID, I guess that is given when a new Notification is created. Anyway, I don't create a Notification so I have to use a different number, but what would I use and would the automatic check if that SignedRoute is valid still work, mark the User as Verified or would I have to hook into that as well and write my own check? When somebody ignores the Verify Email Button in the Welcome Email and instead tries to log in directly then they obviously get the message shown they first have to verify and click if they want a new verification email, in that case I do want to use the simple Verify Email Notification and not send out a new Welcome Email. I am just lost with this and any hint is very welcome.

28 Aug
2 weeks ago

Luka left a reply on Laravel 5.7 Resend Verification Email Not Working On Server

Hi everybody, I have still not been able to fix this problem. Everything works on localhost, but on the server I can send Emails but the Verify Email is not send out. The Sourcecode I am using is above. I have in the meantime updated the code to Laravel 5.8 but the problem is still there on the server.

02 May
4 months ago

Luka left a reply on Laravel 5.7 Resend Verification Email Not Working On Server

I have now installed a clean fresh Laravel Application on the Server, just to test it and the Verify Email was send out. The difference I have is that I do not use the Laravel Register etc instead an Admin uses a Form to add a Member. When the user is added to the Db, a Mailable Welcome Email is created with login Details and a Verification Link inside. All that is send out fine. Is it possible that this somehow disables the integrated Resend Verify Email i am now trying to use? I otherwise can not find the problem.

30 Apr
4 months ago

Luka left a reply on Laravel 5.7 Resend Verification Email Not Working On Server

I only use Mailtrap when I test locally on localhost so that I can test if Emails are send and the Email is send. On the Server I use the settings for my Shared Hosting, so no Mailtrap there.

Luka left a reply on Laravel 5.7 Resend Verification Email Not Working On Server

Thank you for the information and I thought the same, if there would be a smtp issue then no emails should be send out but they are.

I have now added the code I am using, but as I said, if I use localhost and mailtrap its send out. Is there possibly anything I could be missing on the server?

User.php


namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements MustVerifyEmail
{
   use Notifiable;
   use HasRoles;

   protected $dates = ['renewed'];



   protected $fillable = [
      'name', 'email', 'password',
   ];

    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    protected $hidden = [
        'password', 'remember_token',
    ];

Added custom email routes in web.php

 // Email Verification Routes...
 Auth::routes(['verify' => true]);
 Route::get('email/verify', 'Auth\[email protected]')->name('verification.notice');
 Route::get('email/verify/{id}', 'Auth\[email protected]')->name('verification.verify');
 Route::get('email/resend', 'Auth\[email protected]')->name('verification.resend');

In Http\Kernel.php

protected $routeMiddleware = [
   'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
   'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
 ] 

In the EventServiceProvider.php

use Illuminate\Support\Facades\Event;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
  /**
   * The event listener mappings for the application.
   *
   * @var array
   */
     protected $listen = [
      Registered::class => [
        SendEmailVerificationNotification::class,
     ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

     }

Added the resources/views/auth/verify.blade.php

I have also done the necessary changes to the create_users_table migration

$table->timestamp('email_verified_at')->nullable();

Luka left a reply on Laravel 5.7 Resend Verification Email Not Working On Server

Thank you. I checked the Logs on the Server, but nothing in there. May I ask, should the Mail Settings be in the .env file or in the mail.php ? and what driver would you suggest?

Luka left a reply on Laravel 5.7 Resend Verification Email Not Working On Server

smtp. But as I said both other Emails are send without any Problem, it is only the email/resend which does not send an Email out. Any ideas how I can debug it?

Luka left a reply on Laravel 5.7 Resend Verification Email Not Working On Server

Well it's the same routes as on local so that should work and I would assume I would get a routing error anyway instead I get the success message shown " A fresh verification link has been sent to your email address." But this is the only Email which does not arrive and no Error is shown, all the other mails are send successfully.

Luka started a new conversation Laravel 5.7 Resend Verification Email Not Working On Server

I have created a new Project with Laravel 5.7. Everything works fine locally a Email gets send out with login details and when you try out to log in without having clicked the Verify link then it shows you the option to have the Verification Email resend which works fine locally with using Mailtrap. I have then moved everything to the server. The Welcome Email with Login details is send fine, the "Lost Password Email" is send but when I click on resend Verification Email, nothing arrives. So that is the only one not being send and I can not make it out where the Problem is. I have uploaded all the files multiple times, I added some dd on some of the vendor files but everything seems to be the same from Local to Server. Any ideas anyone?

03 Feb
7 months ago

Luka left a reply on Spatie Permission Protect Controller In Constructor

@TYKUS - Thank you ! No idea why I did not think of that.

Luka started a new conversation Spatie Permission Protect Controller In Constructor

I have installed Spatie Permission. I have created different roles and protect mainly the whole Controller by adding the below in my Controller: That means only if you are a Super-Admin or Document Admin will you be able to access the different methods from the Controller except the index method which anyone can access.

I have now got 1 Controller where it is the other way round. I want to protect just 1 Method and all others should be accessible. I could obviously just add them all in the except Array, but I was wondering if there is another way to do it. I hope somebody got a hint. Thank you in advance.

 public function __construct()
    {
        $this->middleware(['auth', 'clearance']);
        $this->middleware(['role:Super-Admin|Document Admin'],['except' => ['index']]); 
}
14 Jan
8 months ago

Luka left a reply on How To Replace Laravel 5.7 Verify Email Notification With View

Because if I see it right then this is just views for showing that you have to verify your Email or to request a new Verification Email, but the email and it's content itself is a Notification. Correct me if I am wrong.

Luka started a new conversation How To Replace Laravel 5.7 Verify Email Notification With View

I have installed Laravel 5.7 and set up the Email Verification. I would like to use Views for the Email instead of the Notification. So I created the Mail File below and I created the View.

WelcomeEmail.php

namespace App\Mail;

use Illuminate\Bus\Queueable; 
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class WelcomeEmail extends Mailable
{
  use Queueable, SerializesModels;

/**
 * Create a new message instance.
 *
 * @return void
 */
public function __construct($user,$password)
{
     
     $this->newUser = $user;
     $this->password = $password;
  
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
  
    return $this->markdown('emails.welcomemail') //pass here your email blade file
        ->with([
                    'firstname' => $this->newUser['firstname'],
                    'email' => $this->newUser['email'],
                    'password' => $this->password,
                    'token' => ?????,
            ]);
}
}

In my Controller I call up the file like this:

     try {
       \Mail::to($user->email)->send(new WelcomeEmail($user,$user->password));
              
    } catch (\Exception $e) {
                echo 'Error - '.$e;
    }

I now struggle with the token. In the Laravel 5.7 Notification they use the following way:

  protected function verificationUrl($notifiable)
  {
    return URL::temporarySignedRoute(
        'verification.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]
    );
   }

I would think that I have to create the Token in the Controller and then have in WelcomeEmail.php $user->token. I would like the token created as above, but what is $notifiable->getKey() ?? Or is there a better way?

18 Dec
8 months ago

Luka left a reply on Tinymce, Vuejs And Image Upload Not Working

Ok, I found a solution, just in case somebody is looking for something similar I will share it here. You have to add the Token so you have to overwrite the images_upload_handler function.

The only issue I have now got is that I create a folder dynamically in the upload method in my controller, but I would like that multiple images in a Post to be saved in the same folder. See the bottom Part which is my Controller. I thought about getting the folder name returned an then adding that into a hidden field but if I add this.folder = json.folder then nothing gets added. Any idea how I could solve this?

data () { 
            return { 
            name: 'app',
           
            myModel:'',
            theme: "modern",
            myToolbar1: 'undo redo | bold italic underline forecolor backcolor | alignleft aligncenter alignright alignjustify | hr bullist numlist outdent indent | link image table | code preview',
            myPlugins: "link image code preview imagetools table lists textcolor hr wordcount",
           
            myInit: {
              
                images_dataimg_filter: function(img) {
        return false;
                    return img.hasAttribute('internal-blob');
                },
                convert_urls : false,
                height:500,
                automatic_uploads: false, 
                images_upload_base_path: '/../../',
                relative_urls : false,

                // override default upload handler to simulate successful upload
                images_upload_handler: function (blobInfo, success, failure,folderName) {
                    var xhr, formData;
                    xhr = new XMLHttpRequest();
                    xhr.withCredentials = false;
                  
                    xhr.open('POST', '/api/upload-image');
                    var token = document.head.querySelector("[name=csrf-token]").content;
                    xhr.setRequestHeader("X-CSRF-Token", token);
                  
                    xhr.onload = function() {
                        var json;
                      
                        if (xhr.status != 200) {
                            failure('HTTP Error: ' + xhr.status);
                            return;
                        }
                        json = JSON.parse(xhr.responseText);

                        if (!json || typeof json.location != 'string') {
                            failure('Invalid JSON: ' + xhr.responseText);
                            return;
                        }
                        success(json.location);
                     
                    };
                 
                    formData = new FormData();
                    formData.append('file', blobInfo.blob(), blobInfo.filename());
              
                    xhr.send(formData);
                   
                }                
            }, 


public function uploadImages()
{
  $folder = uniqid();
  if (!\Storage::exists($folder)) {
        \Storage::disk('posts')->makeDirectory($folder);
  }

  $imgpath = \Storage::disk('posts')->put($folder,request()->file('file'));

  return \Response::json(['folder' => $folder, 'location' => '/storage/uploads/posts/'.$imgpath]);

}

14 Dec
9 months ago

Luka started a new conversation Tinymce, Vuejs And Image Upload Not Working

Hi there, I am trying to implement tinymce in my vuejs component and got it finally to work. I use the official TinyMCE Vue component. I now wanted to add an Image Upload and have to admit that I have got no idea how to get it to work. I was hoping that the Image does not get uploaded straight away and that it will just show up in the editor and only when I send of the whole form it will be send. I assumed to get it to work by setting automatic_uploads to false, but the Image does get send straight away and I get the Error 419 which I suppose is the X-CSRF-TOKEN error. I think I am supposed to do all the settings in the init function, but I have got no idea how to access the function. In actual fact I have got no idea at all how this is supposed to work together and hope somebody can point me in the right direction. My current source code is below.

<template>
<div>
<form method="post" action="" @submit.prevent="onSubmit" @keydown="errors.clear()">
    <fieldset class="add-form"><legend class="add-form">
    <h3>Article Details</h3></legend>
   <label class="required" for="fname">Headline</label>
   <input class="form-control"  v-model="post.title" id="fname" placeholder="Headline">
   <span class="invalid-feedback" v-text="errors.get('title')"></span>
   <tinymce v-model="post.body"
        :plugins="myPlugins" 
        :toolbar ="myToolbar1"
        :init="myInit"
    >
 </tinymce>   

</form> 
</div>

</template>

 <script>
 import Editor from '@tinymce/tinymce-vue';
 // Import TinyMCE
 import tinymce from 'tinymce/tinymce';
 // A theme is also required
 import 'tinymce/themes/modern/theme';

 export default{
    components: {
           'tinymce': Editor // <- Important part
    },

    data () { 
            return { 
            name: 'app',
            myModel:'',
            theme: "modern",

            myToolbar1: 'undo redo | bold italic underline preview | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
            myPlugins: "link image code preview imagetools",
           
            myInit: {
                    automatic_uploads: false, 
                    images_upload_url: '/api/upload-image',   
            },
24 Nov
9 months ago

Luka started a new conversation Valdiation On An Array For An Edit Function To Check Unique

I have a rather confusing problem I try to solve. I have a User Table. A Main User can have a second User added so they are associated. I now have an Edit Form. Let's say that I want to edit User Joe to add his son Bill. The Email Address has to be unique but of course it needs to filter out Joes's Email on Joe but Bills Email needs to be unique on the whole database since I do not have an ID yet. So the way I do it:

   $input = $request->all();
    $registeredMembers = count($input);
    
    $parent_ka_no = null;
    $associatedAdded = false;
    for($counter = 0; $counter<$registeredMembers; $counter++){
        // If there is a User Id then it means the User is already in the database         
        if(isset($input[$counter]['id']) && $input[$counter]['id'] != ''){
            $id = $input[$counter]['id'];
           
            $user = User::findOrFail($id); //Get role specified by id
            
            $validator =  $this->validate($request, 
                [
                $counter.'.email'=>'required|unique:users,email,'.$id,
                $counter.'.ka_no'=>'distinct|required|unique:users,bbka_no, '.$id,
                ],
                [
                '*.email.required' => 'Please supply a valid Email Address',
                '*.email.email' => 'Please supply a valid Email Address',
                '*.email.unique' => 'The supplied Email Address is already in use',
                '*.ka_no.required' => 'Please enter a KA Number',    
                '*.ka_no.unique' => 'The KA No has already been taken.',
                '*.ka_no.distinct' => 'This KA is a duplicate. Please make sure the KA Number is unique',  
                ]
            );
          /*
            if($registeredMembers > 1){
                $validator =  $this->validate($request, 
                [
                    '1.password'=>'required|min:5', 
                ],
                [
                    '1.password.required' => 'Please enter a Password.',
                ]);
            }
            */
        }else{
            // The User is not in the database yet and since it is on the Edit Form, it must be that an associated was added
                $user = new User;
                
                $this->validate($request, [
               
                    $counter.'.email'=>'required|unique',
                    $counter.'.ka_no'=>'distinct|required|unique',
                    $counter.'.password'=>'required|min:5',
                ],             
                [
            
                    $counter.'.email.required' => 'Please supply a valid Email Address',
                    $counter.'.email.email' => 'Please supply a valid Email Address',
                    $counter.'.email.unique' => 'The supplied Email Address is already in use',
                    $counter.'.ka_no.unique' => 'The KA No has already been taken.',
                    $counter.'.ka_no.required' => 'Please enter a KA Number',
                    $counter.'.ka_no.unique' => 'The supplied KA Number is already in use',
                    $counter.'.ka_no.distinct' => 'This KA is a duplicate. Please make sure the KA Number is unique',  
                ]);
                $user->membership_status_id=1;
                
             
                
                $associatedAdded = true;
        }

   Is this way correct? It seems to work partly, but does not work all the time as expected, but can not even say what goes wrong when. Obviously as soon the son is added and I do an edit again, I would have an ID for the son as well so this time it would have to be a Validation excluding the ID for that User. I am not sure how good I explain it, but maybe somebody understands and can tell me if this is the right approach and sees any small error somewhere? Thank you very much.
10 Nov
10 months 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
1 year 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
1 year 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>

  <div class="dates">
        <div class="form-group row">
            {{ Form::label('Date/Time:', '',array('class'=>'required col-sm-2 col-form-label')) }}

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

<input type="file" class="form-control-file" name="event_image" id="exampleInputFile" aria-describedby="fileHelp">
                            <small id="fileHelp" class="form-text text-muted">Please upload a valid image file. Size of image should not be more than 2MB.</small>
        
        {{ Form::submit('Save Details', array('class' => 'btn btn-success btn-lg btn-block')) }}
        {{ Form::close() }}
29 Aug
1 year 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
1 year 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  

Reading about it, do I need something like a Mutator in the EventDates Model?

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
1 year ago
08 Aug
1 year 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.

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

@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
1 year 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
1 year 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
1 year 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
1 year 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? Thank you very much in advance.

 <ul>
 <li v-for="(availableRole, index) in availableRoles">
   <input type="checkbox" v-model="user.roles" :value="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
1 year 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
1 year 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.