Categories
Uncategorized

laravel 8 tips and tricks and how i did it

In day of my learning today on PHP Laravel 8 building application from scratch with google search help!

I am not a good write I am just posting random solutions of my finding in building Laravel application from scratch!. (I don’t claim anybody solutions to mine, this is suggest as a side support. Thanks!)

How to create mailable class in Laravel using version 8?

php artisan make:mail OrderStatusUpdate --markdown=emails.orders.statusupdated 

I have used –markdown option to automatically general email template file for me under resources/views/emails/orders/statusupdated.blade.php file to have template ready on fly to start working!

It will create OrderStatusUpdate class file under Mail folder under app/Mail folder automatically!

How to create custom route to view the email template in browser before sending any emails for test?

Route::get('/mailable', function () {
     $msg = 'Order ID TEST! updated successfully!';
    return new App\Mail\OrderStatusUpdated($msg);
});

This lines of code you can add to web.php under /routes folder which you can easily test out the template by directly visiting to your website or Laravel deployed path for example: youwebsite.com/mailable or yourwebsite.com/somefoldername/mailable like so!

How to pass data as array to mailable class file from Laravel Controller file?

public function handlUpdateOrderStatus(Request $request) {
        
        try {
            $query = Order::where('orderId',$request->orderId)->update(['status' => $request->value, 'updatedAt' => now()]);
            
            // create response result
            if($query) {
                
                $msg = 'Order # '.$request->orderNumber.' (OrderID:'.$request->orderId. ') updated to '. $this->orderStatusList[$request->value] .' successfully!';
                
                // Shoot email
                Mail::to( env('MAIL_REPLY_TO_ADDRESS'), env('MAIL_FROM_NAME_ADMIN') )->send(new OrderStatusUpdated(['msg'=> $msg, 'orderNumber' => $request->orderNumber]));
                
                return ["success" => true, 'message'=> $msg];
                
            } else {
                
                return [
                    "error" => true,
                    'message'=> "Error in updating status, please try again/later."];
            }
        }
        catch(\Exception $e){
            // Get error here
            echo "Email test exception or query exception OrderController!";
        }
        
    }

This function in my OrderController.php file is actually to update the DB record and then shoot email, so here also wanted to pass data to mailable class instance as an array, this is how above, I have passed as array data and will retrieve in the mailable class file (in following next question or block below this one Queue1)

While I was testing this code I came up to another error of issue (Swift_TransportException Connection to mail.xxxxx.com:465 Timed Out), I thought error was to parameter to Mail:: facade function or line, but, syntactically what I followed was correct so no change there.

Then I searched over this and came to find, in .env file MAIL_ENCRYPTION set to null, before setting anything there, I was looking under config/mail.php for default settings where I have tried to add ssl value to encryption and then testes found to be working. Then I have changed the same under .env file MAIL_ENCRYPTION=ssl which was set to null by default of installation of Laravel application and commented or reverted back config/mail.php code and then voila, it worked like charm! (continue to complete Queue1)

How to retrieve data as array passed to mailable instance from Laravel controller and pass down to Laravel email template?


namespace App\Mail;

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

class OrderStatusUpdated extends Mailable implements ShouldQueue {
public $details;
    /**
     * Create a new message instance.
     *
     * @param  \App\Models\Order  $order
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('Order # '. $this->details['orderNumber'] .' Status Updated')
                ->markdown('emails.orders.statusupdated');
    }
}

Here is the block of code fetching/retrieving data in public variable which is pass down to this mailable class file instance in controller as we discussed above in last question and accessing the same under build function of this mailable class file.

I have also implemented this class file with ShouldQueue following Laravel guide on mail.

I have also added following public property: $afterCommit : true, but got below error:

App\Mail\OrderStatusUpdated and Illuminate\Bus\Queueable define the same property ($afterCommit) in the composition of App\Mail\OrderStatusUpdated. However, the definition differs and is considered incompatible. Class was composed

I have remove it as it was not troubling me even if I don’t have it, I guess this be might the case for lower version of Laravel’s than 8.

How to finally consume the data passed in Laravel email template passed down via its mailable class?

@component('mail::message')

# Order Status

Order # {{ $details['orderNumber'] }} 
{{ $details['msg'] }}

@component('mail::button', ['url' => ''])
View Order
@endcomponent

Thanks,<br>
{{ config('app.name') }}
@endcomponent

Finally this is how the template rendered and worked for me! Hope it will work for you too!

Beside this I have also added Laravel Customize components which I will be implementing/using further in the application development. Keep you posted in case I can up with issues in its implementations.

Thanks for visiting & reading the post. Hope it help you in your way of building applications.