calin.ionut

calin.ionut

Member Since 2 Years Ago

Experience Points 5,340
Experience Level 2

4,660 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.

24 Aug
3 weeks ago

calin.ionut left a reply on (Swift_TransportException(code: 0): Connection To Tcp://server.example.com:465 Timed Out

it's working now.....I didn't do anything.

I thing the cache was the problem...after changing in the .env

Always is a pain in the ass when changing something in .env

23 Aug
3 weeks ago

calin.ionut left a reply on Run Queue:work In Maintenance Mode ?

@tykus

because I was testing the new email settings on maintenance mode ... which I am using queue (database) to send emails in bkg and try to force to send email (from jobs table) using the mentioned command ..... it does not do anything.

The job is not dispatch from the jobs table.....ONLY if I get out of maintanance (php artisan up).

That`s why not work!

calin.ionut started a new conversation (Swift_TransportException(code: 0): Connection To Tcp://server.example.com:465 Timed Out

We have changed the email server from a provider to another. The where sending with the old email settings but not with the new ones. I am not sure if it`s laravel server or email server.

I will use here my domain as: example.com

I have changed the new email settings in .env:

MAIL_DRIVER=smtp
MAIL_HOST=server.example.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=ssl

and when we send emails we get this exception in laravel.log

production.ERROR: Connection to tcp://server.example.com:465 Timed Out {"exception":"[object] (Swift_TransportException(code: 0): Connection to tcp://server.example.com:465 Timed Out at /var/www/example.com/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:473, Swift_IoException(code: 0): Connection to tcp://server.example.com:465 Timed Out at /var/www/example.com/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php:166)

I have tried also with tls instead of ssl but the same error.

I have configure that email [email protected] in thunderbird with the given settings from the provider and works.

Email settings: incomming: IMAP server.example.com 993 SSL/TLS Encrypted password outgoing: SMTP server.example.com 465 SSL/TLS Encrypted password

username (email address) and password.

I am missing something ????

calin.ionut started a new conversation Run Queue:work In Maintenance Mode ?

How to run php artisan queue:work in maintenance mode (php artisan down) ????

Is this possible?

calin.ionut left a reply on Config:cache => Your Configuration Files Are Not Serializable.

The problem was in the Controller constructor when defining the $agent.

$agent = new Agent();
config(['agent' => $agent]);

It seems that in config should not be defined any function.

A temp fix:

1 Clear the config

php artisan config:clear

2 comment the code from Controller.php where i defined the $agent

3 Cache the config

php artisan config:cache

4 Uncomment the code from Controller

I was changing some value from .env and the changes was not reflected in the app, then i played with the cache and discover this error :)

calin.ionut started a new conversation Config:cache => Your Configuration Files Are Not Serializable.

I am having an error using the command in laravel 5.8

~$ php artisan config:cache
Your configuration files are not serializable.

I investigate where the problem come from.

Commented the line:

$this->files->delete($configPath);

from

vendor/laravel/framework/src/Illuminate/Foundation/Console/ConfigCacheCommand.php

to see exactly what`s the problem.

In bootstrap/cache/config.php on line 612 is the problem.

"Call to undefined method Jenssegers\Agent\Agent::__set_state()

The Agent is installed via composer ("jenssegers/agent": "^2.6")

Added in /config/app.php

on aliases

 'Agent' => Jenssegers\Agent\Facades\Agent::class,

and on providers

Jenssegers\Agent\AgentServiceProvider::class,

I need $agent in every controller and view and defined Agent in Controller.php in the constructor:

// detect device agent
        $agent = new Agent();
        config(['agent' => $agent]);
        

It`s not ok how i defined the agent in Controller???

Why it complains about:

 undefined method Jenssegers\Agent\Agent::__set_state()

?

20 Aug
3 weeks ago

calin.ionut left a reply on How To Sync Attributes In A Specific Order ?

@sergiu17 on my machine don`t :))

 foreach ($attributes as $attr) {
            echo $attr.' ';
        }
        echo '<br>';

        $product->attributes()->detach();
        foreach($attributes as $attribute) {
            $product->attributes()->attach($attribute);
        }

        foreach ($product->attributes as $attr) {
            echo $attr->AttributeID.' ';
        }

outputs:

82 84 83 86 
82 83 84 86

it still save the attribute_id in asc order.

@ftiersch

The pivot table have two columns (attribute_id and product_id)

Why the order is important?

Because I want to display them in the order they were saved

calin.ionut left a reply on How To Sync Attributes In A Specific Order ?

@sergiu17

tried this combination allready :)

$product->attributes()->detach();

foreach($attributes as $attribute) {
       $product->attributes()->attach($attribute);
}

but the same thing....does not save in the order that the elements are in attributes array

calin.ionut started a new conversation How To Sync Attributes In A Specific Order ?

I have pivot table that saves the attribute_id and product_id

When saving the product with attributes ($attributes) i get an array ex:

array:4 [
  0 => "82"
  1 => "84"
  2 => "83"
  3 => "86"
]

Those attribute I need to be in that order!!!!

That`s the problem

when saving:

 $product->attributes()->sync($attributes, true);

it saved in this order:

attribute_id    product_id
82                   31
83                   31
84                   31
86                   31

How can I save in the order that is on the array (82, 84, 83, 86) ???

calin.ionut left a reply on Search In Multiple Fields Using Eloquent

@cronix

still not working ...

 $products = Product::where(array(['IsActive', '1']))
                ->where(function ($query) use ($search) {
                    $query->where('Name', 'like', '%'.$search.'%')->orWhere('Code', 'like', '%'.$search.'%');
                })
                ->orderBy('created_at', 'desc')
                ->paginate(12)
                ->appends($queries);

It works independently for code and for product name.

If the user type for ex:

1217 TRICOU EXTREME

where 1217 is the code for product name: "TRICOU EXTREME" it does not find anything.

@jlrdw i will test to see if it works.

19 Aug
4 weeks ago

calin.ionut started a new conversation Search In Multiple Fields Using Eloquent

I want to implemented a search for products in laravel 5.8 and in the search controller I have this:

$search = $request->input('ref');
$queries['ref'] = $search;
$products = Product::where(array(['IsActive', '1'], ['Name', 'like', '%' . $search . '%']))
                ->orWhere(array(['IsActive', '1'], ['Code', 'like', '%' . $search . '%']))
                ->orderBy('created_at', 'desc')
                ->paginate(12)
                ->appends($queries);

The search is working for product name and product code (but not combined). I you use a separate search for code OR for product name will work.

For example if i search for:

4512 Tennis ATP Balls Babolat

where 4512 is the product code and "Tennis ATP Balls Babolat" is the product name, the search will not found anything.

What I know about the % in the like:

'Name', 'like', '%4512 Tennis ATP Balls Babolat%'

should find any values that have "4512 Tennis ATP Balls Babolat" in any position

What I dis wrong?

08 Aug
1 month ago

calin.ionut left a reply on Search For Day Created_at

@cronix

the result will be :

2019-08-07 00:00:00 had 2 orders.
2019-08-06 00:00:00 had 1 orders.
2019-08-05 00:00:00 had 1 orders.

for the other days if i don`t have orders it will not get.

How can i set for 2019-08-04, 2019-08-03 .... if there is not any order, the value 0 ?

There is no other way that I can get the entries for a specific day more easily (created_at) ???

something like this?

$orders = DB::table('orders')->whereNull('deleted_at')->whereDay('created_at', $day)->count();
07 Aug
1 month ago

calin.ionut left a reply on Search For Day Created_at

@aurawindsurfing

i want for a specific date not between.

Ex: 2019.08.07 - 2 orders 2019.08.06 - 5 orders 2019.08.05 - 10 orders ...

the $orders will be the count orders for a specific day.

calin.ionut started a new conversation Search For Day Created_at

Hello,

I have this array:

$last7DaysOrders = array(
            'labels' => array(),
            'datasets' => array(
                array(
                    'label' => 'Orders',
                    'data' => array()
                )
            )
        );

and i want to get the number of orders for the last 7 days.

      for ($i = 6; $i >= 0; $i--) {
            $day = Carbon::today()->subDay($i);
            array_push($last7DaysOrders['labels'], $day->format('D'));
            $orders = DB::table('orders')->whereNull('deleted_at')->whereDay('created_at', $day)->count();
            array_push($last7DaysOrders['datasets'][0]['data'], $orders);
        }

but i get unexpected results for the number of orders.

I have also tried with:

$orders = DB::table('orders')->whereNull('deleted_at')->where('created_at', 'like',  $day->format('Y-m-d'))->count();

but i get 0 result.

Any ideas how can I do it?

19 Jul
1 month 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
2 months 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"}\')');

if using "2" not 2 will work!

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
2 months 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="onSearchTable">
</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
3 months 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
4 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
4 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
4 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.

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
5 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 - maybe i forgot something.....

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_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:

mysql -u root -p

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

31 Jan
7 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
9 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 create 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
9 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
9 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
9 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;
    }

then 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
10 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`s not setting the name in from. Why?