calin.ionut

calin.ionut

Member Since 2 Years Ago

Experience Points 4,950
Experience Level 1

50 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 34
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.

19 Jul
3 days ago

calin.ionut started a new conversation Schedule:run Once A Day (at 00:00)

Hi!

I have set up a cron job on a VPS server to run a schedule task and it seems to not working as I expected. I am running laravel 5.8.

In /etc/crontab i have set the cron:

# Cron tasks for promotions
* * * * * admin cd /var/www/server && php artisan schedule:run >> /dev/null 2>&1

and in the App/Console/Kernel.php

 protected function schedule(Schedule $schedule)
    {
        // Check Product Promotion => 00:00
        $schedule->call(function () {
            $promotion = new StoreSchedule();
            $promotion->checkProductsPromotion();
        })->daily();
    }

the check promotion will check if the product is still in promotion.

ex: if I set a promotion for a product 14-07-2019 to 19-07-2019, when it reach at 00:00 (on the 19-07.2019) the product promotion schould be disabled. The function works if i run outside of the schedule.

I haven`t set correctly the daily() ?

12 Jul
1 week ago

calin.ionut left a reply on Query Builder Search A Json Column

@mstrauss the product model

class Product extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */

    protected $table = 'products';
    protected $primaryKey = 'ProductID';

    protected $casts = [
        'Colors' => 'array',
    ];
}

calin.ionut left a reply on Query Builder Search A Json Column

this seems to work:

$products = $products->whereRaw('JSON_CONTAINS(Colors, \'{"id": "2"}\')');

calin.ionut left a reply on Query Builder Search A Json Column

@mstrauss sure

class ProductColor extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */

    protected $table = 'products_colors';
    protected $primaryKey = 'ColorID';
}

calin.ionut left a reply on Query Builder Search A Json Column

@mstrauss i have tried casting the Colors in the model Products and

$products = $products->whereIn('Colors', [2, 3]);

but nothing.

calin.ionut left a reply on Query Builder Search A Json Column

Could be because the Colors colum is varchar??? But the data inside is json

calin.ionut left a reply on Query Builder Search A Json Column

@nezar i have tried both and not working:

 $products = $products->where('Colors->id', 2);
$products = $products->whereJsonContains('Colors', 2);

calin.ionut left a reply on Query Builder Search A Json Column

yes @saikishore the column from the product is "Colors"

@tray2 if can`t find any solution i will :)

calin.ionut started a new conversation Query Builder Search A Json Column

Hello!

In the product table a have a column Colors where i saved the product colors as a json (the colors id`s)

Example of data saved in a column Colors:

[{"id":"2"},{"id":"4"},{"id":"5"},{"id":"6"}]

The query i want to make:

$products = Product::query();
if(request()->has('color')){
    $color = ProductColor::where('Slug', request('color'))->first();
    $products = $products->where('Colors->"$.id"', $color->ColorID);
}

but does not work (it doesn`t display any product)

I also tried with the JSON_EXTRACT and not working.

$products = $products->where(DB::raw('JSON_EXTRACT(`Colors`, "$.id")'), '=', $color->ColorID);

Wow can i find a value in a json column?

21 Jun
1 month ago

calin.ionut left a reply on How To Emit And Receive Event From A Different Vue Instance ?

i think i fixed :)

On the <basic-table> i don`t need:

 @search-table="inputSearch"

and in the basic-table.js

created() {
        Event.$on('search-table', function(data) {
            console.log(data);
        })
    }

calin.ionut started a new conversation How To Emit And Receive Event From A Different Vue Instance ?

I can`t receive an event from a different vue instance. What i did wrong?

I have the following scenario:

<div id="navbar-top">
    <input type="text" v-model="search" @input="onSearchInput">
</div>
<div id="basic-table">
    <basic-table @search-table="inputSearch"></basic-table>
</div>
<script>
    window.Event = new Vue();
    
    new Vue({
        el: '#navbar-top',
            data: {
                    search: ''
            },
            methods: {
                onSearchTable() {
                    Event.$emit('search-table', this.search);
                }
            }
    });
</script>

<script src="basic-table.js"></script>

the basic-table.js is:

Vue.component('basic-table', {
        template: `<div class="card"> html code </div>`,
    methods: {
        inputSearch() {
                    Event.$on('search-table', function(data) {
                        console.log(data);
                })
            },
    }
});
new Vue({
    el: '#basic-table',
});

How can i receive the event from the first vue instance?

10 Jun
1 month ago

calin.ionut left a reply on Substr Html Content Without The Html Become Corrupt

i found this solution that works for me

 @php $infoData = preg_replace('~>\s+<~', '><', $category->infoData); @endphp
 {!! substr(strip_tags($infoData, '<h2>'), 0, 265)."..." !!}

If anyone have a better solution ... :)

calin.ionut started a new conversation Substr Html Content Without The Html Become Corrupt

Hello,

I want to show a portion of the text from DB in a box but the problem is when substr the html data from the db, the page become corrupt (the html) - and it`s normal to become :) (because of the missing close p or other tags)....

the infoData => is html description

i use in the blade:

 {!! substr($category->infoData, 0, 265)."..." !!}

I know that if i strip the html would be better, like this:

{{ substr(strip_tags($category->infoData), 0, 265)."..." }}

but in the info data i have some tags (h2) that i want to give a proper style in the page and the rest of the text to be plain text.

How can i do this ?

03 May
2 months ago

calin.ionut left a reply on Eloquent Optimizations

and maybe use the raw sql (DB facades) instead of eloquent.

calin.ionut left a reply on Eloquent Optimizations

@tykus Depending on the size of $allOrders

the orders table is now ~ 1600 records. So you are saying that is better to pull each data directly from the DB instead pull of the data and play with the collection.

@jlrdw never heard of getting all

I need to gett all the data (orders, users, etc.) to make some statistics

02 May
2 months ago

calin.ionut started a new conversation Eloquent Optimizations

Hi!

I want to make some optimizations in the laravel backend and i found something ... strange.

Ex:

$allOrders = Order::all();
$canceledOrders = $allOrders->where('status', '=', 3);
$cardPaymentOrders = $allOrders->where('payment', '=', 'card');
....

is more slower then i make a new query to the DB (mysql)

$allOrders = Order::all();
$canceledOrders = Order::where('status', '=', 3)->get();
$cardPaymentOrders = Order::where('payment', '=', 'card')->get()
...

I was thinking that making only one query to the DB and play with the data will be more fast (but it`s not)

Why is more faster making separate query requests to the DB ????

19 Apr
3 months ago

calin.ionut left a reply on Echo Broken Html In View Without Broke The Whole Page

fix it! :)

replace the this code:

{!! \Illuminate\Support\Str::words($post->Content, 30,'....') !!}

with this one:

{{ substr(strip_tags($post->Content), 0, 280) }}

calin.ionut left a reply on Echo Broken Html In View Without Broke The Whole Page

I think the problem is with this line of code:

{!! \Illuminate\Support\Str::words($post->Content, 30,'....') !!}

i use it in the main blog page to show only a portion of the content then on the single page blog i use the code to output the content.

{!! $post->Content !!}

the problem is with the first code in the main blog page

calin.ionut started a new conversation Echo Broken Html In View Without Broke The Whole Page

I have a simple blog and i want to echo the html content in a section of the view (the content is saved in a DB).

The problem is IF the content have broken html (ex: div not close) the whole page is broken.

Somewhere in the view a have:

<div class="post-content mb-20">
      {!! $post->Content !!}
</div>

Is there a way to prevent the whole page to be broken if the content has some missing html tags???

03 Apr
3 months ago

calin.ionut left a reply on Laravel 5.8 Access Denied For User 'root'@'localhost' (using Password: YES)

That`s how i installed the server @maverickchan

I tried to change the password:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root_password';

and i got an error message:

ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

then i uninstall the plugin for password validation:

mysql> uninstall plugin validate_password;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root_password';
mysql> FLUSH PRIVILEGES;

and now it`s working with the new password :)

calin.ionut started a new conversation Laravel 5.8 Access Denied For User 'root'@'localhost' (using Password: YES)

I can`t connect to the db from my laravel 5.8 app. It complains:

production.ERROR: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)

The credentials from .env are correct:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=test_db_db
DB_USERNAME=root
DB_PASSWORD=1234#

The server is running ubuntu 18.04 and mysql 5.7.25

Why is access denied???? If i loggin using:

and give the password (1234#) works for the user root.

31 Jan
5 months ago

calin.ionut left a reply on How To Validate Uniqueness For 2 Columns?

Old try and catch works.

try{
            $productAttribute->AttributeID = $request->AttributeName;
            $productAttribute->ProductID = $request->FKey;
            $productAttribute->Stock = $request->AttributeStock;
            $productAttribute->SKU = $request->AttributeSKU;
            $productAttribute->Price = $request->AttributePrice;
            $productAttribute->save();
        } catch (\Exception $e){
            return response()->json(['error' => true, 'msg' => 'The attribute is allready assigned to this product!']);
        }

Is there other way? :)

calin.ionut started a new conversation How To Validate Uniqueness For 2 Columns?

I am having some issues validating 2 columns that i want them to be unique.

A am having 3 tables: products, attributes and products_attributes.

I want the product to have unique attributes assigned. I don`t want to use any rellations between those tables (hasMany, etc....)

The products_attributes model looks look like this:

Schema::create('products_attributes', function (Blueprint $table) {
            $table->increments('ProductAttributeID'); // the primary key
            $table->integer('AttributeID')->unsigned(); // primary key for attributes table
            $table->integer('ProductID')->unsigned(); // primary key for products table

            $table->integer('Stock');
            $table->string('SKU')->unique();
            $table->decimal('Price', 10,2);
            $table->timestamps();

            $table->unique(['ProductID', 'AttributeID']);
        });

Inserting and updating the data I use the id for this table: ProductAttributeID => when the value is 0 I am adding new data else update the existing data.

The validation and saving the data is this:

// update or save product attribute ?
        if(isset($request->ProductAttributeID) && $request->ProductAttributeID != 0) {
            $productAttribute = AttributeProduct::findOrFail($request->ProductAttributeID);
            $validator = Validator::make($request->all(), [
                'AttributeSKU' => [
                    'required', 'string', 'max:255', Rule::unique('products_attributes', 'SKU')->ignore($productAttribute->ProductAttributeID, 'ProductAttributeID')
                ]
            ]);
            if ($validator->fails()) {
                return response()->json(['error' => true, 'msg' => 'U: The SKU field is required and must be unique!']);
            }            
        } else {
            $productAttribute = new AttributeProduct();
            $validator = Validator::make($request->all(), [
                'AttributeSKU' => 'required|unique:products_attributes,SKU|string|max:255'
            ]);
            if ($validator->fails()) {
                return response()->json(['error' => true, 'msg' => 'N: he SKU field is required and must be unique!']);
            }            
        }

        $validator = Validator::make($request->all(), [            
            'AttributeName' => 'required|numeric',
            'AttributePrice' => 'required|numeric',
            'AttributeStock' => 'required|numeric',
            'FKey' => 'required|numeric'
        ]);
        if($validator->fails()) {
            return response()->json(['error' => true, 'msg' => 'All the fields are required!']);
        }

        // make sure the SKU is unique through products table
        $codeExist = Product::where('Code', $request->AttributeSKU)->first();
        if($codeExist){ return response()->json(['error' => true, 'msg' => 'SKU  allready exist!']); }

        // save or update attribute product
        $productAttribute->AttributeID = $request->AttributeName;
        $productAttribute->ProductID = $request->FKey;
        $productAttribute->Stock = $request->AttributeStock;
        $productAttribute->SKU = $request->AttributeSKU;
        $productAttribute->Price = $request->AttributePrice;
        $productAttribute->save();

How can i validate the uniqueness for ['ProductID', 'AttributeID'] ???

10 Dec
7 months ago

calin.ionut left a reply on How To Run Multiple Task Automatically Using "Task Scheduling"?

@tykus it will not work if create an object from that controller an call the function, like this?

$schedule->call(function () {
   // task #1
   $test = new TestController();
   $test->runTask();
})->daily();

calin.ionut started a new conversation How To Run Multiple Task Automatically Using "Task Scheduling"?

I have some blurs about task scheduling.

I am using a VPS server with a laravel 5.7 app.

I want to run automatically in background multiple tasks (some method's from a controller).

From what I search in the documentation the best for doing this is creating a Task Sheduling (in app/console/Kernel => schedule)

If I understood correclty I have to run the code that needs to be executed automatically from the "handle" function (app/console/Kernel):

$schedule->call(function () {
            // task #1
        })->daily();

$schedule->call(function () {
            // task #2
        })->twiceDaily(1, 13);

then creat a supervisor from linux to run this command automatically

php artisan schedule:run

Am I right?

Is there any other config's that should be made in .env?

07 Dec
7 months ago

calin.ionut left a reply on Dynamic Routes

@sustained .... i think i got it :)

The last route that catch dynamic routes:

Route::get('/{categorySlug}/{filters}', '[email protected]')->where(['filters' => '.*']);

The handle function:

public function handle(Request $request)
        {
        // some logic that determines the slug from request
            
        // test the route /category-1/brand-1/product-2
        if($request->segments()[0] == 'category-1') {
                return \Illuminate\Support\Facades\App::call('\App\Http\Controllers\[email protected]', ['cat_id' => 13]);
            }

            dd($request->segments());

        }

and it call the right controller and pass the argument cat_id

   public function test($cat_id)
    {
        dd($cat_id);
    }

I hope it does not affect speed performance.

06 Dec
7 months ago

calin.ionut left a reply on Dynamic Routes

ok...but how can i pass the params further to the controller responsible for display the category, the product, the brand.

There are 3 Controllers. (CategoryController, ProductController, BrandController).

I was thinking about this DynamicController to handle the routes and point to the right controller.

Ex: if the url is:

/{categorySlug}/{brandSlug}/{productSlug}

the DynamicController will do this:

  1. Search for the categorySlug in db (the first segment will always be the category) - else abort(404)
  2. if the second segment is there (this will always be brandSlug || 'filters' keyword)
  3. if the third is there and 'productSlug' exist in db - then it`s a product url :)
  4. dispatch to [email protected]($productID)
05 Dec
7 months ago

calin.ionut started a new conversation Dynamic Routes

I want to have a Controller (DynamicController) and inside a method that handles all dynamic routes.

public function handle($categorySlug, $filters = null)
    {
        $controller = HomeController::class;
        $action = 'index';

        // just for testing :)
        if ($categorySlug == 'something') {
            $controller = CategoryController::class;
            $action = 'showCategory';
        } else {
            abort(404);
        }

        $container = app();
        $route = $container->make(Route::class);
        $controllerInstance = $container->make($controller);

        return (new ControllerDispatcher($container))->dispatch($route, $controllerInstance, $action);
    }

the route that i defined is the last one in routes:

Route::get('/{categorySlug}/{filters}', '[email protected]')->where(['filters' => '.*']);

How to pass the $filters (or any other parameter) to "showCategory" method from the handle?

i want to create dynamic url's for product, category and brand:

ex:

/{categorySlug}/{brandSlug}/{productSlug}

and for filters:

/{categorySlug}/filters/{filters}

calin.ionut left a reply on Download Pdf File Using Guzzle POST Request

I solved the problem :)

A am using a js function to convert from base64 to blob

function b64toBlob(b64Data, contentType, sliceSize) {
        contentType = contentType || '';
        sliceSize = sliceSize || 512;

        var byteCharacters = atob(b64Data);
        var byteArrays = [];

        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);

            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

        var blob = new Blob(byteArrays, {type: contentType});
        return blob;
    }

the from php:

return response()->json(['error' => false, 'FileContent' => base64_encode($pdf), 'ContentType' => 'application/pdf', 'FileName' => $name ]);

calin.ionut left a reply on Download Pdf File Using Guzzle POST Request

@lostdreamer_nl If i am still using ajax, how can i send the pdf file content through json?

needs to be a blob:

new Blob([response.FileContent]);

I have tried to encode the pdf using base64_encode from php (i don't think it's the same):

return response()->json(['error' => false, 'FileContent' => base64_encode($pdf), 'FileName' => $name ]);

and it's not working.

calin.ionut started a new conversation Download Pdf File Using Guzzle POST Request

How can i download a pdf file from a post request using Guzzle?

I need to send some params to a url and if all it's ok i receive a pdf file. I am using laravel 5.7 for server request and ajax for client request.

What i need tot do:

  1. send some params from client to the laravel server (using post)
  2. the laravel server needs to send some params using POST to another url
  3. get the pdf file returned from step 2 to the client.

The client request with ajax to the laravel server:

$.ajax({
            type: 'POST',
            dataType: 'json',
            url: $(this).attr('data-url'),
            data: {order: $(this).attr('data-order')},
            success: function (response) {
                if(!response.error) {                    
                    swal("", response.msg, "success");
                } else {                    
                    swal("", response.msg, "error");
                }
            }
        });

The server post request on $url for getting the pdf file:

        $client = new Client();
            try{
                $response = $client->post($url,[
                    'form_params' => [
                        'nr' => $nr,
                        'username' => 'myUsername',
                        'client_id' => 'myClientID',
                        'user_pass' => 'myPassword',
                        'language' => 'ro'
                    ]
                ]);
            } catch (Exception $e){
                return response()->json(['error' => true, 'msg' => $e->getMessage() ]);
            }

If a dd the $response from guzzle:

Response {#502
  -reasonPhrase: "OK"
  -statusCode: 200
  -headers: array:6 [
    "Content-Type" => array:1 [
      0 => "application/pdf"
    ]
    "Server" => array:1 [
      0 => "Microsoft-IIS/8.5"
    ]
    "X-Powered-By" => array:2 [
      0 => "PHP/7.0.9"
      1 => "ASP.NET"
    ]
    "Content-Disposition" => array:1 [
      0 => "attachment; filename="2332800120195.pdf""
    ]
    "Date" => array:1 [
      0 => "Wed, 05 Dec 2018 09:58:21 GMT"
    ]
    "Content-Length" => array:1 [
      0 => "47117"
    ]
  ]
  -headerNames: array:6 [
    "content-type" => "Content-Type"
    "server" => "Server"
    "x-powered-by" => "X-Powered-By"
    "content-disposition" => "Content-Disposition"
    "date" => "Date"
    "content-length" => "Content-Length"
  ]
  -protocol: "1.1"
  -stream: Stream {#500
    -stream: stream resource @13
      wrapper_type: "PHP"
      stream_type: "TEMP"
      mode: "w+b"
      unread_bytes: 0
      seekable: true
      uri: "php://temp"
      options: []
    }
    -size: null
    -seekable: true
    -readable: true
    -writable: true
    -uri: "php://temp"
    -customMetadata: []
  }
}

How can i download the file?

05 Nov
8 months ago

calin.ionut left a reply on Queueing A Mail Message Not Working With Queue Database

i forgot to clear the cache :))

php artisan config:cache
php artisan config:clear 

Now it works. It is not necessary the from() method if you have overwritten in .env

MAIL_FROM_NAME=
MAIL_FROM_NAME=

calin.ionut left a reply on Queueing A Mail Message Not Working With Queue Database

even if i set explicit:

return $this->from('[email protected]', 'test app name')

does not work. It shows the email from MAIL_FROM_ADDRESS but not the name

calin.ionut left a reply on Queueing A Mail Message Not Working With Queue Database

i have already set those variables in env. And it should be enough using $this->from:

return $this->from($this->from)
                         ->subject($this->emailSubject)
                        ->view('custom-template')
                        ->with('data', $this->data);

but the name is not displayed.

calin.ionut left a reply on Queueing A Mail Message Not Working With Queue Database

one more thing....

Why is not setting the name for the sender???

In the constructor for the mailable i set the name (MAIL_FROM_NAME)

 $this->emailFrom = array('address' => env('MAIL_FROM_ADDRESS'), 'name' => env('MAIL_FROM_NAME'));

and in the build function:

return $this->from($this->emailFrom['address'], $this->emailFrom['name'])
                        ->subject($this->emailSubject)
                        ->view('custom-template')
                        ->with('data', $this->data);

it is not set the name in from. Why?

calin.ionut left a reply on Queueing A Mail Message Not Working With Queue Database

it works.... thx @D9D9705996

I didn`t know that in laravel 5.7 the QUEUE_DRIVER war renamed to QUEUE_CONNECTION

calin.ionut started a new conversation Queueing A Mail Message Not Working With Queue Database

I want to create a queue (database) for sending the emails and it`s not working.

What i have done:

  1. create a mailable for sending the emails
protected $type;
    protected $data;
    protected $emailFrom;
    protected $emailSubject;

    public function __construct($subject, $type, $data)
    {
        $this->emailFrom = env('MAIL_FROM_ADDRESS');
        $this->emailSubject = $subject;
        $this->type = $type;
        $this->data = $data;
    }

    /**
     * Build the message.
     * Within this method, you may call various methods such as from, subject, view, and attach
     *
     * @return $this
     */
    public function build()
    {
        if($this->type === 'newsletter'){
            return $this->from($this->emailFrom)
                        ->subject($this->emailSubject)
                        ->view('admin.modules.newsletter.template_1.newsletter')
                        ->with('data', $this->data);
        }
    }
  1. create the database queue
php artisan queue:table
php artisan migrate
  1. change the queue driver config (.env)
QUEUE_DRIVER=database
  1. created a job for sending email
php artisan make:job SendEmailJob
protected $to;
    protected $subject;

    protected $type;
    protected $data;

    public function __construct($to, $subject, $type, $data)
    {
        $this->to = $to;
        $this->subject = $subject;
        $this->type = $type;
        $this->data = $data;

    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Mail::to($this->to)->send(new SendEmailMailable($this->subject, $this->type, $this->data));
    }
  1. Restart the server, clear the cache

  2. dispatch the job

$job = (new SendEmailJob($NewsletterEmail, $NewsletterSubject,'newsletter', $data))->delay(Carbon::now()->addSeconds(10));
        dispatch($job);

The problem is when i dispatch the job. The email is sending ... but is not using the queue database (i have to wait until it sends).

In the jobs table i don`t see anything related to the dispatch.

What could be the problem?

23 Oct
8 months ago

calin.ionut left a reply on Create The Relationship One To Many

thx @Cronix ... i don't know why i put belongToMany...maybe I am so tired :)

i have changed the models:

// a property belongs to a filter
    public function group(){
        return $this->belongsTo(FilterGroup::class, 'FilterGroupID','FilterGroupID');
    }
// a filter has many properties
    public function properties(){
        return $this->hasMany(FilterProp::class,'FilterGroupID','FilterGroupID');
    }

and now when calling the properties - property - for a group, it shows all the filter properties for the filter group :)

calin.ionut started a new conversation Create The Relationship One To Many

I have two tables (one to many relationship) and i want to configure the models .... but it's not working as it should.

The first table is filter_group:

 Schema::create('filter_group', function (Blueprint $table) {
            $table->increments('FilterGroupID');
            $table->string('Name')->unique();
            $table->timestamps();
        });

and the second table is filter_prop:

Schema::create('filter_prop', function (Blueprint $table) {
            $table->increments('FilterPropID');
            $table->string('Name')->unique();
            $table->integer('FilterGroupID')->unsigned();
            $table->foreign('FilterGroupID')->references('FilterGroupID')->on('filter_group');
            $table->timestamps();
        });

The FilterGroup model:

    // a filter group can have many filter properties
    public function properties(){
        return $this->belongsToMany(FilterProp::class);
    }

The FilterProp model:

    // a filter property belongs to one filter group
    public function group(){
        return $this->belongsTo(FilterGroup::class, 'FilterGroupID','FilterGroupID');
    }

What I am doing wrong?

17 Oct
9 months ago

calin.ionut left a reply on How To Create A Dynamic Route

that`s what i am using now.... but i want to change them to be more seo friendly

calin.ionut started a new conversation How To Create A Dynamic Route

It is possible to create a dynamic route:

ex:

/{category}/filter1/filter2/filter3/....

and read in the controller all the segments after the {category}, without creating custom routes for each one ?

I have tried this:

/{category-slug}/{filter1}

but this route reads the first segment: (category-slug) and second (filter1).

If I have the third segment in the url, I have to declare another route.

/{category-slug}/{filter1}/{filter2}

I want to create a filter for the category. The filters applied are the segments in the url.

16 Oct
9 months ago

calin.ionut left a reply on Download A Url File Istead Of Opening The File

Creating a hidden form and submit it after the ajax call...works

The hidden form:

<form id="downloadXmlForm" method="post" action="{{ route('download-xml-invoices') }}" style="display: none">
     <input type="hidden" name="xmlFileName">
     <button type="submit" class="btn btn-primary">Export XML</button>
     ({ csrf_field() }}
</form>

After receiving from ajax request (on success) => submit the form to download the file:

$('input[name="xmlFileName"]').val(resp.fileName);                                
document.getElementById('downloadXmlForm').submit();

On the backend the response for the ajax request is:

...
$fileName = uniqid().'.xml';
$xmlFilePath = storage_path('invoices/'.$fileName);
file_put_contents($xmlFilePath, $xmlString);

return response()->json(['error' => false, 'msg' => $message, 'fileName' => $fileName]);

The download function that is call on form submit:

public function downloadInvoicesXml(Request $request){
    return response()->download( storage_path('invoices/'.$request->input('xmlFileName')));
}

calin.ionut left a reply on Download A Url File Istead Of Opening The File

i have tried on the server with:

return  $response = response($xmlString, 200, [
            'Content-Type' => 'application/xml',
            'Content-Disposition' => 'attachment; filename="test.xml"',
        ]);

where $xmlString is the file generated. I think is more secure for me to download directly the file instead saving it on the server then download.

But i am not sure how to change the ajax ... to download the file directly (on success response)

calin.ionut left a reply on Download A Url File Istead Of Opening The File

Hi @Palak27

I have tried....but the same thing. The file is opened in the same page

calin.ionut started a new conversation Download A Url File Istead Of Opening The File

I am having some trouble downloading a file content from the server.

I want to send an ajax request with some data to the server and get back the response the xml file that was generated.

The ajax request is:

  $('#exportInvoice').on('click', function () {
         $.ajax({
              type: 'POST',
              dataType: 'json',
              url: '{{ route('export-xml') }}',
              data: {dateRange: dateRange},
              success: function (resp) {
                  if(resp.error){
                      swal("", resp.msg, "error");
                  } else {
                       swal({title: "", text: resp.msg, type: "success"}, function(){
                             window.location = resp.url;
                       });                            
                  }
              }
          });
  }) ```

the server response

return response()->json(['error' => false, 'msg' => $message, 'url' => asset('uploaded/export-invoice.xml')]) ->header('Content-Type', 'application/xml') ->header('Content-Disposition','attachment; filename="myfile.xml"');


The file is opening in the browser .... instead of downloading.
09 Oct
9 months ago

calin.ionut left a reply on Create A Megamenu With 4 Columns

i simplified the code :)

calin.ionut left a reply on Create A Megamenu With 4 Columns

i`ts not hard but.... anyway. Once at top @foreach and once at bottom @endforeach

calin.ionut left a reply on Create A Megamenu With 4 Columns

i have tried on each line too but the same...

calin.ionut left a reply on Create A Megamenu With 4 Columns

@Snapey i have tried putting 3 backticks before and after each code block, but with no success :(

08 Oct
9 months ago

calin.ionut started a new conversation Create A Megamenu With 4 Columns

I am having some trouble creating a dynamic megamenu with laravel blade

Each Group Category contains up to 60 categories;

What i want is => each group category

  1. must have 4 columns;
  2. each column must have max 15 categories, not more then 60;
  3. IF 4th column is empty => display a picture (only on the 4th);
  4. the 4th column IF contain the picture must be the last column.

ex: if the group category have 12 categories => display the 12 categories on the first column, second and third will be empty and the fourth will have the picture.

My code for this is (from laravel blade template ):

@foreach($groupCategories as $grCat) @php $i = 0; $c = 0; $cats = $tools->getCategoriesByGroup($grCat->GroupCategoryID); @endphp

  • {{ $grCat->Name }}
        @if(count($cats) > 0) @foreach($cats as $cat) @if($c == 0 || $i % 15 == 0) {!! '' !!} @php $c = 0; @endphp @endif @php $i++ @endphp @endforeach

                        @if( (count($cats) < 15) || (count($cats) > 15 && count($cats) < 45) || (count($cats) > 45 && count($cats) < 60) ) {!! '</ul>' !!} @endif
        
                        @if((count($cats) <= 15)) {!! '<ul class="col-lg-3"></ul> <ul class="col-lg-3"></ul>' !!} @endif
        
                        @if((count($cats) > 15 && count($cats) < 45)) {!! '<ul class="col-lg-3"></ul>' !!} @endif
                       
                        @if( count($cats) <= 45 ) <img src="customimage.jpg"> @endif
                    @endif
                </ul>
            </ul>
        </li>
        

        @endforeach

        If i have on a group category exactly 30 categories, it does not display properly. If it`s less then 30 or greater then 30 it works.

        Have anyone any better idea how to make this code more simple and working? :)