kakallatt

kakallatt

Member Since 4 Years Ago

Experience Points
14,930
Total
Experience

70 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
254
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 3
14,930 XP
04 Aug
1 month ago

kakallatt started a new conversation Where Is Put Service Code In Laravel Project?

I am building an app using Laravel, and I use Google_Service_Drive as a service to read a spreadsheet on Google Drive.

Currently, I am adding my service register in the register function of AppServiceProvider class.

$this->app->singleton('keyword_tracker', function ($app) {
            $client = new Google_Client();

            putenv('GOOGLE_APPLICATION_CREDENTIALS=' . config('keywords.credentials'));

            $client->useApplicationDefaultCredentials();
            $client->addScope(Google_Service_Drive::DRIVE);

            $driveService = new Google_Service_Drive($client);

            return $driveService;
        });

And I am adding all logic code in a repository, something like that:

class KeywordRepository implements KeywordRepositoryInterface {

    /**
     * Read keywords from google sheet.
     *
     * @return mixed
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     * @throws \League\Csv\Exception
     */
    public function readKeywords()
    {
        $driveService = app()->make('keyword_tracker');

        $response = $driveService->files->export(config('keywords.fileId'), 'text/csv', array(
            'alt' => 'media'));
        $content = $response->getBody()->getContents();

        $csv = Reader::createFromString($content, 'r');
        $csv->setHeaderOffset(0);

        return $csv->getRecords();
    }
}

Is that the best way to organize my code? Because I just feel my code is bulky. Are there any better ideas in this case? Thank you!

24 Jun
2 months ago

kakallatt started a new conversation BelongsTo Field Has Error When Using With $request->viaResource

  • Laravel Version: 5.8
  • Nova Version: 2.0.5
  • PHP Version: 7.3
  • Operating System and Version: MAC OS 10.14.4
  • Browser type and version: Google Chrome 75.0.3770.100

Description:

I have an application allows creating a task. A task belongs to a campaign.

I have a creating button in campaign detail page, if user click that button, then the URL will be like this: http://demo.test/nova/resources/tasks/new?viaResource=campaigns&viaResourceId=1&viaRelationship=.

As you can see, I added the resource id, so I can use them when creating a task. Something like that:

$campaign = Campaign::find($request->viaResourceId);
...
Select::make('Campaign', 'campaign_id')
                ->options([$campaign->id => $campaign->name])
                ->displayUsingLabels()
                ->withMeta(['value' => $campaign->id])
                ->hideWhenUpdating()
                ->readonly(true),

That code works unless I use a BelongsTo field for another relationship (in this case is task group). It seems the BelongsTo field made another request, and it didn't attach the viaResourceId in the URL so I coud not access my campaign variable. For example, $campaign->id -> I got the error: Trying to get property 'id' of non-object

17 Jun
3 months ago

kakallatt started a new conversation Spatie Crawler Just Loads Forever

https://github.com/spatie/crawler

I have a crawl observer like below:

<?php

namespace App\Observers;

use DOMDocument;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
use Spatie\Crawler\CrawlObserver;

class PageCrawlObserver extends CrawlObserver
{
    private $pages =[];

    public function willCrawl(UriInterface $uri) {
        echo "Now crawling: " . (string) $uri . PHP_EOL;
    }

    /**
     * Called when the crawler has crawled the given url successfully.
     *
     * @param \Psr\Http\Message\UriInterface $url
     * @param \Psr\Http\Message\ResponseInterface $response
     * @param \Psr\Http\Message\UriInterface|null $foundOnUrl
     */
    public function crawled(UriInterface $url, ResponseInterface $response, ?UriInterface $foundOnUrl = null)
    {
        $path = $url->getPath();
        $doc = new DOMDocument();
        @$doc->loadHTML($response->getBody());
        $title = $doc->getElementsByTagName("title")[0]->nodeValue;

        $this->pages[] = [
            'path'=>$path,
            'title'=> $title
        ];

        dd($this->pages);

        exit;
    }

    /**
     * Called when the crawler had a problem crawling the given url.
     *
     * @param \Psr\Http\Message\UriInterface $url
     * @param \GuzzleHttp\Exception\RequestException $requestException
     * @param \Psr\Http\Message\UriInterface|null $foundOnUrl
     */
    public function crawlFailed(UriInterface $url, RequestException $requestException, ?UriInterface $foundOnUrl = null)
    {
        echo 'failed';
    }

    public function finishedCrawling()
    {
        echo 'crawled ' . count($this->pages) . ' urls' . PHP_EOL;
        foreach ($this->pages as $page){
            echo sprintf("Url  path: %s Page title: %s%s", $page['path'], $page['title'], PHP_EOL);
        }
    }
}

That code works! But I have to put the exit command at the end of crawled function. Otherwise, It just loads forever until it got a timeout message. I tried to increments PHP execution time, but it just loads until that time got reached and show the timeout error.

I need to run the finishedCrawling function so I don't want to put the exit function like the above code. Any ideas for that? Thank you!

14 Jun
3 months ago
13 Jun
3 months ago

kakallatt started a new conversation How To Config Nginx To Server Static Html Website

When I created a site in Forge panel I already selected Static HTML, but the settings seems aren't difference with PHP project's settings.

And the server cannot read my CSS files. Everytime I access the CSS files, it will print the phpinfo();

Any idea about that? Thank you.

23 May
3 months ago

kakallatt started a new conversation Display Relationship Data In Nova Field

I have a code that iterator dynamic fields from the database.

Something like this:

foreach (\App\AttributeGroup::getAllWithAttributes($request->route()->parameter('resourceId')) as $attributeGroup)
{
    $fields = collect($attributeGroup->attributes)->map(function ($attribute) {
        $class = 'Laravel\Nova\Fields\' . ucfirst($attribute->type);

        $field = $class::make($attribute->name, $attribute->code)
            ->fillUsing(function ($request, $model, $requestAttribute) use ($attribute) {
                return function () use ($model, $request, $requestAttribute, $attribute) {
                    $model->attributes()->attach([
                        $attribute->id => ['value' => $request->post($requestAttribute)]
                    ]);
                };
            });

        // Only select dropdown menu has options
        if ($attribute->type == 'select') $field->options($attribute->getOptions());

        return $attribute->setValidation($field);
    })->filter()->all();

    $tabs[ $attributeGroup->name ] = $fields;
}

In that, I was using the fillUsing to save data from each field into an intermediate table.

Below is attribute_product table:

enter image description here

It works when saving data, but it doesn't show the data when I tried to edit a specific product.

How can I display data from an intermediate table (Relationship between Attribute and Product is BelongsToMany)? I have no idea in this case.

enter image description here

22 May
3 months ago

kakallatt left a reply on Laravel Eloquent Filter Product's Attributes

@snapey @bobbybouwmann do you guys have any ideas about that?

kakallatt left a reply on Laravel Eloquent Filter Product's Attributes

@SNAPEY - If you change orWhere to where, it will return an empty array because there is no product that has both attribute_id = 1 and attribute_id = 2.

kakallatt left a reply on Laravel Eloquent Filter Product's Attributes

@BOBBYBOUWMANN - Thanks for your helping, but I already tried that and it didn't work as I expected. The result includes product #3 that has RAM 4GB. My expectation is only 2 products (#1 and #2) because product #3 doesn't have attribute HDD 256GB.

21 May
4 months ago

kakallatt started a new conversation Laravel Eloquent Filter Product's Attributes

I am making a filter function for products. I have 2 models: Product and Attribute (BelongsToMany relationship)

Attributes table:

id      name
-------------
1       RAM
2       HDD

Products table:

id      name
-----------------
1       Product 1
2       Product 2
3       Product 3
4       Product 4

And the pivot table look like:

id      attribute_id            product_id     value
----------------------------------------------------
1       1 (RAM)                 1              8GB
2       2 (HDD)                 1              256GB
3       1 (RAM)                 2              8GB
4       2 (HDD)                 2              256GB
5       1 (RAM)                 3              4GB
6       2 (HDD)                 4              512GB

When filter products, user select RAM => [4GB, 8GB] and HDD => 256GB.

I want to get products that have RAM - 4GB OR RAM - 8GB AND HDD - 256GB. It means product has attributes RAM - 4GB, HDD - 256GB AND RAM - 8GB, HDD - 256GB will be satisfied the filters. Compared to my above database, I will get products with ID 1 and 2 (Product 3 have RAM 4GB but doesn't have HDD 256, so doesn't count).

Here is my code, but it doesn't work as I expected.

$products = Product::whereHas('attributes', function ($query) {
            $query->whereIn('attribute_id', [1, 2]);
            $query->whereIn('value', ['4GB', '8GB', '256GB']);
        })->get();
12 May
4 months ago

kakallatt started a new conversation What Pattern Prefer To Use When Combine Laravel And Vuejs

As I know, there are 2 ways to use Vuejs in view: inline-template and component.

#1. Inline-template

I gonna use the code from series Let's Build A Forum with Laravel and TDD for express my point.

ThreadsController:

public function show($channel, Thread $thread, Trending $trending)
    {
        if (auth()->check()) {
            auth()->user()->read($thread);
        }

        $trending->push($thread);

        $thread->increment('visits');

        return view('threads.show', compact('thread'));
    }

View (threads.show)

@extends('layouts.app')

@section('head')
    <link rel="stylesheet" href="/css/vendor/jquery.atwho.css">
@endsection

@section('content')
    <thread-view :thread="{{ $thread }}" inline-template>
        <div class="container">
            <div class="row">
                <div class="col-md-8" v-cloak>
                    @include ('threads._question')

                    <replies @added="repliesCount++" @removed="repliesCount--"></replies>
                </div>

                <div class="col-md-4">
                    <div class="panel panel-default">
                        <div class="panel-body">
                            <p>
                                This thread was published {{ $thread->created_at->diffForHumans() }} by
                                <a href="#">{{ $thread->creator->name }}</a>, and currently
                                has <span
                                        v-text="repliesCount"></span> {{ str_plural('comment', $thread->replies_count) }}
                                .
                            </p>

                            <p>
                                <subscribe-button :active="{{ json_encode($thread->isSubscribedTo) }}" v-if="signedIn"></subscribe-button>

                                <button class="btn btn-default"
                                        v-if="authorize('isAdmin')"
                                        @click="toggleLock"
                                        v-text="locked ? 'Unlock' : 'Lock'"></button>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </thread-view>
@endsection

And the ThreadView Component doesn't include <template></template> tag.

Taylor still uses the blade as default and just import Vuejs component when needed.

#2. Component: Same above but all the stuff in view will be brought into <template></template> tag.

Which way should I prefer to use in my project? I can't see the advantages and disadvantages of both ways. The only thing I can see, if I use the inline-template, I can take advance of Laravel Collection helper or blade directive (@auth, @guest).

04 May
4 months ago

kakallatt started a new conversation [Vue Warn]: Error In Render: “TypeError: Cannot Read Property 'products' Of Undefined”

I got this error in console tab.

[Vue warn]: Error in render: "TypeError: Cannot read property 'products' of undefined"

My code works normally but I don't know why that error shows up. I think it because the DOM has rendered first then my data was populated after that. Is that true? If yes, how can I fix it?

Here is my component:

<template>
    <main role="main">

        <!--        <breadcrumbs></breadcrumbs>-->

        <slider></slider>
        <bestseller :products="serverData.bestsellerProducts.products"></bestseller>
        <categorized-products></categorized-products>
        <latest :products="serverData.latestProducts.products"></latest>

    </main>
</template>

<script>
    import Slider from './Slider';
    import Bestseller from './Product/Bestseller';
    import Latest from './Product/Latest';
    import CategorizedProducts from './ProductCategory/CategorizedProducts';
    import {mapGetters} from 'vuex';

    export default {
        computed: {
            ...mapGetters({
                serverData: 'getServerData'
            })
        },
        components: {
            Slider,
            Bestseller,
            Latest,
            CategorizedProducts
        }
    }
</script>

<style scoped>

</style>
19 Mar
6 months ago

kakallatt started a new conversation Eager Load On Nova Resource And Model

I have 2 tables: Product and Categories. Should I declare eager load in Nova Resource like this:


// For Product Resource

/**
 * The relationships that should be eager loaded on index queries.
 *
 * @var array
 */
public static $with = ['categories'];

or on model like this:

// For model App\Product

protected $with = ['categories'];

If I do both on resource and model. Will it cause a duplicated query?

18 Mar
6 months ago
17 Mar
6 months ago

kakallatt started a new conversation Excluding RelatableQuery In Edit Form View Of Laravel Nova?

I have 2 resources: Product and Inventory (BelongsToMany relationship)

The pivot table (inventory_product) has an extra field is quantity (Storing quantity of the product in an inventory).

When using BelongToMany field, it works correctly but the dropdown list still shows all the possible options even the ones already attached. Therefore, I use relatableQuery method to exclude attached ones from the query.

public static function relatableQuery(NovaRequest $request, $query)
    {
        // Get the current resource.
        $resourceId = $request->route()->parameter('resourceId');

        // Get the array of product ids that already attached.
        $attachedItems = app(self::$model)->whereHas('inventories', function ($query) use ($resourceId) {
            $query->where('inventory_id', $resourceId);
        })->get()->pluck('id');

        return $query->whereNotIn('id', $attachedItems);
    }

But the problem is when I go to the edit form to adjust the quantity field it doesn't allow me to do that because of the validation. The dropdown menu is empty because above code filtered them. So how can I avoid the above code in edit form view?

I already tried to get the parameter from the NovaRequest, but it didn't work :(

Thank you for your help!!!

15 Mar
6 months ago

kakallatt started a new conversation Pass Data From Nova Resource To FormField

I created a custom Field in Nova and I want to show a list of category in the view and a checkbox will associate with each category.

I already have a recursive array of the category in my resource file but I don't know how to pass it to FormField?

Here is my code:

Category Resource

$resourceId = $request->route()->parameter('resourceId');
$categories = app(self::$model)->where('id', '!=', $resourceId)->orderBy('position', 'ASC')->get()->toTree();

Thank you for your help!!!

01 Nov
10 months ago

kakallatt started a new conversation Laravel Trigger Model Event On Relation Deleting

I have 2 events on 2 models.

User model:

static::deleting(function ($user) {
       
        $user->team()->deletel();
});

Team model:

static::deleting(function ($team) {
        self::transferMembers($team);
});

Expectation: When admin delete a user, the team belongs to that user will be deleted and other users in that team should be transferred to the default team.

Reality: The team was deleted but it didn't trigger the deleting event to transfer members to default team.

Thank you for your helping!

25 Oct
10 months ago

kakallatt left a reply on Maximum Function Nesting Level Of '512' Reached, Aborting!

@Cronin That's work!!! Thank you so much!!!

24 Oct
10 months ago

kakallatt left a reply on Maximum Function Nesting Level Of '512' Reached, Aborting!

@RamjithAp I did 10000 already. It never work because I've created a recursive dependency between team and users. Do you have solution for this case, please help me out. Thank you.

kakallatt left a reply on Maximum Function Nesting Level Of '512' Reached, Aborting!

@RamjithAp Thank you for quick reply, but when I tried to do that, it will turn to this error: Maximum function nesting level of '1000' reached, aborting!

kakallatt started a new conversation Maximum Function Nesting Level Of '512' Reached, Aborting!

I have 2 model: User and Team. - A user belongs to a team. - A team has many users.

And here is my User model.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable {

    use Notifiable, HasRole;

    protected $guarded = [];

    protected $with = ['team', 'role'];

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

    public function team()
    {
        return $this->belongsTo(Team::class);
    }
}

Team model:

class Team extends Model {

    protected $with = ['leader'];

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('membersCount', function ($builder) {
            $builder->withCount('members');
        });
    }

    public function leader()
    {
        return $this->belongsTo(User::class, 'leader_id');
    }

    public function members()
    {
        return $this->hasMany(User::class);
    }
}

When I tried to eager load team in User model by using protected $with = ['team'];, it ends up with a error

Maximum function nesting level of '512' reached, aborting!

Can anyone help me? Thank you!

25 Apr
3 years ago

kakallatt left a reply on Select2 And Vue Directive

May somebody help me, please !!!

23 Apr
3 years ago

kakallatt started a new conversation Select2 And Vue Directive

I am integrating a jQuery select2 plugin by wrapping it inside a custom directive.

    export default {

        data() {
            return {
                selected: null,
                options: []
            }
        },

        ready() {
        this.fetchUsers()
    }

        methods: {
            fetchUsers: function () {
                this.$http({
                    url: '/api/users/get-all',
                    method: 'GET'
                }).then(function (response) {
                    this.$set('options', response.data)
                }, function (response) {
                    // error callback
                });
            }
        },

        directives: {
            select: {
                twoWay: true,
                priority: 1000,

                params: ['options'],

                bind: function () {
                    var self = this;

                    $(this.el)
                            .select2({
                                theme: "bootstrap",
                                closeOnSelect: true,
                                minimumInputLength: 3,
                                data: this.params.options
                            })
                            .on('change', function () {
                                self.set(this.value)
                            })
                },
                update: function (value) {
                    $(this.el).val(value).trigger('change')
                },
                unbind: function () {
                    $(this.el).off().select2('destroy')
                }
            }
        }

    }
<select v-select="selected" :options="options"></select>

I try to get all users and set to options in fetchUsers function, but seem fetchUsers function was executed after select2 directive so the options variable always be empty.

So how can I get all users through ajax (vue-resource) and after that populate to select2?

18 Apr
3 years ago

kakallatt left a reply on Set Value In Computed Properties.

@jimmck I am not really understand. May you give me an example? Thank you.

kakallatt left a reply on Set Value In Computed Properties.

Oh no. I want to convert 3 inputs to time. Like:

Input 1: 012323 -> 01:23:23

Input 2: 102312 -> 10:23:12

Input 3: 070908 -> 07:09:08

kakallatt left a reply on Set Value In Computed Properties.

@ratiw @gocanto Ok. When user enter a number I want to convert to the time, like this: 003040 -> 00:30:40. But I have 3 inputs (array value) so how can I implement the computed properties?

kakallatt left a reply on Set Value In Computed Properties.

May someone help me?

17 Apr
3 years ago

kakallatt started a new conversation Set Value In Computed Properties.

I have 3 inputs like this:

<input type="text" v-model="settings['apple']" />
<input type="text" v-model="settings['banana']" />
<input type="text" v-model="settings['orange']" />

When a user enter value for a input I want to get the value which user entered to process value and update new value. I am using computed properties to process value:

        computed: {
            settings: {
                set: function (newValue) {
                    var parts = newValue.match(/[\s\S]{1,2}/g) || [];

           // Set new value ...
                }
            }
        },

The problem is how can I know which input user entered and set the new value?

15 Apr
3 years ago

kakallatt left a reply on Get Data From Another Component

@tykus_ikus @ZetecVan I see. But how can I call $dispatch() when my input was changed (I get value by v-model).

Thank you very much.

kakallatt started a new conversation Get Data From Another Component

I have 2 components: A and B.

Component A:

    import B from '../components/B.vue';
    
    export default {
    
        components: {
            B
        },
    
        methods: {
            test: function() {
                console.log(B.data().settings);
            }
        }
    }

And component B:

    export default {
    
        data() {
            return {
                setting: '123'
            }
        }
    
    }

When I trigger test method then I get the value is 123. But when I enter new value from an input and trigger test method again I can't get the new value, the value is still 123.

I have no idea about this. Thank you so much !!!.

05 Apr
3 years ago

kakallatt started a new conversation Multiple Services Implementing Same Interface, Switching At Runtime

I'm trying to create multiple services that all implement the same interface/contract, and which service that is used depends on user input. So I can do that in controller to get service that is selected from user.

Service Provider:

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->call([$this, 'registerProductionService']);
    }
    
    /**
     * Produce video depend on user selection.
     *
     * @param Request $request
     */
    public function registerProductionService(Request $request)
    {
        $service = studly_case($request->input('production')) . 'Repository';
    
        if (in_array($service, $this->availableServices))
        {
            $namespace = (new \ReflectionClass(ReportContract::class))->getNamespaceName();
    
            $this->app->bind(ReportContract::class, "{$namespace}\\{$service}");
        }
    }

In controller:

    public function create(ReportContract $report)
    {
        $report->create();
    }

But when I want to call create() method from queue, I can't get data from Request class. It means I can't get service that is selected from user? So how can I do that?

04 Apr
3 years ago

kakallatt left a reply on Multiple Services Implementing Same Interface, Switching At Runtime

@JarekTkaczyk In Controller you can use $request->input() to get data but if I use queue I can't use $request->input() so how can I get the class name?

01 Apr
3 years ago

kakallatt left a reply on Trigger Event When A File Is Updated

@infernobass7 So should I use setInterval so poll every few seconds?

kakallatt left a reply on Broadcasting And Queues

@bobbybouwmann It seem the event is fired but the notification doesn't not pusher when a job is processed. It wait for all jobs are processed and push all once time.

kakallatt started a new conversation Trigger Event When A File Is Updated

I am using the ffmpeg library for processing the videos. I have a progress bar to show the percent of the processing video. When ffmpeg run it create a log file and update the content to write the duration, percentage, ...

And when this file is updated how can I trigger a function in vue.js to get the information in this file? Thank you for your help.

kakallatt left a reply on Broadcasting And Queues

@bobbybouwmann May you help me, please !!!

31 Mar
3 years ago

kakallatt left a reply on Broadcasting And Queues

@bobbybouwmann In broadcast method, I return the channel name as array.

/**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return ['test'];
    }

And this is my Listener

class PushNotificationToUser
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  VideoHasProcessed  $event
     * @return void
     */
    public function handle(VideoHasProcessed $event)
    {
        $message = 'The video' . $event->name . ' has processed. Check it out!!!';
    }
}

kakallatt left a reply on Broadcasting And Queues

@bobbybouwmann No. It's not fails. I try to sleep for 5 seconds and print out a message. I got a same result.

kakallatt left a reply on Broadcasting And Queues

@bobbybouwmann I just updated my code in above.

kakallatt left a reply on Broadcasting And Queues

@bobby I add 10videos to a queue by use a foreach loop, then when a video is processed (background) I fired a event. Even when I add 1 video into queue and the first video is processing I add 1 more video, it still doest not push separate notification. When 2 videos is processed 2 notifications is pushed together.

kakallatt left a reply on Broadcasting And Queues

Somebody help me, please !!!!

30 Mar
3 years ago

kakallatt started a new conversation Broadcasting And Queues

I am developing a app to process videos. I try to push 10 videos into a queue. After a video was processed I fired a event like this:

...
$production->render();

event(new VideoHasProcessed(basename($this->video->path)));
...

And I do following this video to push a notification to users (https://laracasts.com/series/whats-new-in-laravel-5-1/episodes/12)

The problem is: I want to push a notification when each video was processed but in fact, after 10 videos was processed the notification was displayed.

This is my script:

<script>
    (function () {
        var pusher = new Pusher(PUSHER_ID, {
            encrypted: true
        });

        var channel = pusher.subscribe('test');

        channel.bind('App\\Events\\VideoHasProcessed', function(data) {
            console.log(data);
        });
    })();
</script>

Update:

Dispatch a job

    foreach ($request->input('files') as $file)
        {
            ...
    
            // Dispatch a job.
            $this->dispatch(new ProduceVideo($video));
    
            ....
        }

And my job class:

public function handle(ProductionRepository $production)
{
    ...

    $production->render();

    event(new VideoHasProcessed(basename($this->video->path)));

    ...
}
28 Mar
3 years ago

kakallatt left a reply on Call A Component From Another Component

@johngun @mehany Thank you so much !!!. It's work :D.

27 Mar
3 years ago

kakallatt left a reply on Call A Component From Another Component

Thank you so much but I don't understand your answer. Simply, I am using veuify and in the main.js I have 2 components:

var Vue = require('vue');

Vue.use(require('vue-resource'));

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#_token').getAttribute('content');

import Explorer from './components/Book.vue';
import Alert from './components/Alert.vue';

new Vue({

    el: 'body',

    components: {Book, Alert}

});

This is my Alert.vue:

<template>
    <div class="Alert Alert--{{ type | capitalize }}"
         v-show="show"
         transition="fade"
    >
        <slot></slot>

        <span class="Alert__close"
              v-show="important"
              @click="show = false"
        >
            x
        </span>
    </div>
</template>

<script>

    export default {
        props: {
            type: { default: 'info' },
            timeout: { default: 3000 },
            important: {
                type: Boolean,
                default: false
            }
        },

        data() {
            return {show: true};
        },

        ready() {
            if (!this.important)
            {
                setTimeout(
                    () => this.show = false,
                        this.timeout
                    )
            }

        }
    }

</script>

<style>
    .Alert {
        padding: 10px;
        position: relative;
    }

    .Alert__close {
        position: absolute;
        top: 10px;
        right: 10px;
        cursor: pointer;
    }

    .Alert--Info {
        background: #e3e3e3;
    }

    .fade-transition {
        transition: opacity 1s ease;
    }

    .fade-leave {
        opacity: 0;
    }
</style>

And in another component (Book.vue), I want to call the alert component by using this code: <alert>A book was created !!!</alert>. But It just showed a origin text: A book was created !!!

// resources/assets/js/components/Book.vue
<template>
    .....
    <alert >A book was created !!!</alert>

    //Create book form
    <form> .... </form>
</template>

kakallatt left a reply on Call A Component From Another Component

@mehany It's not work.

I insert <alert v-ref:alert>A book was created successfully !!!</alert> in Book component like this:

// resources/assets/js/components/Book.vue
<template>
    .....
    <alert v-ref:alert>A book was created successfully !!!</alert>

    //Create book form
    ....
</template>

<script>
    export default {
        methods: {
            submit: function () {
                    this.$http.post('/api/books/add', {
                    data: this.data,
                }).then(function (response) {
                     this.$refs.alert
                }, function (response) {
                });
    }
</script>

kakallatt left a reply on Call A Component From Another Component

@johngun This is my code. I am using vue-resource. I have an alert component, how can I call it after submit successfully.

submit: function () {
    this.$http.post('/api/books/add', {
        data: this.data,
    }).then(function (response) {
        // I want to use Alert component right here to notice to users.
    }, function (response) {
    });
}
26 Mar
3 years ago

kakallatt started a new conversation Call A Component From Another Component

I have an Alert component like in this video: https://laracasts.com/series/learning-vue-step-by-step/episodes/21 And I have another component (Book). When a book was created how can I call Alert component in the success callback function like this:

<alert>A book was created successfully !!!</alert>

I am a newbie in using vue.js. Thank you for your help.

01 Mar
3 years ago

kakallatt left a reply on Delete Running Job On Queue

@bobbybouwmann So your code block will remove all jobs from the queue, right? And how can I determine running job and only remove this one? Thank you so much !!!

27 Feb
3 years ago

kakallatt started a new conversation Delete Running Job On Queue

I am working with Beanstalkd. Sometime, the job takes a long time to process so I want to delete it, how can I do that?

Moreover, how can I remove some jobs which I added into the queue?