GodziLaravel

Member Since 4 Years Ago

Experience Points
31,390
Total
Experience

3,610 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
2
Lessons
Completed
Best Reply Awards
1
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

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

  • Community Pillar

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

Level 7
31,390 XP
Mar
05
1 day ago
Activity icon

Started a new Conversation Javascript , How To Verify If A Property Of An Object Exists Or Not?

Hello ,

to make my question more simple : I will use the console.log();

when I console.log(this.var1); , if this does not exists it will returns undefined so I can use a simple condition like:

if(this.var1 !== undefined) {
// do this  and so that ...
}

But the problem is how to verify the property if it exists or not of an object that also I don't know if it exists or not ?

is there a way to avoid double check like:

if(this.var1 !== undefined && this.var1.proper1 !== undefined) {
// do this  and so that ...
}

Thanks

Mar
03
3 days ago
Activity icon

Started a new Conversation Vue Js : Child Component's CSS Is Overridden By The Parent Tag <h1>

Hello ,

First let me show you the parent component :

(...)
<div class="card-header">
                            <h1>
                                <company-edit :id="companyId" :key="companyId"></company-edit>
                            </h1>
</div>

(...)


<style scoped></style>

As you can see there is no specific styles.

component :

 <div class="form-group row">
        <label class="col-4 col-form-label pr-0" :for="'companyNameI"> Company name in-				 
                 house</label>
     <div class="col">
            <input (...)

<style scoped></style>

The problem is when I put <company-edit> inside <h1></h1> tag all the content of the <company-edit> is overridden by H1 style, and all the form labels are on H1 style!

Is there a way to "scope" the CSS of child component ?

Thanks

Mar
01
5 days ago
Activity icon

Started a new Conversation What's The Best Way To Convert Markdown To Html ?

Hello ,

I use an API that contains a markdown property and I would like to save it in DB as a HTML instead of markdown.

What's the best way to do that ?

Thanks

Feb
25
1 week ago
Activity icon

Started a new Conversation Laravel Validation Problem With Uploaded Image

Hello ,

I upload an image using FormData()(Javascript side) when I try to make a validation it's not working !

        $request->validate([
            'companiesLogos' => 'required|image|size:512',
        ]);

The validation error returns "The companies logos must be an image." even when I upload an image !

When I dd(request()->file('companiesLogos') the result is :

Illuminate\Http\UploadedFile {#1548
  -test: false
  -originalName: "5C51E427-1715-44E6-9B14D9487D7B7F2D_source.jpg"
  -mimeType: "image/jpeg"
  -error: 0
  #hashName: null
  path: "/tmp"
  filename: "phpEwa4h8"
  basename: "phpEwa4h8"
  pathname: "/tmp/phpEwa4h8"
  extension: ""
  realPath: "/tmp/phpEwa4h8"
  aTime: 2021-02-25 14:59:14
  mTime: 2021-02-25 14:59:14
  cTime: 2021-02-25 14:59:14
  inode: 917514
  size: 388750
  perms: 0100600
  owner: 1000
  group: 1000
  type: "file"
  writable: true
  readable: true
  executable: false
  file: true
  dir: false
  link: false
}

Any suggestion?

Activity icon

Started a new Conversation How To Update Specific Filed According To A Condition?

Hello ,

        $company = Company::find($id)
            ->update([
                "company_name" => $request["company_name"],
                "former_company" => $request["former_company"],
                "company_logo" => $imageName,
            ]);

Is it possible to update company_logo only if $imageName is not null ,

how to put this condition inside the ->update() ?

Feb
24
1 week ago
Activity icon

Replied to Is It Possible To Upload A File With Other Data On The Same Request ?

@bugsysha

In fact I thought that formData.append() is just adding to an object . but with the example of @tykus above it's now more clear for me.

thanks

Activity icon

Replied to Is It Possible To Upload A File With Other Data On The Same Request ?

@tykus

With axios.patch it returns an empty result !

but I tried to append the method in formData

            let formData = new FormData();
            formData.append('test', this.companyDetail);
            formData.append('companiesLogos', this.companiesLogos);
            formData.append('_method', 'patch');
            const headers = {
                'Encrypt': 'multipart/form-data',
            }
            axios.post('/api/companies/' + id,
                formData,
                {
                    headers: headers
                }
            );

and the result okay for the file but not for the data:

array:3 [
  "test" => "[object Object]"
  "_method" => "patch"
  "companiesLogos" => Illuminate\Http\UploadedFile {#1548
    -test: false
    -originalName: "cap1.PNG"
    -mimeType: "image/png"
    -error: 0
    #hashName: null
    path: "/tmp"
    filename: "php3QK5RO"
    basename: "php3QK5RO"
    pathname: "/tmp/php3QK5RO"
    extension: ""
    realPath: "/tmp/php3QK5RO"
    aTime: 2021-02-24 17:33:45
    mTime: 2021-02-24 17:33:45
    cTime: 2021-02-24 17:33:45
    inode: 917513
    size: 16735
    perms: 0100600
    owner: 1000
    group: 1000
    type: "file"
    writable: true
    readable: true
    executable: false
    file: true
    dir: false
    link: false
  }
]

As you can see test is just a string ("[object Object]") instead of object with multiple properties !

I verified the header in chrome browser and the encrypt is correct :

Encrypt: multipart/form-data <----------
Host: localhost:3000
Activity icon

Replied to Is It Possible To Upload A File With Other Data On The Same Request ?

@corvs

I try with this but it's not working ! it returns an empty array

let bodyFormData = new FormData();
            bodyFormData.append('userName', 'Fred');
            //bodyFormData.append('image', imageFile);
            axios({
                method: 'patch',
                url: '/api/companies/' + id,
                data: bodyFormData,
                headers: {'Content-Type': 'multipart/form-data' }
            })

Activity icon

Replied to Is It Possible To Upload A File With Other Data On The Same Request ?

@bugsysha

I try to add the header as you can see bellow :

let bodyFormData = new FormData();
            bodyFormData.append('userName', 'Fred');
            //bodyFormData.append('image', imageFile);
            axios({
                method: 'patch',
                url: '/api/companies/' + id,
                data: bodyFormData,
                headers: {'Content-Type': 'multipart/form-data' }
            })

In the update controller : I simply dd($request->all()) but the result is empty array [] instead to see "user_name"=>"Fred"

Activity icon

Started a new Conversation Is It Possible To Upload A File With Other Data On The Same Request ?

I try to upload a file with other fields like name, birth date , ....

the problem is : using Axios I have to use new FormData() and the problem of FormData is it sends data as a string. event with JSON.stringify()

If the sent value is different than String or Blob it will be automatically converted to String

source : https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

My question : How to send a form data (including file) using Axios ?

Activity icon

Started a new Conversation How To Return Null Instead Of Undefined Using .find()

Hello

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found

In this example if there is no results it will returns undefined But is it possible to return Null instead ?

Thanks

Feb
23
1 week ago
Activity icon

Replied to All Properties Of The $request Are A String Type !

@tykus Is that means it's not possible to send a file and data on the same request ?

Activity icon

Started a new Conversation All Properties Of The $request Are A String Type !

Hello ,

I use Axios to send a form to update method :

            let form = new FormData();
            Object.keys(this.companyData).forEach((key) => {
                form.append(key, this.companyData[key])
            });
            form.append('companiesLogos', this.companiesLogos);
            form.append('_method', 'patch');

**************            
console.log(form.get('bic')); <------ here type is null
**************

            axios.post('/api/companies/' + id, form)
                .then((response) => {
                this.$refs.closeModal.click();
                this.companyUpdatedConfirmation();
            }).catch((error)=> {
                console.log(error.response.data.errors)
            })

in the controller : (update method)

    public function update(Request $request, $id)
    {
        dd($request->all());

The result:

array:38 [
  "id" => "704"
  "created_at" => "2021-02-17T11:58:03.000000Z"
  "updated_at" => "2021-02-23T12:23:58.000000Z"
  "name" => "0001 new company"
  "vat_number" => "null"
  "national_identification_number" => "null"

As you can see id should be integer but here it's a string and vat_number is null but here it's a string with the value "null"

in JS side : I did console.log(form.get('bic')); and the result as expected NULL which is correct

also it's not possible to apply the validation : 'vat_number' => 'required', when it's null (string)

Activity icon

Replied to I Can't Receive File From Axios Patch Method

@tykus thanks :

I modified some stuff and this works :

let form = new FormData();
            Object.keys(this.companyData).forEach((key) => {
                form.append(key, this.companyData[key])
            });
            form.append('companiesLogos', this.companiesLogos);
            form.append('_method', 'patch');
            axios.post('/api/companies/' + id, form)
                .then((response) => {
                this.$refs.closeModal.click();
                this.companyUpdatedConfirmation();
            }).catch((error)=> {
                console.log(error.response.data)
            })
Feb
22
1 week ago
Activity icon

Replied to How To Post Using Axios Without Object Key

@tykus Thanks for your answer ,

when I switch to axios.patch . I get this error : The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE."

my route is a resource type :

Route::resource('api/companies', 'CompanyController', [
        'only' => ['index', 'show', 'store', 'update', 'destroy'],
    ]);
Activity icon

Started a new Conversation I Can't Receive File From Axios Patch Method

Hello , I try to upload a file :

 <input v-on:change="onImageChange" type="file" class="custom-file-input" :id="'customFile'+id">
(...)
        updateCompany(id) {
            axios.post('/api/companies/' + id, {
                _method: 'patch',
                company: this.companyData,
                imageAvatar:this.imageAvatar
            }).then((response) => {
                this.$refs.closeModal.click();
                this.companyUpdatedConfirmation();
            })
        },
        onImageChange(e) {
                console.log(e.target.files[0]);
                this.imageAvatar = e.target.files[0];
                console.log(this.imageAvatar);
        }

But, in update controller the result is always empty and when I :

dd($request->hasFile('imageAvatar')); it returns false !

Any suggestion ?

Activity icon

Started a new Conversation How To Post Using Axios Without Object Key

Hello folks,

axios.post('/api/companies/' + id, {
                _method: 'patch',
                company: this.companyData
            })

Actually the companyData is also an object having all properties I need (id, name, date ...)

In fact, to access company name I need always pass by company because it's the root key so in my controller I have to : $request["company"]["name"],

I would like to remove the root key (company) and send the company detail directly .

Feb
18
2 weeks ago
Activity icon

Started a new Conversation How To Add A Specific Condition To The Validation Loop?

Hello ,

This is my validation bellow:

        $request->validate([
            'name' => 'required|unique:segments,name,NULL,id,user_id,'. auth()->id(),
            'segments.*.builder' => 'required|integer',
            'segments.*.value' => 'required',
        ]);

How to add an extra condition to this validation like :

if builder == 'abc' then value should be required AND integer

thanks

Feb
17
2 weeks ago
Activity icon

Replied to How To Use Multiple Arrow When Calling A Class Methods

this one works with me :

class BusinessTypeFetch
{


    private static $params = [];

    public static function setParams($businessTypeCountry, $businessTypeId)
    {
        self::$params = [
            "business_type_id" => $businessTypeId,
            "business_type_country" => $businessTypeCountry
        ];
        return new self;
    }

    public function getBusinessTypeName()
    {
        $param = self::$params["business_type_country"];
        // do something with $param ...
        return (....)

    }
}

Now I can call it like : BusinessTypeFetch::setParams('param1','param2')->getBusinessTypeName();

Feb
16
2 weeks ago
Activity icon

Started a new Conversation How To Use Multiple Arrow When Calling A Class Methods

Hello ,

class BusinessTypeFetch
{
 
    private static  $businessTypeCountry;
    public  $businessTypeName;
    private static $businessTypeId;

      static public function setParam($businessTypeId, $businessTypeCountry) {
        self::$businessTypeId = $businessTypeId;
        self::$businessTypeCountry = $businessTypeCountry;
    }
    public function fetchBusinessTypeName(){
          return "This is your params: ".self::$businessTypeCountry." ".self::$businessTypeCountry;
    }
}

what I'm looking for is to call fetchBusinessTypeName method after setParam

like : BusinessTypeFetch::setParam('995','8787')->fetchBusinessTypeName();

Is it possible ?

Activity icon

Started a new Conversation How To Add Jsx To An Existing Vujs Project ?

Hello ,

I have my vuejs project and I would like to know how to add JSX to it ?

Thanks

Feb
11
3 weeks ago
Activity icon

Started a new Conversation VueJs: Child Component Property Is Not Updated !

Hello ,

I'm using vue-table-2 (server table) and I would like to add a child component in each row :

parent component

        <v-server-table :columns="columns" :options="options"
                        :url="'/api/url"
                        ref="segmentTable"
                        @loading="onTableLoad"
                        @loaded="onTableLoaded">

<span slot="actions" slot-scope="{row}">
                <company-edit
                     :row="row"
                      />
(...)

child component

<template>{{row.id}}</template>
(...)
<script>
export default {
    props: [
        "row"
    ],
(...)

The problem is that the parent component is sending always the same value of row (the first value)

Normally it supposed to send each time a different row value !

Any idea ?

Activity icon

Started a new Conversation How To Change The Order Of Columns Table ?

Hello ,

Is there any specific way to re-order the column of existing table? (not empty table)

Thanks

Feb
09
3 weeks ago
Activity icon

Started a new Conversation How To Update A Column Using Another Table's Column ?

Hello ,

I want to update CompanyAddresses.country_id using countries table, this update is based on CompanyAddresses.country and countries.code match.

CompanyAddresses

| id | country | country_id |
|----|---------|------------|
| 1  | BE      | null       |
| 2  | US      | null       |
| 3  | NL      | null       |

countries

| id | code | name          |
|----|------|---------------|
| 1  | BE   | Belgium       |
| 2  | US   | United States |
| 3  | NL   | Netherlands   |

I have Country and CompanyAddress models

Thanks!

Activity icon

Started a new Conversation Is It Possible To Cast The Country Code ?

Hello ,

the address model output is like :

{
      "id": 23824,
      "type": "primary",
      "line_1": "street 1",
      "city": "Paris",
      "country": "FR",
      "created_at": "2021-02-09T11:07:04.000000Z",
      "updated_at": "2021-02-09T11:07:04.000000Z"
    }

I'm wondering if there is in Laravel a way to convert the country code to the country name, to have something like : "country": "France",?

note

I have a country model and table if needed

Feb
08
3 weeks ago
Activity icon

Started a new Conversation How To Change The Array Key Name And Remove Some Keys ?

Hello,

This is my current array :

 $data = array
    (
        '0' => array
            (
                'no' => 1,
                'id_maquina' => 1,
                'id_transaccion' => 1276316093,
                'ultimo_cambio' => 'asdfsaf',
                'fecha_ultimo_mantenimiento' => 1275804000,
                'mecanico_ultimo_mantenimiento' =>'asdfas',
                'fecha_ultima_reparacion' => 1275804000,
                'mecanico_ultima_reparacion' => 'sadfasf',
                'fecha_siguiente_mantenimiento' => 1275804000,
                'fecha_ultima_falla' => 0,
                'total_fallas' => 0,
            ),

        '1' => array
            (
                'no' => 2,
                'id_maquina' => 2,
                'id_transaccion' => 1276494575,
                'ultimo_cambio' => 'xx',
                'fecha_ultimo_mantenimiento' => 1275372000,
                'mecanico_ultimo_mantenimiento' => 'xx',
                'fecha_ultima_reparacion' => 1275458400,
                'mecanico_ultima_reparacion' => 'xx',
                'fecha_siguiente_mantenimiento' => 1275372000,
                'fecha_ultima_falla' => 0,
                'total_fallas' => 0,
            )
    );

My question is how to change no to number and remove fecha_siguiente_mantenimiento from all rows ?

Thanks

Feb
04
1 month ago
Activity icon

Started a new Conversation How To Convert All Ids From BigInt To UUID

Hello ,

In my current project all Ids are Big integer type, I'm wondering if there is a way to convert them (all tables) to an UUID, and how about the relationships ?

Feb
02
1 month ago
Activity icon

Started a new Conversation Laravel: Need For A Clean Way To Keep Only One Element Of An Array

Hello ,

I'm wondering what's the best way to keep only the id from the array bellow ?

 $result = array:86 [▼
    0 => array:20 [▼
      "id" => "3683b387--sd5f-sd5f-0fa3-bc70-cfa2f21b3ec3"
      "name" => "test"
    ]
    1 => array:20 [▼
      "id" => "3531f356-1d38-0a78-af7c-621b3ec5"
      "name" => "test 2"
      "business_type" => null
      "language" => "nl
    ]
    2 => array:20 [▼
      "id" => "e1asd9f49845-b077-4aad321b3ec4"
      "name" => "test 4"
      "web_url" => "Google"
    ]
    3 => array:20 [▶]
    4 => array:20 [▶]
Jan
29
1 month ago
Activity icon

Started a new Conversation LeftJoin : How To Order By Relation Ship

first let me show you the eloquent request :

        $companies = TeamleaderCompany::select('teamleader_companies.*')
            ->leftjoin('teamleader_company_emails', 'teamleader_companies.id', '=', 'teamleader_company_emails.teamleader_company_id')
            ->leftjoin('teamleader_company_tags',function ($join){
                $join->on('teamleader_companies.id', '=', 'teamleader_company_tags.teamleader_company_id');
            })
            ->leftjoin('teamleader_company_telephones', function ($join){
                $join->on('teamleader_companies.id', '=', 'teamleader_company_telephones.teamleader_company_id');
                $join->where('teamleader_company_telephones.type', 'ilike' , "phone");
            })
            ->groupBy('teamleader_companies.id')

How to order this result by teamleader_company_emails.email ?

Activity icon

Replied to Queue Job Not Working On The Production Server !

To restart queue : php artisan queue:restart

Activity icon

Awarded Best Reply on Allways Updating In DB When It Should Insert

Can you dd() before the 3rd if ?


                dd($values);
                  if (!isset($values['id'])) {
Activity icon

Replied to Allways Updating In DB When It Should Insert

Can you dd() before the 3rd if ?


                dd($values);
                  if (!isset($values['id'])) {
Activity icon

Replied to Queue Job Not Working On The Production Server !

@tykus In fact That was the problem :

Also, did you restart the queue worker on production after your code changed (this may be moot depending on your deployment process).

Now it works !

Activity icon

Replied to Queue Job Not Working On The Production Server !

I think I found it !

on supervisor I add : database --sleep=3 --queue=default to php artisan queue:work

Then :

sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start laravel-worker:*
Activity icon

Started a new Conversation Queue Job Not Working On The Production Server !

Hello ,

In my local sever (Homestead) everything works fine !

But on the prod server when try to run a queue job it's not working at all !

Lets start from the route :

Route::get('test', function () {
    for($currentPage = 1; $currentPage <= 5; $currentPage++){
        $delay = \DB::table('jobs')->count() * 20;
    dispatch(new App\Jobs\ImportCompaniesTeamLeaderJob($currentPage))->delay($delay+1);
    }
});

ImportCompaniesTeamLeaderJob

<?php

namespace App\Jobs;

use App\CustomClass\Teamleader\Sync\CompanySync;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ImportCompaniesTeamLeaderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $page;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $company = new CompanySync();
        $company->addOrUpdate(true, $this->page, 20);
    }
}
public function addOrUpdate($manual = false, $pageNumber = 1, $pageSize = 20)
    {

(...)

 foreach ($companiesTeamleader["data"] as $cKey => $cValue) {
            activity()->log("------UPDATE API page($pageNumber, $pageSize)---------->".$cValue["id"]);
			(...)
		}
	}

on Local server (Homestead) I could see the result of activity()->log("------UPDATE API page($pageNumber, $pageSize)---------->".$cValue["id"]);

------UPDATE API page(1, 20)---------->bc74270c-90d5-0184-9f78-6a384259b4a9
------UPDATE API page(1, 20)---------->4ceb7ef2-ea38-0be4-9c78-be6a42361fe5
(..)

On the prod server

In jobs table I see a related row to this queue and after 20 sec (delay) it disappears which is normal and there is nothing in failed_jobs table which means everything is okay ! but nothing within handle is executed !

Any suggestion ?

Activity icon

Awarded Best Reply on The Route /email/resend Returns : The GET Method Is Not Supported For This Route

This works with me : In fact after the upgrade to Laravel 7 , I think we need to change verify.balde.php

from

  <a href="{{ route('verification.resend') }}">{{ __('click here to request another') }}</a>.

To

<a  onclick="event.preventDefault(); document.getElementById('email-form').submit();">**{{ __('click here to request another') }}</a>.
<form id="email-form" action="{{ route('verification.resend') }}" method="POST" style="display: none;">@csrf</form>

The Get is not supported anymore

Activity icon

Replied to Homestead : Queue Is Not Working !

@tykus

I'm using a database system and I already have job table and failed_jobs table .

What should I add to the .env ?

Activity icon

Replied to Homestead : Queue Is Not Working !

@tykus thanks ,

the only parameter I have in .env is QUEUE_CONNECTION=sync.

in config/queue.php

    'connections' => [

        'sync' => [
            'driver' => 'sync',
        ],

        'database' => [
            'driver' => 'database',
            'table' => 'jobs',
            'queue' => 'default',
            'retry_after' => 90,
        ],
Activity icon

Started a new Conversation Homestead : Queue Is Not Working !

Hello ,

In my local (Homestead laravel 7)

When I run a queue job I don't see anything in php artisan queue:listen

public function handle()
    {
        activity()->log("--------".rand()."--------");
    }

When I check the activity_log table I see the results but whithout delay !

Here how I call the queue job

    for($currentPage = 1; $currentPage <= 5; $currentPage++){
        $delay = \DB::table('jobs')->count() * 20;
    dispatch(new App\Jobs\ImportCompaniesTeamLeaderJob())->delay($delay+1);
    }
Activity icon

Started a new Conversation Queue Job Not Working As Expected !

Hello ,

I created a queue to synchronize my table with a an API :

As you can see this queue is with a parameter $page

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

    protected $page;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $companies = new CompanySync();
        $companies->addOrUpdate(true, $this->page, 50);
    }
}

I created a route to run this :

Route::get('company-update', function () {
        dispatch(new App\Jobs\ImportCompaniesTeamLeaderJob(2))->delay(100);
});

When I call this route then I check the jobs table I see a related row to this queue and after 100 sec (delay) it disappears which is normal and there is nothing in failed_jobs table which means everything is okay !

But : nothing happened.

I tested the method $companies->addOrUpdate(true, $this->page, 50); without queue and it works !

any suggestion ?

Jan
28
1 month ago
Activity icon

Started a new Conversation How To Use A Job Queue With Dynamic Parameter ?

To add items to my table I created a job queue to call the function addOrUpdate(), the mission of this function is to consume the result of a specific API.

In fact this function has one facultative parameter addOrUpdate($pageNumber) to select the page on the API.

I need to create a queue job to fetch all pages from page 1 to 200.

How to inject a dynamic parameter inside the addOrUpdate() bellow to fetche all pages :

$this->companySync->addOrUpdate(1);

$this->companySync->addOrUpdate(2);

$this->companySync->addOrUpdate(3);

$this->companySync->addOrUpdate(4);

(...)

    public function handle()
    {

        $syncRapport = $this->companySync->addOrUpdate();
        
    }