Charrua

Charrua

Member Since 1 Year Ago

A Coruña

Owner at Charrua

Experience Points 5,350
Experience Level 2

4,650 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 20
Lessons
Completed
Best Reply Awards 0
Best Reply
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.

25 Jun
22 hours ago

Charrua left a reply on Set A Unsubscribe Link On Emails Using Maligun And Mailable

@AURAWINDSURFING - Thank you for your help, the Mailgun way is to activate an option inside Mailgun dashboard and that'll include the unsubscribe link automatically on each mail that I send trough Laravel using markdown.

I have placed a support ticket on Mailgun, let's see what they answer... I'll post it here.

21 Jun
4 days ago

Charrua started a new conversation Many To Many Relationships Attach/sync The Same Model

Hello, I'm working on an invoicing app. I have my Invoice and Product models.

In my DB I have a salables table that holds the relationship between Invoices and Products, in this case I'm using many to many polymorphic relationship, as I have also other models, like Budgets, etc.

So in that table I would save the products that are in the invoice or in the budget, as other data, as quantity, price, etc....

The problem is that when I save the invoice and attach products to the salables table, they do not appear to be saved.

Example, if I send product ID 1,2,3,4, each with internal data as quantity, there is no problem. To save I'm using $invoice->products()->attach($items);

The main issue, is when in the same invoice, I have for example the same product two times, ID 1 and ID 1, but with different quantities or prices... The problem is that it only saves one copy of the product.

That is because to save the related models, Laravel uses ID as key inside the array I'm passing to the attach() method. Is there other way to achieve this? any ideas?

20 Jun
5 days ago

Charrua left a reply on Set A Unsubscribe Link On Emails Using Maligun And Mailable

@AURAWINDSURFING - Hello! I'm already using that, if you saw my code I'm using ->markdown('emails.group-a-noshow') the problem is how to include a Mailgun unsubscribe link on it.

Thank you anyway ;)

18 Jun
1 week ago

Charrua started a new conversation Set A Unsubscribe Link On Emails Using Maligun And Mailable

I'm sending emails trough Mailgun in my Laravel app. At this moment I manage maligun unsubscribes with an automatic feature on maligun website (track unsubscribes). This adds a link on each email at the bottom.

The problem is that I wanted to manage unsubscribes from Laravel, and mark recipients with a STOP field on database. This is to unsubscribe users from transactional emails but not for important emails.

Is there a way to include the unsubscribe link for maligun in a programmatically way?

This is my mailable

/**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {   
        
        $this->replyTo($this->appointment->school->email)->markdown('emails.appointments.group-a-noshow');

        $this->subject('Sorry we missed you!');

        $this->withSwiftMessage(function ($message) {
            $message->getHeaders()
                    ->addTextHeader('X-Mailgun-Variables', json_encode([
                        'model_id' => $this->appointment->id,
                        'model' => get_class($this->appointment),
                        'email_type' => 9 
                    ]));
        });

    }
13 Jun
1 week ago

Charrua left a reply on Get Relation Inside Notification $notifiable

Pease ignore this question as the relation is resolving as it should. I can access $notifiable->school without problem.

Charrua started a new conversation Get Relation Inside Notification $notifiable

I'm trying to get a relation inside the $notifiable variable, but it doesn't exists. Is there a way to add this or maybe create a new query inside for loading the model with the relation? My model Appointment has a school relation.

I was thinking on calling inside public function toTwilio($notifiable) something like:

public function toTwilio($notifiable)
    {
        
    //get appointment with school relation
    $appointment = \App\Appointment::with('school')->find($this->notifiable->id);

        $tinyUrl = Bitly::getUrl('http://192.168.2.206:8080/appt-a/'.$notifiable->uuid); // http://bit.ly/nHcn3
                
        $from = '+'.$appointment->school->twilio_number;
        
        $content = "Sorry we missed you! Let's reschedule your free class " . $tinyUrl . ". If you need further help call or text your school " .  $appointment->school->phone;

        return (new TwilioSmsMessage())
            ->content($content)
            ->from($from)
            ->statusCallback('.../webh/status-sms');

    }


This is my actual code failing, see that I'm not using $appointment but $notifiable

<?php

namespace App\Notifications\Appointments;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

use App\Mail\Appointments\GroupANoShowMail as Mailable;
use NotificationChannels\Twilio\TwilioChannel;
use NotificationChannels\Twilio\TwilioSmsMessage;
use Bitly;

class GroupANoShow extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [TwilioChannel::class];
    }


    public function toTwilio($notifiable)
    {
        
        $tinyUrl = Bitly::getUrl('http://192.168.2.206:8080/appt-a/'.$notifiable->uuid); // http://bit.ly/nHcn3
                
        $from = '+'.$this->notifiable->school->twilio_number;
        
        $content = "Sorry we missed you! Let's reschedule your free class " . $tinyUrl . ". If you need further help call or text your school " .  $this->notifiable->school->phone;

        return (new TwilioSmsMessage())
            ->content($content)
            ->from($from)
            ->statusCallback('.../webh/status-sms');

    }
    
}

12 Jun
1 week ago

Charrua left a reply on Let Public Vue SPA To Store Data On Laravel API (authenticated In Some Way)

@AUDUNRU - @AUDUNRU - Great idea! Thank you for your help! I will try that :)

08 Jun
2 weeks ago

Charrua started a new conversation Let Public Vue SPA To Store Data On Laravel API (authenticated In Some Way)

Hi, I have a Laravel app that manages a school calendar, multiple manager users can add appointments to calendar.

When an appointment doesn't show up, we will be firing some automated email to the member for re-schedule a new appointment. The email will contain a button for re-chedule, when clicked, members will be redirected to SPA made on Vue.

I will want to secure this in some way, the basic ideas that come to me are:

  • Securing the API: maybe some sort of authentication between the SPA and the API or maybe the API will only let this SPA's domain to call an API route (some sort of whitelist domain to call API route) At first I was thinking on using Laravel Passport but I couldn't find a use case that fits.

  • Securing the SPA: only members that are sent the email will have access to the SPA

What will be your recommendations/ideas?

07 Jun
2 weeks ago

Charrua left a reply on Firing An Event And Access To An $event->notification

@JOHNBRAUN - John, was returning an error on trying to access a private property. You were in the right path, making the prop public $communication on the notification file fixed the issue. I can access it now :)

Thank you.

Charrua left a reply on Firing An Event And Access To An $event->notification

This is the log output, maybe I can't access to communication object because is private...

[notification] => App\Notifications\Communications\CommSMS Object
        (
            [communication:App\Notifications\Communications\CommSMS:private] => App\Communication Object
                (
                    [dates:protected] => Array
                        (
                            [0] => deleted_at
                        )

                    [connection:protected] => mysql
                    [table:protected] => 
                    [primaryKey:protected] => id
                    [keyType:protected] => int
                    [incrementing] => 1
                    [with:protected] => Array
                        (
                        )

                    [withCount:protected] => Array
                        (
                        )

                    [perPage:protected] => 15
                    [exists] => 1
                    [wasRecentlyCreated] => 
                    [attributes:protected] => Array
                        (
                            [id] => 67
                            [title] => test message
                            [message] => This is a test message. Hola!
                            [type] => sms
                            [communication_type_id] => 6
                            [groups] => 
                            [programs] => 
                            [school_id] => 2
                            [authorized_by] => dp
                            [button_text] => 
                            [button_url] => 
                            [image] => 
                            [image_url] => 
                            [sent] => 1
                            [sent_on] => 2019-06-07 05:11:55
                            [deleted_at] => 
                            [created_at] => 2019-06-06 14:14:43
                            [updated_at] => 2019-06-07 05:11:55
                        )

                    [original:protected] => Array
                        (
                            [id] => 67
                            [title] => test message
                            [message] => This is a test message. Hola!
                            [type] => sms
                            [communication_type_id] => 6
                            [groups] => 
                            [programs] => 
                            [school_id] => 2
                            [authorized_by] => dp
                            [button_text] => 
                            [button_url] => 
                            [image] => 
                            [image_url] => 
                            [sent] => 1
                            [sent_on] => 2019-06-07 05:11:55
                            [deleted_at] => 
                            [created_at] => 2019-06-06 14:14:43
                            [updated_at] => 2019-06-07 05:11:55
                        )

                    [changes:protected] => Array
                        (
                        )

                    [casts:protected] => Array
                        (
                        )

                    [dateFormat:protected] => 
                    [appends:protected] => Array
                        (
                        )

                    [dispatchesEvents:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [relations:protected] => Array
                        (
                            [school] => App\School Object
                                (
                                    [connection:protected] => mysql
                                    [dates:protected] => Array
                                        (
                                            [0] => deleted_at
                                        )

                                    [table:protected] => 
                                    [primaryKey:protected] => id
                                    [keyType:protected] => int
                                    [incrementing] => 1
                                    [with:protected] => Array
                                        (
                                        )

                                    [withCount:protected] => Array
                                        (
                                        )

                                    [perPage:protected] => 15
                                    [exists] => 1
                                    [wasRecentlyCreated] => 
                                    [attributes:protected] => Array
                                        (
                                            [id] => 2
                                            [name] =>
                                            [ata_id] =>
                                            [email] => 
                                            [phone] =>
                                            [address] => 
                                            [sms_from] =>
                                            [twilio_number] =>
                                            [sms_address] => 
                                            [shop_shipping_id] => 1
                                            [deleted_at] => 
                                            [created_at] => 2016-08-30 06:00:00
                                            [updated_at] => 
                                        )

                                    [original:protected] => Array
                                        (
                                            [id] => 2
                                            [name] =>
                                            [ata_id] =>
                                            [email] => 
                                            [phone] =>
                                            [address] => 
                                            [sms_from] =>
                                            [twilio_number] =>
                                            [sms_address] =>
                                            [shop_shipping_id] => 1
                                            [deleted_at] => 
                                            [created_at] => 2016-08-30 06:00:00
                                            [updated_at] => 
                                        )

                                    [changes:protected] => Array
                                        (
                                        )

                                    [casts:protected] => Array
                                        (
                                        )

                                    [dateFormat:protected] => 
                                    [appends:protected] => Array
                                        (
                                        )

                                    [dispatchesEvents:protected] => Array
                                        (
                                        )

                                    [observables:protected] => Array
                                        (
                                        )

                                    [relations:protected] => Array
                                        (
                                        )

                                    [touches:protected] => Array
                                        (
                                        )

                                    [timestamps] => 1
                                    [hidden:protected] => Array
                                        (
                                        )

                                    [visible:protected] => Array
                                        (
                                        )

                                    [fillable:protected] => Array
                                        (
                                        )

                                    [guarded:protected] => Array
                                        (
                                            [0] => *
                                        )

                                    [forceDeleting:protected] => 
                                )

                        )

                    [touches:protected] => Array
                        (
                        )

                    [timestamps] => 1
                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [forceDeleting:protected] => 
                )

            [id] => 3c0b7b0b-235e-4c74-86ec-539e82cfaafb
            [connection] => 
            [queue] => 
            [chainConnection] => 
            [chainQueue] => 
            [delay] => 
            [chained] => Array
                (
                )

        )

Charrua left a reply on Firing An Event And Access To An $event->notification

@JOHNBRAUN - Hey John, running that dd() gives me nothing... I have already tried that...

dd($event->notification->communication) 
//or
dd($event->notification->communication->id)

Charrua started a new conversation Firing An Event And Access To An $event->notification

Hello, I have set an event listener to some SMS notifications.

The data I would like to get is the ID of the notification causer, for example I'm sending a group sms to some members, that message has the id 67 and is a Communication model. The problem is that I'cant access the object, this is my output.

Remember I wanted to access the ´id´ of the communication object. In the output is object `#8.

I have tried $event->notification->communication->id but nothing happens...

The output posted is from dd($event->notification)

App\Notifications\Communications\CommSMS
App\Notifications\Communications\CommSMS {#878
  -communication: App\Communication {#893
    #dates: array:1 [
      0 => "deleted_at"
    ]
    #connection: "mysql"
    #table: null
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:18 [
      "id" => 67
      "title" => "test message"
      "message" => "This is a test message. Hola!"
      "type" => "sms"
      "communication_type_id" => 6
      "groups" => null
      "programs" => null
      "school_id" => 2
      "authorized_by" => "dp"
      "button_text" => null
      "button_url" => null
      "image" => null
      "image_url" => null
      "sent" => 1
      "sent_on" => "2019-06-07 05:24:04"
      "deleted_at" => null
      "created_at" => "2019-06-06 14:14:43"
      "updated_at" => "2019-06-07 05:24:04"
    ]
    #original: array:18 [
      "id" => 67
      "title" => "test message"
      "message" => "This is a test message. Hola!"
      "type" => "sms"
      "communication_type_id" => 6
      "groups" => null
      "programs" => null
      "school_id" => 2
      "authorized_by" => "dp"
      "button_text" => null
      "button_url" => null
      "image" => null
      "image_url" => null
      "sent" => 1
      "sent_on" => "2019-06-07 05:24:04"
      "deleted_at" => null
      "created_at" => "2019-06-06 14:14:43"
      "updated_at" => "2019-06-07 05:24:04"
    ]
    #changes: []
    #casts: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: array:1 [
      "school" => App\School {#930
        #connection: "mysql"
        #dates: array:1 [
          0 => "deleted_at"
        ]
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #withCount: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:13 [
          "id" => 2
          "name" => "Huntersville"
          "ata_id" => 3278
          "email" => "[email protected]"
          "phone" => 7048958757
          "address" => "9616 Sherrill Estates Road, Huntersville, NC 28078"
          "sms_from" => 17048958757
          "twilio_number" => 17048102125
          "sms_address" => "9616 Sherrill Estates Rd, Huntersville"
          "shop_shipping_id" => 1
          "deleted_at" => null
          "created_at" => "2016-08-30 06:00:00"
          "updated_at" => null
        ]
        #original: array:13 [
          "id" => 2
          "name" => "Huntersville"
          "ata_id" => 3278
          "email" => "[email protected]"
          "phone" => 7048958757
          "address" => "9616 Sherrill Estates Road, Huntersville, NC 28078"
          "sms_from" => 17048958757
          "twilio_number" => 17048102125
          "sms_address" => "9616 Sherrill Estates Rd, Huntersville"
          "shop_shipping_id" => 1
          "deleted_at" => null
          "created_at" => "2016-08-30 06:00:00"
          "updated_at" => null
        ]
        #changes: []
        #casts: []
        #dateFormat: null
        #appends: []
        #dispatchesEvents: []
        #observables: []
        #relations: []
        #touches: []
        +timestamps: true
        #hidden: []
        #visible: []
        #fillable: []
        #guarded: array:1 [
          0 => "*"
        ]
        #forceDeleting: false
      }
    ]
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #fillable: []
    #guarded: array:1 [
      0 => "*"
    ]
    #forceDeleting: false
  }
  +id: "bbc7390f-9faf-4457-808f-906a337a493d"
  +connection: null
  +queue: null
  +chainConnection: null
  +chainQueue: null
  +delay: null
  +chained: []
}
31 May
3 weeks ago
30 May
3 weeks ago

Charrua started a new conversation Looking For A Vue Wrapper For Using PayPal

Hello, we wanted to use PayPal for payments on a website that let users pay for some workshops. Our backend would be written using laravel and our frontend using Vue.js.

The ideal way would be using Stripe, but in the country that the website is going to run (Uruguay), Stripe does not exist. And PayPal would be a solution...

Do you know/use any npm package that works with PayPal? Any experience? I've found https://www.npmjs.com/package/vue-paypal-checkout but I have no references.

Thank you.

27 May
4 weeks ago

Charrua left a reply on Need Help To Think Over A 3 Model Related Query

@DAVIDPETROV - Hi, the idea of using a time_notified column or similar, is not a bad idea, but there are many emails sent to the member, so that would not be a good idea. That's why we have an email log, to log the emails sent to the members.

My main issue here is how to test this query and not send the same email in the same week.

25 May
1 month ago

Charrua started a new conversation Need Help To Think Over A 3 Model Related Query

This is a school Laravel app, using 3 models Member for school members, Attendance for registering school attendance and EmailLog to see emails sent to members.

The main objective is to send "miss you" emails to inactive members on 4 ranges: one week inactive members, two week, one month and two month.

Let's only review the first case, one week inactive members. To select those members I created a local scope on the members model:

public function scopeOneWeekInactiveRange($query) {
        $query->whereDoesntHave('attendance', function ($query) {
            $query->where('scan_date', '>', now()->subDays(7));
        })
        ->whereHas('attendance', function ($query) {
            $query->where('scan_date', '>', now()->subDays(14));
        });
}

This will select all members that have previous activity but doesn't have activity on the last week, I think we are on the way...

Once we have the selection, I will fire through php artisan member:send-inactive-oneweek a notification. Once the notification email is delivered or opened, it will create a new row on email_logs table with the member and the email type sent, in this particular case email_type_id is 16.

My command looks like this:

public function handle(){
        $members_to_notify = \App\Member::OneWeekInactiveRange()->get();

        //send notification 
        Notification::send($members_to_notify, new InactiveOneWNoti());
}

If I run this command on a daily basis, my school members that are on that range will get the notification all days. That is not what we wanted.

So I've created another local scope on our Member model. The main purpose for this scope is to select only members that doesn't have an email_type_id equal to 16 on the last week. If it does, this means that an email was already fired to this member.

public function scopeOneWeekInactiveRangeEmail($query) {
        $query->whereDoesntHave('emailLog', function ($query) {
            $query->where('created_at', '>', now()->subDays(7))
                    ->where('email_type_id', 16);
        });
}

So now, I have modified the artisan command php artisan member:send-inactive-oneweek to:

public function handle(){
        $members_to_notify = \App\Member::OneWeekInactiveRange()
                        ->OneWeekInactiveRangeEmail()
                        ->get();
    
        //send notification 
        Notification::send($members_to_notify, new InactiveOneWNoti());

}

Here is the MAIN ISSUE:

My mind says to me that this query is good to go, but I need a way to test it, I have make many drawings with possibilities but I can't find a way to really test this, I don't want an email sent two times on the same week. I wanted to only send this email again if the member has the one week inactive condition again in the future. Any ideas?

21 May
1 month ago

Charrua left a reply on Laravel Js Bundle Size Is Too Heavy, Using PDFmake And Data Tables

Sadly the whole bundle pdfmake/build parsed size is 1.79Mb running nom run prod

Charrua started a new conversation Laravel Js Bundle Size Is Too Heavy, Using PDFmake And Data Tables

Hello, I'm using datatables.net plugin to order and export data to PDF. The issue is that the "pdfmake": "^0.1.56", package is about 2Mb of my app.js file, any ideas on reducing this? Thank you.

Charrua left a reply on Where To Place Logic To Check And Compare Model On Request

I have managed to create a new method on the model to check and return true/false. Seems to do the job.

Charrua started a new conversation Where To Place Logic To Check And Compare Model On Request

Hi, I wanted to compare and check every Transaction model when is requested.

Our problem is that some people of our sales team is selling products with a lower price. So we wanted to detect and "flag" visually those transactions for future review. This flag would be a simple red & bold on the transaction total. We list transactions on a table.

So I need something that checks against a collection, array or db every Transaction model. At first I think of global scopes, local scopes, mutators and assessors, but none of them seems to solve the problem.

Where do you think I can place the logic to check on every model and create the flag?

26 Apr
1 month ago

Charrua left a reply on Permission Error

issue solved by renaming /storage/framework/views/0c9eaf38a7c8de5cb461bff09b989a5ca40fa88d.php

Charrua started a new conversation Permission Error

Hello I use markdown for sending emails on my app, recently I have updated a logo link on my email template and I get now a permission error.

The template I'm modifying is located on resources/views/vendor/mail/html/message.blade.php

@component('mail::layout')
    {{-- Header --}}
    @slot('header')
        @component('mail::header', ['url' => '...'])
            <img src="https://.../img/logo_..._black_emails.png">
        @endcomponent
    @endslot

    {{-- Body --}}
    {{ $slot }}

    {{-- Subcopy --}}
    @isset($subcopy)
        @slot('subcopy')
            @component('mail::subcopy')
                {{ $subcopy }}
            @endcomponent
        @endslot
    @endisset

    {{-- Footer --}}
    @slot('footer')
        @component('mail::footer')
            &copy; {{ date('Y') }}. All rights reserved.
        @endcomponent
    @endslot
@endcomponent

The error I'm getting is:

[2019-04-26 12:23:09] production.ERROR: file_put_contents(/var/www/vhosts/.../laravel/storage/framework/views/0c9eaf38a7c8de5cb461bff09b989a5ca40fa88d.php): failed to open stream: Permission denied (View: /var/www/vhosts/.../laravel/resources/views/vendor/mail/html/message.blade.php) {"userId":1,"email":"...","exception":"[object] (ErrorException(code: 0): file_put_contents(/var/www/vhosts/.../laravel/storage/framework/views/0c9eaf38a7c8de5cb461bff09b989a5ca40fa88d.php): failed to open stream: Permission denied (View: /var/www/vhosts/.../laravel/resources/views/vendor/mail/html/message.blade.php) at /var/www/vhosts/.../laravel/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:122, ErrorException(code: 0): file_put_contents(/var/www/vhosts/.../laravel/storage/framework/views/0c9eaf38a7c8de5cb461bff09b989a5ca40fa88d.php): failed to open stream: Permission denied at /var/www/vhosts/.../laravel/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:122)
[stacktrace]
17 Apr
2 months ago

Charrua left a reply on Trying To Get Related Models Between Date Ranges, Need Advice On Architecture

@FTIERSCH - You are right, I was thinking in the wrong way. Thank you very much for your help! Solved my issue

Charrua left a reply on Trying To Get Related Models Between Date Ranges, Need Advice On Architecture

@FTIERSCH - Thank you for your help, this is getting closer, the result of that implementation is getting me the members that have activity between the range

now()->subDays(15) > 'scan_date' > now()->subDays(8)

Remember I need those members that have no activity on that date range

Charrua started a new conversation Trying To Get Related Models Between Date Ranges, Need Advice On Architecture

Hello, I'm struggling with obtaining some related models on custom date ranges. This is a school app that manages members and attendances. Each Member has many Attendance, when the member comes to school, a new record on the attendance table is inserted.

I would like to get some inactivity information to send some emails, for example: -members who are inactive one week -members who are inactive two weeks -members who are inactive one month -members who are inactive two months

The problem is that those members that are inactive for example one month, are also inactive one week, so if I send an email to inactive members from one week, also other inactive members are going to get this email.

I can get those ranges mentioned earlier, for example:

//Member.php
public function oneWeekInactive(){
    $date = new Carbon;
    $start = $date->copy()->subDays(8);
    $end = $date->copy();
    return $this->hasMany('App\Attendance')->whereBetween('scan_date', array($start, $end));
}

In my controller the query for those members is:

$members_to_notify = \App\Member::withoutGlobalScope(SchoolScope::class)
    ->whereNotNull('email')
    ->doesntHave('oneWeekInactive')
    ->get();

So my first question is, do you think I need to redefine those ranges as: -members who are inactive ONLY one week -members who are inactive ONLY two weeks -members who are inactive ONLY one month -members who are inactive ONLY two months

If the redefine is correct, how do you think I can get members for the first range get members with more than one week inactive but not two week inactive I know I need to subtract those members in some way but I'm stuck.

16 Apr
2 months ago

Charrua left a reply on Laravel Relation Query Taking Too Much Time To Load

@STAUDENMEIR - Seems that adding an index the query time is as expected, I'll post results here. Thank you

Charrua left a reply on Laravel Relation Query Taking Too Much Time To Load

@MUNAZZIL - I'm sorry but this does not work, thank you anyway ;)

Charrua left a reply on Laravel Relation Query Taking Too Much Time To Load

@MUNAZZIL - This does the same, 8 seconds waiting...

Charrua left a reply on Laravel Relation Query Taking Too Much Time To Load

@STAUDENMEIR - ``` $members = \App\Member::withoutGlobalScope(SchoolScope::class) ->whereNotNull('email') ->when($to_school, function ($query, $to_school) { return $query->where('school_id', $this->communication->school_id); }) ->has('attendance') ->get();

Charrua started a new conversation Laravel Relations Taking Too Much Time

Hello, I have two models, one for school Member and the other for school Attendance, each one with the corresponding database table.

My goal is to get all school members who have at least one attendance between some particular date, as an example let's take '2019-04-05' and '2019-04-12' (one week)

So in my Members model I have a relation:

public function attendance() {
    return $this->hasMany('App\Attendance')
->whereBetween('scan_date', array('2019-04-05', '2019-04-12'));
}

The problem is that the attendance table has like 76000 records now so the query takes about 8 seconds to get the results. Is there a way to make this query faster? maybe limit in some way?

09 Apr
2 months ago

Charrua started a new conversation Passing Laravel To Vue Collection Interpreted Different As Object And Array

Hello, I'm passing data to Vue from Laravel. I have a blade template and a Vue component that accept data on properties as:

<cash-sale-online-order-new
     :products="{{ $products }}">
</cash-sale-online-order-new>

Those products came from eloquent on a Laravel controller:

public function create(Request $request)
    {   
        
        $products = \App\Product::with(['product_type'])->get();

        return view('.....', compact('products'));
    }

This will give me an array of objects on Vue, and that is OK.

The problem is that when I $products = \App\Product::with(['product_type'])->get()->keyBy('id'); that collection, the result in Vue is an Object with Objects inside.

This is strange because if I inspect on Laravel with dd() both product queries (without keyBy('id') and with keyBy('id')) they both return a Collection and an Array inside, but for some reason they are differently seen by Vue.

Any ideas?

25 Mar
3 months ago

Charrua left a reply on Vue Child Component Is Updating Parent Data Without Event ?¿ Need Explanation

When assigning value to reference type, it will copy the pointer to the address. They point to the same memory address. ´´´ var obj1 = {a: 1} var obj2 = obj1 // copy the pointer to the address obj2 = {a: 2} // change obj2's value console.log(a) // {a: 2} console.log(b) = // {a: 2}

>if we assign a’s value to b and change b’s value will change a’s value.
They point to the same memory address.

>When we pass something to component, if it’s premitive type like “String”, “Number” and you change it’s value in component. Vue will trigger the checking function to let us know that we are changing the porps value. If it’s reference type like “Object” and you change it’s value in component. Vue will not trigger the checking function. Parent and child will share the value, point to the same address. They will change at the same time.

Charrua left a reply on Vue Child Component Is Updating Parent Data Without Event ?¿ Need Explanation

The strange thing is that I don't get any warnings on the developer console. Still investigating this I would love to fully understand.

24 Mar
3 months ago

Charrua started a new conversation Vue Child Component Is Updating Parent Without Event ?¿ Need Explanation

Hello, I'm using Vue components to send data to a parent component that is a form, each field is a child component. So for the child components I emit events as v-on:change="$emit('date_selected', date)", then I update the parent data by listening to those events.

The problem now is that I have some field that is updating parent without emitting any event, maybe is emitting something I can't see under the hood.

Parent component

<template>
    <div>
        <article-fields
            :products="products" 
            :items="items">
        </article-fields>    
        <a href="#" class="btn btn-sm btn-primary" v-on:click.stop.prevent="addArticle()">Add article</a>
    </div>         
</template>

<script>

    import articleFields from './form/articleFields';

    export default {

        components: {
            'article-fields': articleFields
        },
        props: {
            products: {
               type: Object,
               required: true,
            }
        },
        data () {
            return {
                items:[{product:{}, id:0, quantity:0, discount:0}],
            }
        },
        methods: {
            addArticle: function () {
                this.items.push( {product:{}, id:0, quantity:0, discount:0} )
            }
        }

    }
</script>

Child component

<template>   
    <div>
        <div v-for="(articulo, index) in items" v-bind:key="index">
            
            <select v-model="articulo.id" @change="assignProduct(articulo)">
                <option value="" disabled>Select...</option>
                <option v-for="(product) in products" :value="product.id" v-bind:key="product.id">
                    {{ product.name }} 
                </option>
            </select>

            <input v-model.number="articulo.product.price" type="text">
                           
            <input v-model.number="articulo.quantity" type="text">
                
            <input v-model.number="articulo.discount" type="text">
                
        </div>
    </div>        
</template>

<script>
    export default {
        inject: ['$validator'],
        props: {
            products: {
               type: Object,
            },
            items: {
               type: Array,
            }
        },
        methods: {
            assignProduct(item) {
                item.product = this.products[item.id]
            },
            removeArticle: function (index) {
                this.items.splice(index, 1)
            }
        }
    }
</script>

For some reason when I update the fields on child component, the items also get updated on parent. Anyone knows why this is happening?

05 Mar
3 months ago

Charrua left a reply on PUT Request From Axios => "405 Method Not Allowed"

Great, thank you all, issue solved!

04 Mar
3 months ago

Charrua left a reply on PUT Request From Axios => "405 Method Not Allowed"

Hello @sergiu17, all routes are registered as the controller is a resource controller, if I run php artisan route:list I get the following:

GET|HEAD   budgets   App\Http\Controllers\[email protected]
POST             budgets   App\Http\Controllers\[email protected]
GET|HEAD   budgets/create       App\Http\Controllers\[email protected]
DELETE.        budgets/{budget}   App\Http\Controllers\[email protected]
PUT|PATCH budgets/{budget}.  App\Http\Controllers\[email protected]
GET|HEAD   App\Http\Controllers\[email protected]
GET|HEAD.  App\Http\Controllers\[email protected]

My controllers update method is:

public function update(Request $request, $id)
    {
        //
    }

Charrua started a new conversation PUT Request From Axios => "405 Method Not Allowed"

Hi, I'm using Axios in a Laravel + Vue app. I have my resource controller and trying to update some model, so I'm sending a PUT request, but with no success.

I get 405 Method Not Allowed using this code:

axios.put('http://127.0.0.1:8000/budgets', {
        date: this.date,
        items: this.items,
        notes: this.notes,
        sub_total: this.subTotal,
        tax: this.tax,
        total: this.total,
})
.then(function (response) {
        console.log(response)
})
.catch(function (error) {
        console.log(error.response.data)
                           
})

I have also tried to use

axios.post('http://127.0.0.1:8000/budgets', {
    _method: 'PUT',
        date: this.date,
        items: this.items,
        notes: this.notes,
        sub_total: this.subTotal,
        tax: this.tax,
        total: this.total,
})
.then(function (response) {
        console.log(response)
})
.catch(function (error) {
        console.log(error.response.data)
                           
})

But no success, any ideas on how to solve this issue?

16 Feb
4 months ago

Charrua left a reply on Trying To Load Selected Value On Select

Hello Tray, sorry but your solution does't work.

Charrua started a new conversation Trying To Load Selected Value On Select

Hello I have an issue loading the selected option of a select input. Here is my code, items is the object I want to populate with the products object

<div class="form-row" v-for="(article, index) in items" v-bind:key="index">
    <label class="form-control-label" for="input-name">Producto</label>
    <select name="articulo" v-model="article.product" v-validate="'required'" class="form-control">
        <option v-for="(product) in products" :value="product">
            {{ product.name }} 
        </option>
    </select>
</div>

If I run this code I get the product object inside each item object as expected. The problem is the reverse situation, if start the items object populated on page load, the selected option is not selected.

I have found a way for the select to work and is to change the value of the option, instead to use the product object, use a property as product.name and the same on the select model article.product.name. The issue is that I need the value of each option to populate the item.product object.

04 Dec
6 months ago

Charrua started a new conversation Vue-router And Vue-stripe-elements-plus Issue

Hi, I'm building a SPA with Vue, two pages are using the <Card> component from vue-stripe-elements-plus.

The views that load the <Card> component are /gala and /seminars.

The problem is when I change from one view to the other, the <Card> component seems not to render again and an error is shown in console:

vue.runtime.esm.js?2b0e:587 [Vue warn]: Error in beforeMount hook: "IntegrationError: Can only create one Element of type card."

My routes are:

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'

Vue.use(Router)

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/gala',
      name: 'gala',
      component: () => import(/* webpackChunkName: "about" */ './views/Gala.vue')
    },
    {
      path: '/seminars',
      name: 'seminars',
      component: () => import(/* webpackChunkName: "about" */ './views/Seminars.vue')
    }
  ]
})

Maybe I'm missing something?

29 Nov
6 months ago

Charrua left a reply on Which OAuth 2.0 Flow Should I Use? Vue Form And API

@D9705996 - That is what I’m looking for now, if I need to authenticate or not... how can I resolve this? Any more ideas? How to determine if I need authentication to send the form data or not...

Charrua left a reply on Which OAuth 2.0 Flow Should I Use? Vue Form And API

@D9705996 - Great answer, thank you. The ticket form will be public and reachable by all guest users (eg domain.com/form), they will not need to login to fill and send the form. And my API will live on anotherdomain.com/api

Maybe I'm confused and is not the case to use authenticated API requests to my app because there is no login on the frontend... I thought on using authenticated requests to add some security to my API but maybe is not the use case here.

Charrua started a new conversation Which OAuth 2.0 Flow Should I Use? Vue Form And API

Hello, I'm new to OAuth and APIs. I have set my Laravel API endpoints to store and send responses for saving a resource. In other webpage I have a Vue public form for users to buy tickets and store them in the Laravel app.

If I use passport, what type of authorization flow (why, benefits) I need to use to authenticate all requests to my API? Thank you.

13 Nov
7 months ago

Charrua left a reply on Laravel Storing Images Outside Public Directory

@talinon you are right, that solved my issue. Thank you.

Charrua started a new conversation Laravel Storing Images Outside Public Directory

Hello, I'm trying to store images using the local driver. I have followed docs and created the symbolic link php artisan storage:link

I'm saving a file from a form and in my controller I have the following: $communication->image = Storage::putFile('messages', $request->file('image'));

The problem is that this is creating a directory messages inside storage/app/messages and not in storage/app/public/messages as it should.

My ´config/filesystems.php` is:

return [

    'default' => env('FILESYSTEM_DRIVER', 'local'),

    'cloud' => env('FILESYSTEM_CLOUD', 's3'),

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
        ],

    ],

];

Any ideas?

10 Nov
7 months ago

Charrua left a reply on Getting Error OuteNotificationFor() On Batch Email Notifications

This issue was solved. Code has no errors, I was using Supervisor to manage queues and I have forgot to restart it on production server.

09 Nov
7 months ago

Charrua started a new conversation Getting Error OuteNotificationFor() On Batch Email Notifications

Hello, I'm trying to send email to members on my app and I get the following error:

production.ERROR: Call to undefined method Illuminate\Database\Query\Builder::routeNotificationFor() {"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method Illuminate\Database\Query\Builder::routeNotificationFor() at /var/www/vhosts/.../laravel/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2483)

I have the members model with the Notifiable trait and the weird issue is that on my local machine the emails are delivered... The problem is on production... Any ideas?

The notifications are fired with:

Notification::send($members_to_notify, new CommMessage($communication));

And the CommMessageclass is:


namespace App\Notifications\Communications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

use App\Mail\Communications\Message as Mailable;

class CommMessage extends Notification implements ShouldQueue
{
    use Queueable;

    private $communication;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($communication)
    {
        $this->communication = $communication;
       
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return Mailable
     */
    public function toMail($notifiable)
    {
        return (new Mailable($this->communication))->to($notifiable->email);
    }
    
}

The mailable Message class is:

namespace App\Mail\Communications;

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

class Message extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * The appointment instance.
     *
     * @var Appointment
     */
    public $communication;
    
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($communication)
    {
        $this->communication = $communication;

    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $this->replyTo($this->communication->school->email)->markdown('emails.communications.message');

        $this->subject($this->communication->title);

        $this->withSwiftMessage(function ($message) {
            $message->getHeaders()
                    ->addTextHeader('X-Mailgun-Variables', json_encode([
                        'model_id' => $this->communication->id,
                        'model' => get_class($this->communication),
                        'email_type' => 11 //Communication message (EmailLogType)
                    ]));
        });

    }

}
13 Oct
8 months ago

Charrua left a reply on Scheduler Running With Delay (not On Time)

@hondnl this is the Plesk engineer answer:

This is a known issue with plesk-php7x which have libsodium package included for stronger cryptography.

Forced initialization of crypto library on startup each PHP script depletes entropy (/dev/random) and next processes wait for another portion of randomness. So any php script can cause entropy depletion.

The developers have submitted this issue as a bug PPPM-9444 which is planned to be fixed in one of the future Plesk updates.

Please subscribe to the following article to be notified when the bug is fixed: https://support.plesk.com/hc/en-us/articles/360010129094

11 Oct
8 months ago

Charrua started a new conversation Integrating Facebook Page_insights With Laravel

Hello, what would be a good workflow to integrate facebook page insights in a Laravel dashboard app?

I don't know where to start.

Any ideas would be great!