Charrua

Owner at Charrua

Hire Me

Experience

2,710

0 Best Reply Awards

  • Member Since 9 Months Ago
  • 14 Lessons Completed
  • 0 Favorites

20th August, 2018

Charrua left a reply on Use ClientRef Value When Sending SMS With Nexmo • 21 hours ago

problem solved creating a custom channel and a service provider to resolve NexmoCustomSmsChannel class.

Charrua left a reply on Creating Nexmo Custom Notification Channel • 21 hours ago

For someone looking for this answer, the problem was that I needed a service provider for NexmoCustomSmsChannel class to resolve.

18th August, 2018

Charrua started a new conversation Creating Nexmo Custom Notification Channel • 3 days ago

Hello, I'm creating a new Nexmo notification channel because I need to add some client-ref parameter to the Nexmo API request.

The original channel that packs with Laravel 5.6 has a send method:

/**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return \Nexmo\Message\Message
     */
    public function send($notifiable, Notification $notification)
    {
        if (! $to = $notifiable->routeNotificationFor('nexmo')) {
            return;
        }
        $message = $notification->toNexmo($notifiable);
        if (is_string($message)) {
            $message = new NexmoMessage($message);
        }
        return $this->nexmo->message()->send([
            'type' => $message->type,
            'from' => $message->from ?: $this->from,
            'to' => $to,
            'text' => trim($message->content),
        ]);
    }

I need to add the parameter as:

        return $this->nexmo->message()->send([
            'type' => $message->type,
            'from' => $message->from ?: $this->from,
            'to' => $to,
            'text' => trim($message->content),
        'client-ref' => 'some text...',
        ]);

So I tried to duplicate the channel and instantiate it as Laravel documentation on creating custom channel (https://laravel.com/docs/5.6/notifications#custom-channels)

I have created NexmoCustomSmsChannel and only add my parameter, so the final channel is a duplicate from the original only with one extra parameter:

<?php

namespace App\Channels;

use Nexmo\Client as NexmoClient;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\NexmoMessage;


class NexmoCustomSmsChannel 
{
    /**
     * The Nexmo client instance.
     *
     * @var \Nexmo\Client
     */
    protected $nexmo;

    /**
     * The phone number notifications should be sent from.
     *
     * @var string
     */
    protected $from;

    /**
     * Create a new Nexmo channel instance.
     *
     * @param  \Nexmo\Client  $nexmo
     * @param  string  $from
     * @return void
     */
    public function __construct(NexmoClient $nexmo, $from)
    {
        $this->from = $from;
        $this->nexmo = $nexmo;
    }

    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return \Nexmo\Message\Message
     */
    public function send($notifiable, Notification $notification)
    {
        if (! $to = $notifiable->routeNotificationFor('nexmo')) {
            return;
        }

        $message = $notification->toVoice($notifiable);

        if (is_string($message)) {
            $message = new NexmoMessage($message);
        }

        return $this->nexmo->message()->send([
            'type' => $message->type,
            'from' => $message->from ?: $this->from,
            'to' => $to,
            'text' => trim($message->content),
            'client-ref' =>  'some text...',
        ]);
    }
}

And my notification is like:

<?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\Channels\NexmoCustomSmsChannel;


class AppIntroNew extends Notification implements ShouldQueue
{
    use Queueable;


    private $appointment;


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



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



    /**
     * Get the Nexmo / SMS representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return NexmoMessage
     */
    public function toVoice($notifiable)
    {
        return (new NexmoMessage)->content('some sms content.');
    }
    
}

The error I get is:

[2018-08-18 04:23:58] local.ERROR: Target [Nexmo\Client\Credentials\CredentialsInterface] is not instantiable while building [App\Channels\NexmoCustomSmsChannel, Nexmo\Client]. {"exception":"[object] (Illuminate\Contracts\Container\BindingResolutionException(code: 0): Target [Nexmo\Client\Credentials\CredentialsInterface] is not instantiable while building [App\Channels\NexmoCustomSmsChannel, Nexmo\Client]. at /Users/.../Documents/Web/.../app/vendor/laravel/framework/src/Illuminate/Container/Container.php:918)

Any ideas?

17th August, 2018

Charrua left a reply on Use ClientRef Value When Sending SMS With Nexmo • 3 days ago

@crnkovic I have created App\Channels\NexmoCustomSmsChannel and copied the code, added the parameter I need but I get an error.

My Nexmo custom channel looks like this:

namespace App\Channels;

use Nexmo\Client as NexmoClient;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\NexmoMessage;

class NexmoCustomSmsChannel 
{
    /**
     * The Nexmo client instance.
     *
     * @var \Nexmo\Client
     */
    protected $nexmo;

    /**
     * The phone number notifications should be sent from.
     *
     * @var string
     */
    protected $from;

    /**
     * Create a new Nexmo channel instance.
     *
     * @param  \Nexmo\Client  $nexmo
     * @param  string  $from
     * @return void
     */
    public function __construct(NexmoClient $nexmo, $from)
    {
        $this->from = $from;
        $this->nexmo = $nexmo;
    }

    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return \Nexmo\Message\Message
     */
    public function send($notifiable, Notification $notification)
    {
        if (! $to = $notifiable->routeNotificationFor('nexmo')) {
            return;
        }

        $message = $notification->toVoice($notifiable);

        if (is_string($message)) {
            $message = new NexmoMessage($message);
        }

        return $this->nexmo->message()->send([
            'type' => $message->type,
            'from' => $message->from ?: $this->from,
            'to' => $to,
            'text' => trim($message->content),
            'client-ref' => $message->client_ref,
        ]);
    }
}

And the error I get is:

[2018-08-17 12:22:10] local.ERROR: Target [Nexmo\Client\Credentials\CredentialsInterface] is not instantiable while building [App\Channels\NexmoCustomSmsChannel, Nexmo\Client]. {"exception":"[object] (Illuminate\Contracts\Container\BindingResolutionException(code: 0): Target [Nexmo\Client\Credentials\CredentialsInterface] is not instantiable while building [App\Channels\NexmoCustomSmsChannel, Nexmo\Client]. at /Users/.../Documents/Web/.../app/vendor/laravel/framework/src/Illuminate/Container/Container.php:918)

Any ideas?

Charrua left a reply on Use ClientRef Value When Sending SMS With Nexmo • 3 days ago

@crnkovic I have also found that file and my understanding is like you said, this method is only sending those parameters, so maybe I need to duplicate this channel as you said and add the client-ref parameter and test.

Maybe this has an easiest way but I cant find any on the web...

Charrua left a reply on Use ClientRef Value When Sending SMS With Nexmo • 3 days ago

Yes I understand that, but I'm looking for a way to do it inside the notification (I'm also listening to some events)

Something like return (new NexmoMessage)->content('text')->clientRef('25');

Charrua started a new conversation Use ClientRef Value When Sending SMS With Nexmo • 3 days ago

Hello, I'm using SMS notification alerts using Nexmo. Searching their API I can see a custom information field that I can use for sending additional information attached to the SMS, this is the client-ref.

You can see it here 'https://developer.nexmo.com/api/sms#send-an-sms' under 'Request body'

This is my notification code:

    /**
         * Get the Nexmo / SMS representation of the notification.
         *
         * @param  mixed  $notifiable
         * @return NexmoMessage
         */
        public function toNexmo($notifiable)    {
            
    return (new NexmoMessage)->content('Congratulations! You have an appt with .... Please text C to CONFIRM.');

        }

Any ideas in how to send also the client-ref parameter?

13th August, 2018

Charrua left a reply on Trigger Notification On Bulk Insert • 1 week ago

@wilburpowery unfortunately ModelName::create($array-of-data) only creates one at a time, remember I need to create a bulk insert. And ModelName::insert($array-of-data) doesn't fire any events:

Model doesn't have an insert method. Calling Model::insert results in a call to Builder::insert through the __call() magic method.

As I need to insert a maximum of 20 bulk records, I ended up by doing:

foreach ($array-of-data as $item){
    $appointment = \App\GoalAppointment::create($item);
    $appointment->notify(new AppNew($appointment));
}

10th August, 2018

Charrua left a reply on Trigger Notification On Bulk Insert • 1 week ago

@wilburpowery great but instead to use an event, can I fire the notification directly from that method?

For example:

public static function boot()
{
    parent::boot();
    
    static::created(function ($appointment) {
        $appointment->notify(new AppIntroNew($appointment));
    })
}

@Cronix I understand that using DB query builder does not fire any model events. I need to create in some way a bulk insert, lets say 100 records... Why would be the Eloquent way? I have found some information on using ModelName::insert($array);, this would be the Eloquent way? and this will trigger the create method that @wilburpowery refers to? Or this will trigger the event and therefore I need to create the listener with the notification fire?

Thank you both.

9th August, 2018

Charrua started a new conversation Trigger Notification On Bulk Insert • 1 week ago

Hi, I'm actually saving into the database appointments by inserting them in bulk.

DB::table('goals_appointments')->insert( $appointments_array );

Is there a way to trigger a notification to each appointment inserted?

30th July, 2018

Charrua left a reply on Limit Queued Notification Tries • 3 weeks ago

maybe I found a easiest solution but is for all jobs. I'm running php artisan queue:work --tries=1and this will do the job, for now...

Thank you @lostdreamer_nl for your help.

Charrua left a reply on Limit Queued Notification Tries • 3 weeks ago

Hey @lostdreamer_nl thank you for that piece of code! seems logic. But I'm wondering if there is an easiest way to accomplish this, maybe pass in some other way the $tries value to Illuminate\Mail\SendQueuedMailable class inside the notification class... I have to do this to SMS notifications and so on.. So I'm looking for an easiest way (if is one)

27th July, 2018

Charrua left a reply on Limit Queued Notification Tries • 3 weeks ago

I have added that public method but no luck. This is my notification:

class AppIntroCurrentDay extends Notification implements ShouldQueue
{
    use Queueable;

    private $appointment;

    public function maxTries()
    {
        return 5;
    }


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


    /**
     * 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->appointment))->to($this->appointment->email);
    }
    
}

And the job that is created in the jobs table: As you can see there is a "maxTries":null,

{"displayName":"App\Notifications\Appointments\AppIntroCurrentDay","job":"Illuminate\Queue\[email protected]","maxTries":null,"timeout":null,"timeoutAt":null,"data":{"commandName":"Illuminate\Notifications\SendQueuedNotifications","command":"O:48:\"Illuminate\Notifications\SendQueuedNotifications\":9:{s:11:\"notifiables\";O:45:\"Illuminate\Contracts\Database\ModelIdentifier\":3:{s:5:\"class\";s:15:\"App\Appointment\";s:2:\"id\";i:866;s:10:\"connection\";s:5:\"mysql\";}s:12:\"notification\";O:49:\"App\Notifications\Appointments\AppIntroCurrentDay\":9:{s:62:\"\u0000App\Notifications\Appointments\AppIntroCurrentDay\u0000appointment\";O:45:\"Illuminate\Contracts\Database\ModelIdentifier\":3:{s:5:\"class\";s:15:\"App\Appointment\";s:2:\"id\";i:866;s:10:\"connection\";s:5:\"mysql\";}s:2:\"id\";s:36:\"26b0504d-bb22-4098-a8ec-80d65b09bbcc\";s:10:\"connection\";N;s:5:\"queue\";N;s:15:\"chainConnection\";N;s:10:\"chainQueue\";N;s:5:\"delay\";N;s:7:\"chained\";a:0:{}s:6:\"\u0000*\u0000job\";N;}s:8:\"channels\";a:1:{i:0;s:5:\"nexmo\";}s:10:\"connection\";N;s:5:\"queue\";N;s:15:\"chainConnection\";N;s:10:\"chainQueue\";N;s:5:\"delay\";N;s:7:\"chained\";a:0:{}}"}}

Charrua started a new conversation Limit Queued Notification Tries • 3 weeks ago

I want to define a limit to try each queued notifications. For example when writing a job class, I use $tries to define maxTries for that queued job, but I don't know how to implement this using queued notifications.

Any ideas?

25th July, 2018

Charrua started a new conversation Get Nexmo SMS Notification API Response • 3 weeks ago

Hello, I'm using nexmo SMS notifications and wanted to get the nexmo API response when I send an SMS to get the ID (of the message) and then store it with some model ID for example.

The main purpose is then to get the nexmo delivery status of the message and assign it to that model also...

In my notification class I use:

public function via($notifiable)
    {
        return ['mail', 'nexmo'];
    }

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



    /**
     * Get the Nexmo / SMS representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return NexmoMessage
     */
    public function toNexmo($notifiable)
    {
        return (new NexmoMessage)
                    ->content('Test SMS');
    }

10th July, 2018

Charrua left a reply on How To Add Custom Headers To Notification Emails? • 1 month ago

Hello @squibby I have the same problem, I want to send notifications and attach a custom header with model id, how do you solve this? I have my code for mail notification but I cant find a way to attach the header.

public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting('Hello ' . $this->appointment->customer)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

9th July, 2018

Charrua started a new conversation Custom Headers On Email Notifications • 1 month ago

Hey I wanted to set custom header with model id for example in my emails to later store the maligun response through webhooks.

I have tried many solutions found on the web but none suits my needs.

A solution I have tried is: https://stackoverflow.com/a/43653673/7274497 but this attaches a custom header to any of the emails sent through laravel and not only for specific notifications (that is what I need).

I have also investigate MailMessageand SimpleMessageclasses that are present on the notification class but I cant find a way to attach custom headers.

public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting('Hello ' . $this->appointment->customer)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

Any ideas?

Charrua left a reply on Model Notes (like Activity Log) • 1 month ago

Great answer @Jarrid, initially I was thinking in something like this but the downside was that I thought when cleaning the log it will clean all logs, but investigating the code I have found that we can clean up a particular log instead of all logs... That's not in documentation.

protected $signature = 'activitylog:clean
                            {log? : (optional) The log name that will be cleaned.}';

So I will be using this Laravel package for my model notes.

6th July, 2018

Charrua started a new conversation Model Notes (like Activity Log) • 1 month ago

Hi, I'm looking for integrating some sort of "notes" on some models. Let's say we have a school with members associated, I want to attach to each member some events that are fired automatically like notifications.

So each member will have their info and some notes, notes that are automatically inserted after a notification is sent. It will be like Spatie's https://github.com/spatie/laravel-activitylog but for other models instead of users.

I'm already using this package for logging user activity but now I want something like this to add "notes" to other models. Any ideas?

Thank you.

14th June, 2018

Charrua left a reply on View Composer Only To Users, Not Admin Role • 2 months ago

Great answer @mushood thank you

12th June, 2018

Charrua left a reply on View Composer Only To Users, Not Admin Role • 2 months ago

Hey @mushood, that's right, if is the admin, I don't want to trigger the eloquent query.

I have access to auth()->user() yes, and can check the member role as auth()->user()->role

If I don't place the conditional on the constructor, where do you think it would be?

Charrua started a new conversation View Composer Only To Users, Not Admin Role • 2 months ago

Hello, I've followed Laravel's https://laravel.com/docs/5.6/views#view-composersto create data available in all views but I want this data only available to certain user roles, not for admin roles.

Where do you think I can include this condition?

My view composer class looks like this:

<?php

namespace App\Http\ViewComposers;

use Illuminate\View\View;
use Carbon\Carbon;

class AppointmentResultComposer
{

    protected $appointments;

    public function __construct()
    {
        $today = new Carbon();
        $date = $today->subMonths(1);

        $this->appointments = \App\Appointment::with('school', 'reason')->where('date', '>=', $date)->get();;
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('appointments_unresolved', $this->appointments);
    }
}

29th May, 2018

Charrua left a reply on Trying To Update Laravel-mix Package • 2 months ago

This was solved updating laravel-mix package and webpack and deleting babelrc. The error was in .babelrc file as this shows:

SyntaxError: Unexpected token } in JSON at position 340
    at JSON.parse (<anonymous>)
    at babelrc (/Users/dubideas/Documents/Web/autonomo-app/app/node_modules/laravel-mix/src/config.js:191:36)

28th May, 2018

Charrua left a reply on Trying To Update Laravel-mix Package • 2 months ago

Hello @topvillas I have already tried that with no success... I need a clean way to update a package or a package with dependencies... What do you think?

27th May, 2018

Charrua started a new conversation Trying To Update Laravel-mix Package • 2 months ago

Hello, I wanted to use mix version() to create versioning of js files, so when I activate this on web pack.mix.js I've found that the hash was created as part of filename /js/app.73108c3c3cf952f6bb6c.jsso I realized that I was using an old version of laravel-mix "laravel-mix": "^0.12.1" My question here is how to update laravel-mix package? I need to update other packages?

I have tried for example to run npm install [email protected]and the output was ´´´ npm WARN deprecated [email protected]: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5

[email protected] postinstall /Users/dubideas/Documents/Web/autonomo-app/app/node_modules/uglifyjs-webpack-plugin node lib/post_install.js

npm WARN [email protected] requires a peer of [email protected]^2.2.0 but none is installed. You must install peer dependencies yourself. npm WARN [email protected] requires a peer of [email protected]^6.0.0 but none is installed. You must install peer dependencies yourself. ´´´ So I tried to compile trough nom run prod but It output errors:

> @ prod /Users/dubideas/Documents/Web/autonomo-app/app
> npm run production


> @ production /Users/dubideas/Documents/Web/autonomo-app/app
> cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

undefined:20
        }]
        ^

SyntaxError: Unexpected token } in JSON at position 340
    at JSON.parse (<anonymous>)
    at babelrc (/Users/dubideas/Documents/Web/autonomo-app/app/node_modules/laravel-mix/src/config.js:191:36)
    at global.tap (/Users/dubideas/Documents/Web/autonomo-app/app/node_modules/laravel-mix/src/helpers.js:10:5)
    at Object.babel (/Users/dubideas/Documents/Web/autonomo-app/app/node_modules/laravel-mix/src/config.js:189:13)
    at module.exports (/Users/dubideas/Documents/Web/autonomo-app/app/node_modules/laravel-mix/src/builder/webpack-rules.js:15:33)
    at WebpackConfig.buildRules (/Users/dubideas/Documents/Web/autonomo-app/app/node_modules/laravel-mix/src/builder/WebpackConfig.js:79:41)
    at WebpackConfig.build (/Users/dubideas/Documents/Web/autonomo-app/app/node_modules/laravel-mix/src/builder/WebpackConfig.js:25:14)
    at Object.<anonymous> (/Users/dubideas/Documents/Web/autonomo-app/app/node_modules/laravel-mix/setup/webpack.config.js:26:38)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)

15th May, 2018

Charrua left a reply on Laravel Authentication From A Raspberry PI • 3 months ago

Hello @lostdreamer_nl thank you for your answer, I have created a personal access token but there is no way to add the authentication header to chromium being launched by the command line.... Do you know any?

I have tried also to install a chrome extension 'modheader' that adds headers to all requests, but as I'm launching chromium with command line, the request for the url is launched before the extension loads...

Any ideas?

9th May, 2018

Charrua started a new conversation Laravel Authentication From A Raspberry PI • 3 months ago

Hi, I use my raspi to load a laravel dashboard app based on Spatie (https://github.com/spatie/dashboard.spatie.be). For authentication I was using http basic auth, but now chromium has deprecated those authentications...

[Deprecation] Subresource requests whose URLs contain embedded credentials (e.g. `https://user:[email protected]/`) are blocked. See https://www.chromestatus.com/feature/5669008342777856 for more details.

Any ideas on alternative ways for automatic authentication?

25th April, 2018

Charrua left a reply on Queue Worker With Supervisor, Multiple Processes • 3 months ago

Great answer, thank you very much @Cronix

24th April, 2018

Charrua left a reply on Queue Worker With Supervisor, Multiple Processes • 3 months ago

Yes that's the problem, how can I figure the number of processes I need? Do you know any documentation for me to investigate?

Charrua started a new conversation Queue Worker With Supervisor, Multiple Processes • 3 months ago

Hi, I have setup Supervisor on a DigitalOcean's droplet with a Laravel app. Following Laravel documentation I've found that it starts 8 worker processes, can you explain why? I need only one process or I need multiple, my queue work is really small. This is in documentation: ´´´ [program:laravel-worker] process_name=%(program_name)s_%(process_num)02d command=php /home/forge/app.com/artisan queue:work sqs --sleep=3 --tries=3 autostart=true autorestart=true user=forge numprocs=8 redirect_stderr=true stdout_logfile=/home/forge/app.com/worker.log ´´´

24th March, 2018

Charrua left a reply on Vue "import" And "Vue.use" Inside Components • 4 months ago

@rin4ik I'm sorry but your solution is not working. I've found this on VeeValidate docs:

The default behavior for the plugin is to forcibly inject a validator instance for each component, which means each component has its own validator scope, that made sharing error messages between components relatively hard depending on your case.

You may also want to stop all automatic injections, and control when a component gets the ability to validate:

import Vue from 'vue';
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate, { inject: false });

This will make the plugin stop instantiating a new validator for each component instance, excluding the root instance. The errorBag and the fields objects will be also shared along with the validator, they will not be injected if the component does not have a validator instance.

Then the only I need to do inside every component I wanted validation is:

export default {

        $_veeValidate: {
            validator: 'new' // give me a new validator each time.
        },

Charrua left a reply on Vue "import" And "Vue.use" Inside Components • 4 months ago

Confirmed, using Vue.use registers plugins globally

Plugins usually add global-level functionality to Vue. There is no strictly defined scope for a plugin

Vue.use automatically prevents you from using the same plugin more than once, so calling it multiple times on the same plugin will install the plugin only once.


https://vuejs.org/v2/guide/plugins.html#Using-a-Plugin

So, do you think is there any way to make VeeValidate to not apply on every component?

Charrua left a reply on Vue "import" And "Vue.use" Inside Components • 4 months ago

Hi, thank you for answering. I have placed this in each component and deleted it from app.js but is the same

import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);

I think using Vue.use is registering VeeValidate globally no matter where is placed, and is applying validation computed properties to each component, even if the component don't use validation.

Charrua started a new conversation Vue "import" And "Vue.use" Inside Components • 4 months ago

Hi, as I'm new to Vue I have a really important conceptual question.

I'm using Vue in a Laravel app, with many components, each one in a separate file, some of them use vee-validate to validate fields and some others don't use.

My question is, where do place the calls to the validation library? (import and Vue.use)

Now I have them in app.js but this means that other components that don't use validation, inherit some validation error variables... I have to place them inside the components?

My goal is that only the components that need validation use vee-validate.

Thank you.

13th March, 2018

Charrua left a reply on Pass Data Through Job To Mailable View Issue • 5 months ago

As the error shows, I was having an error in a function that was expecting a user, but as the job executes from outside, no user was logged.

Charrua started a new conversation Pass Data Trough Job To Mailable To View Issue • 5 months ago

Hello, I want to accomplish sending a mail when some data is saved. I think about queuing jobs and mailables.

In my store method controller, I dispatch a job, then that jobs handles and send email with a view. My problem is I need to send some data to the view, data would be some eloquent query that I don't have in my store controller. So I have tried many ways to send that data, I know it's through constructors but no clue.

The data I wanted to pass to the view is $candidate_list = \App\GoalAppointment::all()

From the store method I do SendNewGoalEmail::dispatch();

the job is:

namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

use Illuminate\Support\Facades\Mail;
use App\Mail\GoalCreated;

class SendNewGoalEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        

    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        $candidate_list = \App\GoalAppointment::all();

        $email = new GoalCreated($candidate_list);

        Mail::to('[email protected]')->send($email);
    }
}

the mailable is:

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

class GoalCreated extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * The candidate_list instance.
     *
     * @var Order
     */
    public $candidate_list;


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


    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.test');
    }
}

6th March, 2018

Charrua started a new conversation Hide Search Results On Click Outside Search Box • 5 months ago

Hi there, I'm creating an Algolia search with vue-instansearch.

In this moment I show search results in an absolute div after search input. When this input is filled, the results div is showed, but I need to hide that div when the user clicks outside the results div.

For showing the results div, I listen to the query event fired when ais-input is filled and using v-if.

Another thing is that each search result has an add button, I'm searching and adding live members on a list.

this is my component:

<template>

    <div>
    <ais-index index-name="members" :query-parameters="{ filters: 'school_id=2' }">

        <ais-input placeholder="Search members..." v-on:query="isVisible" class="form-control"></ais-input>
            
            <div class="results-box" v-show="queryExists">
                
                <ais-no-results>
                    <template slot-scope="props">
                        No members found for <i>{{ props.query }}</i>.
                   </template>
                </ais-no-results>

                <search-results>
                  <table>
                    <tbody>
                      <tr v-for="result in results" :key="result.objectID">
                        <td>{{ result.name }} {{ result.last }}</td>
                        <td><button v-on:click="addMember(result)">Add</button></td>
                    </tr>
                    </tbody>
                  </table>
                </search-results>

            </div>
        
        </div>
    </div>       

    </ais-index>

    {{ members }}
    
    </div>

</template>


<script>

    export default {

        data() {
            return{
                search: '',
                members : [],
            }
        },

        methods: {
            addMember: function (payload) {
                this.members.push( {member_id:payload.member.id} )
            },

            isVisible: function (payload) {
                this.search =  payload;
            }
        },

        computed: {
            queryExists() {
              return this.search.length > 0;
            },
        }
    
    }

</script>

<style type="text/css">

.results-box{
    position: absolute;
    top: 100%;
    z-index: 100;
    left: 0px;
    right: auto;
    background-color: white;
    width: 100%;
    padding: 20px;
    box-shadow: 0 10px 40px 0 rgba(62, 57, 107, 0.07), 0 2px 9px 0 rgba(62, 57, 107, 0.06);
    overflow-y: auto;
    max-height: 400px;
}    

.results-box table{
    width: 100%;
}

.results-box td{
    border-bottom: 1px grey dotted;
    padding: 5px;
}    
</style>

3rd March, 2018

Charrua started a new conversation Creating Data Object/array For Charts Datasets • 5 months ago

Hello, this time I'm trying to create datasets for rendering a vue charts.js stacked chart. All data will be dynamically loaded. The chart will show attendance by day in X axis and stacked by group in Y axis.

The result I need is something like this:

$datasets = collect([
        ['label' => 'Tigers', 'data' => [1,2,3,4,5,6,7], 'backgroundColor' => 'green'],
        ['label' => 'Juniors', 'data' => [1,2,3,4,5,6,7], 'backgroundColor' => 'red'],
        ['label' => 'Adults', 'data' => [1,2,3,4,5,6,7], 'backgroundColor' => 'blue'],
        ['label' => 'Black Belts', 'data' => [1,2,3,4,5,6,7], 'backgroundColor' => 'black'],
 
    ]);

The data index corresponds to each day.

Data source are two models, Group containing group labels and background colors and Attendance containing attendances for members.

My code approach is really sad, I need to do many queries to get what I want. I know there must be an easier way. For now I have this on my controller (I know is the wrong place). I think I will extract this code to a separate class that will create the output needed.

The problem is that I don't know how to create this class, it has some particular name? classes in charge of generating data objects? How will be structured?

I know that I need to: 1- query groups, add days to each group 2- query attendances, group them by group and by day 3- merge those two collections 4- add those day merged results in the output format needed.

1- query groups, add days to each group

$groups = \App\Group::select('name', 'backgroundColor')
                        ->get()
                        ->keyBy('name')
                        ->map(function ($item, $day) {
                            $item->Monday = 0;
                            $item->Tuesday = 0;
                            $item->Wednesday = 0;
                            $item->Thursday = 0;
                            $item->Friday = 0;
                            $item->Saturday = 0;
                            $item->Sunday = 0;
                            return $item->toArray();
                        })
2- query attendances, group them by group and by day

$attendances = \App\Attendance::with(['group'])
                        ->select('group_id', DB::raw('DAYNAME(scan_date) as day_name'), DB::raw('count(group_id) as group_total'))
                        ->groupBy('day_name', 'group_id')
                        ->get()
                        ->map(function ($item, $key) { //add group name
                               $item->group_name = $item->group['name'];
                               return $item;
                        })
                        ->groupBy(['group_name'])
                        ->map(function ($items, $group_name) {
                            return $items->pluck('group_total', 'day_name')->toArray();
                        });
3- merge those two collections

$merged_results = $group->map(function ($item, $key) use ($attendances) {
                            if (isset($attendance_group[$key])){
                                $item = array_merge($item, $attendance_group[$key]);
                            }
                            return $item;
                        });
4- add those day merged results in the output format needed.

$datasets = \App\Group::select('name as label', 'backgroundColor')
                        ->get()
                        ->keyBy('label')
                        ->map(function ($item, $key) use ($groups){
                            $data = array_except($groups[$key], ['name']);
                            $item->data = array_flatten($data);
                            return $item;
                        })
                        ->values()
                        ->toArray();

Any ideas on how to study this or refactor?

1st March, 2018

Charrua left a reply on Eloquent Relationship Query, Sum(), Group, Count(). • 5 months ago

Thank you for your help @bobbybouwmann @jlrdw I ended up studying both eloquent and the query builder.

I ended up with this result:

Collection {#418 ▼
  #items: array:7 [▼
    2 => Collection {#425 ▼
      #items: array:11 [▼
        "cash-out" => "12310.06"
        "merchandise" => "12197.00"
        "new" => "25724.05"
        "other" => "7918.62"
        "pending" => "4239.10"
        "pre-paid-test" => "2453.00"
        "private-class" => "594.30"
        "renewal" => "15393.86"
        "special-activity" => "8546.00"
        "testing" => "10336.00"
        "upgrade" => "8880.00"
      ]
    }
    3 => Collection {#424 ▼
      #items: array:11 [▼
        "after-school" => "1185.00"
        "cash-out" => "7693.80"
        "merchandise" => "15236.50"
        "new" => "10555.00"
        "other" => "5714.93"
        "pre-paid-test" => "2370.00"
        "private-class" => "180.00"
        "renewal" => "4228.60"
        "special-activity" => "565.00"
        "testing" => "8280.00"
        "upgrade" => "6638.66"
      ]
    }
    4 => Collection {#423 ▶}
    6 => Collection {#422 ▶}
    7 => Collection {#421 ▶}
    8 => Collection {#420 ▶}
    9 => Collection {#419 ▶}
  ]
}

From this query:

$transactions = \App\Transaction::withoutGlobalScope(SchoolScope::class)
    ->has('school')
    ->select('school_id', 'reason_id', DB::raw('sum(paid) as total'), 'name as reason_name')
    ->join('transaction_types', 'transaction_types.id', '=', 'transactions.reason_id')
    ->whereBetween('entry_date', array($this->start, $this->end))
    ->groupBy(['school_id', 'reason_name'])
    ->get()
    ->groupBy(['school_id'])
    ->map(function ($item, $key) {
        return $item->pluck('total', 'reason_name'); 
    });

26th February, 2018

Charrua started a new conversation Eloquent Relationship Query, Sum(), Group, Count(). • 5 months ago

Hi everyone, let's say we have three models, schools, transactions, transaction_categories.

my database is:

schools table: id, name transactions table: id, school_id, category_id, amount transaction_categories table: id, name

In transaction categories I have one, two, three, four. In transactions, transactions associated with school.

I need to group transactions by category_id and then sum. The output I need is index (school id) and then all categories.

    1 => {
        "one" : 450,
        "two" : 1000,
        "three" : 450,
    },
    2 => {
        "one" : 450,
        "two" : 1000,
        "three" : 450,
    },
    3 => {
        "one" : 450,
        "two" : 1000,
        "three" : 450,
    },
]```

Any ideas? I have tried fr hours with no success.

22nd February, 2018

Charrua left a reply on Insert Array To Object Data Property • 5 months ago

Solved by adding products as array in laravel model, before sending it to javascript, so now each member data is initialized with a products array.

Charrua started a new conversation Insert Array To Data Property • 5 months ago

Hello, I have my Vue data populated with a Laravel Model using https://github.com/laracasts/PHP-Vars-To-Js-Transformer. I need to add those checkboxes to each member, for example when initializing members, I have name, id for each member.

That translates to

members:[
                {name: peter, id: 2},
        {name: john, id: 3},
        {name: marcus, id: 4},
],

When I fill some inputs, new data is associated with each member, resulting for example in:

members:[
                {name: peter, id: 2, date: "2018-05-06"},
        {name: john, id: 3, notes: "this is a note"},
        {name: marcus, id: 4},
],

But now I'm trying to add some checkboxes to each member, listing products. The result I need is:

members:[
                {name: peter, id: 2, date: "2018-05-06", products:[1,2,3]},
        {name: john, id: 3, notes: "this is a note", products:[3,2]},
        {name: marcus, id: 4},
],

But I cant get this to work, with my actual component this is not working.

my component is:

<template>
    <form>

        <div class="row" v-for="(member, index) in members" >
            <div class="col-sm-3">

                {{ member.name }} {{ member.last }}

            </div>
            <div class="col-sm-3">
                <input type="checkbox" id="jack" value="Jack" v-model="member.products">
                <label for="jack">Jack</label>
                <input type="checkbox" id="john" value="John" v-model="member.products">
                <label for="john">John</label>
                <input type="checkbox" id="mike" value="Mike" v-model="member.products">
                <label for="mike">Mike</label>
            </div>

            <div class="col-sm-3">
                <input type="text" :name="member.id" v-model="member.date">
            </div>

            <div class="col-sm-3">
                <input type="text" :name="member.id" v-model="member.notes">
            </div>

        </div>
        <input type="submit" value="Submit" class="btn btn-primary">

    </form>
</template>

<script>

let members = window.members_model;

export default {
        data() {
            return{
                members,

            }
        }
}
</script>

Any ideas?

13th February, 2018

Charrua left a reply on Local Scope Based On User Role • 6 months ago

@aardalich thank you for your answer, and yes this is a tenant app (I don't even know how to call it, but yes, this is the correct way) I have listen and seen the resources that you quote, really great!

I ended creating a global scope called SchoolScope, and applied it to models like transactions, members, etc. In that SchoolScope I have a conditional to know if the user has admin role.

public function apply(Builder $builder, Model $model)
    {

        if (auth()->user()->isAdmin()) {
            
            $builder->where('school_id', auth()->user()->school_id);
            
        }

    }

Like this, for example in members view, if I'm adminI can list all school's members, but if I log in with a particular school user, I can list only the school members of that school.

Charrua left a reply on Local Scope Based On User Role • 6 months ago

Hello @skliche, thank you for answering, the hardcoded school_idwas for the example, I have there Auth::user()->school_id. I understand your solution but I need to place this conditional in all my local scopes (transactions, members, etc..) maybe I'm not solving the problem in the best way and there is some approach that don't use local scopes... I'm trying to think other way.

The ideal would be to create this conditional in some file once, and when a user for school_id = 5 is logged, he will only see his members, transactions, etc. When an admin is logged in he can see everything. Any ideas?

12th February, 2018

Charrua started a new conversation Local Scope Based On User Role • 6 months ago

Hello, I 'm working on a school administration app that manages about 7 schools. Each school has a user that can access his own member's list as well as transactions using a local scope defined in the Model. Then I have an administrator user, the question is, how can I query the same route, but with no local scope, based on user role? In other words, I would like the admin user to see all school members listed.

My transaction model local scope

/**
     * Scope a query to only include transactions for school id.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeSchool($query)
    {
        return $query->where('school_id', 2);
    }

My Transactioncontroller index method ( I have some search filters ):

$transactions = \App\Transaction::->orderBy('id', 'desc')
            ->filter($filters)
            ->school()
            ->paginate(30);

AuthServiceProvider gate for admin:

Gate::define('manage', function ($user) {
            
            return $user->role == 'admin';

        });

8th February, 2018

Charrua left a reply on Don't Show Results From Soft Deleted Relation Model • 6 months ago

Thank you both!!

Charrua left a reply on Don't Show Results From Soft Deleted Relation Model • 6 months ago

Great answer @tykus, thank you!! Is this in documentation? I cant find it...

Charrua started a new conversation Don't Show Results From Soft Deleted Relation Model • 6 months ago

Hello, I have my School model with schools, and then my Member model. Suppose we have 3 schools active and 1 soft deleted, and members from that schools.

How can I list all members but not the ones that are from the deleted school?

I was thinking in some local scope in my Member model, but I can't figure it out.

Any ideas? Thanks.

11th November, 2017

Charrua left a reply on Laravel And Bulk Email Services Workflow • 9 months ago

Hello Yamen thank you for replying, I have already read the docs but my question is not about the mail function in Laravel. It’s more like the workflow for bulk email and managing lists, subscribers, sync, etc...

Edit Your Profile
Update

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