#laravel mailable tutorial
Explore tagged Tumblr posts
laravelvuejs · 6 years ago
Text
Laravel 5.8 Tutorial From Scratch - e20 - Flashing Data to Session & Conditional Alerts in View - Laravel
Laravel 5.8 Tutorial From Scratch – e20 – Flashing Data to Session & Conditional Alerts in View – Laravel
Laravel 5.8 Tutorial From Scratch – e20 – Flashing Data to Session & Conditional Alerts in View – Laravel
[ad_1]
Now that our contact form is sending emails, it’s time for us to focus on providing some feedback for our users once the form goes through. Follow along as we flash some data to the session and conditionally display an alert on the view. We will also tackle the inverse to hide our form.
View On WordPress
0 notes
phpdeveloperfan · 6 years ago
Photo
Tumblr media
Easy and Fast Emails with Laravel 5.3 Mailables ☞ https://scotch.io/tutorials/easy-and-fast-emails-with-laravel-5-3-mailables #php #laravel
1 note · View note
theskillstock · 3 years ago
Text
​Laravel 9 e-mail sending tutorail; on this tutorial we can learn how to send emails in laravel 9 the usage of SMTP drivers like Mailgun, Postmark, Amazon SES and sendemail. Laravel 9 provide us a mail class for sending emails. So we would really like to show you the way to send emails from localhost the use of mailable in laravel 9 project. Laravel 9 affords numerous SMTP drivers consisting of Mailgun, Postmark, Amazon SES and sendmail.
1 note · View note
phpprogrammingblr · 6 years ago
Photo
Tumblr media
Easy and Fast Emails with Laravel 5.3 Mailables ☞ https://scotch.io/tutorials/easy-and-fast-emails-with-laravel-5-3-mailables #php #laravel
0 notes
wordpresstemplateslove · 6 years ago
Photo
Tumblr media
Easy and Fast Emails with Laravel 5.3 Mailables ☞ https://scotch.io/tutorials/easy-and-fast-emails-with-laravel-5-3-mailables #php #laravel
0 notes
airman7com · 5 years ago
Text
Laravel 7.x, 6 Kirim Email Menggunakan Tutorial Kelas Mailable
Laravel 7.x, 6 Kirim Email Menggunakan Tutorial Kelas Mailable
Dalam artikel ini, Kami akan menunjukkan kepada Anda cara mengirim email secara laravel menggunakan kelas yang tersedia dengan contoh. Kami akan belajar cara mengirim email di laravel menggunakan driver SMTP. Laravel menyediakan API dengan dukungan driver untuk SMTP, SendMail, Mailgun, Sendgrid, Mandrill, Amazon SES, SpartPost, dll. Tutorial contoh ini juga berfungsi dengan versi laravel 7.x,…
View On WordPress
0 notes
mbaljeetsingh · 7 years ago
Text
Understanding and Working with Files in Laravel
File uploads is one the most commonly used features on the web. From uploading avatars to family pictures to sending documents via email, we can't do without files on the web.
In today’s article will cover all the ways to handle files in Laravel. If you are new to Laravel, browse the courses or navigate to the tutorials section. After reading the article, If we left something out please let us know in the comments and we’ll update the post accordingly.
Handling of files is another thing Laravel has simplified in its ecosystem. Before we get started, we’ll need a few things. First, a Laravel project. There are a few ways to create a new Laravel project, but let's stick to composer for now.
composer create-project --prefer-dist laravel/laravel files
Where files is the name of our project. After installing the app, we’ll need a few packages installed, so, let’s get them out of the way. You should note that these packages are only necessary if you intend to save images to Amazon’s s3 or manipulate images like cropping, filters etc.
composer require league/flysystem-aws-s3-v3:~1.0 intervention/image:~2.4
After installing the dependencies, the final one is Mailtrap. Mailtrap is a fake SMTP server for development teams to test, view and share emails sent from the development and staging environments without spamming real customers. So head over to Mailtrap and create a new inbox for testing.
Then, in welcome.blade.php update the head tag to:
<meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>File uploads</title> <style> * { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; } </style>
Modify the body contents to:
<form action="/process" enctype="multipart/form-data" method="POST"> <p> <label for="photo"> <input type="file" name="photo" id="photo"> </label> </p> <button>Upload</button> </form>
For the file upload form, the enctype="multipart/form-data" and method="POST" are extremely important as the browser will know how to properly format the request. is Laravel specific and will generate a hidden input field with a token that Laravel can use to verify the form submission is legit.
If the CSRF token does not exist on the page, Laravel will show “The page has expired due to inactivity” page.
Now that we have our dependencies out of the way, let's get started.
Understanding How Laravel Handles Files
Development as we know it in 2018 is growing fast, and in most cases there are many solutions to one problem. Take file hosting for example, now we have so many options to store files, the sheer number of solutions ranging from self hosted to FTP to cloud storage to GFS and many others.
Since Laravel is framework that encourages flexibility, it has a native way to handle the many file structures. Be it local, Amazon's s3, Google's Cloud, Laravel has you covered.
Laravel's solution to this problem is to call them disks. Makes sense, any file storage system you can think of can be labeled as a disk in Laravel. To this regard, Laravel comes with native support for some providers (disks). We have: local, public, s3, rackspace, FTP etc. All this is possible because of Flysystem.
If you open config/filesystems.php you’ll see the available disks and their respected configuration.
File Uploads in Laravel
From the introduction section above, we have a form with a file input ready to be processed. We can see that the form is pointed to /process. In routes/web.php, we define a new POST /process route.
use Illuminate\Http\Request; Route::post('process', function (Request $request) { $path = $request->file('photo')->store('photos'); dd($path); });
What the above code does is grab the photo field from the request and save it to the photos folder. dd() is a Laravel function that kills the running script and dumps the argument to the page. For me, the file was saved to "photos/3hcX8yrOs2NYhpadt4Eacq4TFtpVYUCw6VTRJhfn.png". To find this file on the file system, navigate to storage/app and you’ll find the uploaded file.
If you don't like the default naming pattern provided by Laravel, you can provide yours using the storeAs method.
Route::post('process', function (Request $request) { // cache the file $file = $request->file('photo'); // generate a new filename. getClientOriginalExtension() for the file extension $filename = 'profile-photo-' . time() . '.' . $file->getClientOriginalExtension(); // save to storage/app/photos as the new $filename $path = $file->storeAs('photos', $filename); dd($path); });
After running the above code, I got "photos/profile-photo-1517311378.png".
Difference Between Local and Public Disks
In config/filesystems.php you can see the disks local and public defined. By default, Laravel uses the local disk configuration. The major difference between local and public disk is that local is private and cannot be accessed from the browser while public can be accessed from the browser.
Since the public disk is in storage/app/public and Laravel's server root is in public you need to link storage/app/public to Laravel's public folder. We can do that with our trusty artisan by running php artisan storage:link.
Uploading Multiple Files
Since Laravel doesn't provide a function to upload multiple files, we need to do that ourselves. It’s not much different from what we’ve been doing so far, we just need a loop.
First, let’s update our file upload input to accept multiple files.
<input type="file" name="photos[]" id="photo" multiple>
When we try to process this $request->file('photos'), it's now an array of UploadedFile instances so we need to loop through the array and save each file.
Route::post('process', function (Request $request) { $photos = $request->file('photos'); $paths = []; foreach ($photos as $photo) { $extension = $photo->getClientOriginalExtension(); $filename = 'profile-photo-' . time() . '.' . $extension; $paths[] = $photo->storeAs('photos', $filename); } dd($paths); });
After running this, I got the following array, since I uploaded a GIF and a PNG:
array:2 [▼ 0 => "photos/profile-photo-1517315875.gif" 1 => "photos/profile-photo-1517315875.png" ]
Validating File Uploads
Validation for file uploads is extremely important. Apart from preventing users from uploading the wrong file types, it’s also for security. Let me give an example regarding security. There's a PHP configuration option cgi.fix_pathinfo=1. What this does is when it encounters a file like https://site.com/images/evil.jpg/nonexistent.php, PHP will assume nonexistent.php is a PHP file and it will try to run it. When it discovers that nonexistent.php doesn't exists, PHP will be like "I need to fix this ASAP" and try to execute evil.jpg (a PHP file disguised as a JPEG). Because evil.jpg wasn’t validated when it was uploaded, a hacker now has a script they can freely run live on your server… Not… good.
To validate files in Laravel, there are so many ways, but let’s stick to controller validation.
Route::post('process', function (Request $request) { // validate the uploaded file $validation = $request->validate([ 'photo' => 'required|file|image|mimes:jpeg,png,gif,webp|max:2048' // for multiple file uploads // 'photo.*' => 'required|file|image|mimes:jpeg,png,gif,webp|max:2048' ]); $file = $validation['photo']; // get the validated file $extension = $file->getClientOriginalExtension(); $filename = 'profile-photo-' . time() . '.' . $extension; $path = $file->storeAs('photos', $filename); dd($path); });
For the above snippet, we told Laravel to make sure the field with a name of photo is required, a successfully uploaded file, it’s an image, it has one of the defined mime types, and it’s a max of 2048 kilobytes ~~ 2 megabytes.
Now, when a malicious user uploads a disguised file, the file will fail validation and if for some weird reason you leave cgi.fix_pathinfo on, this is not a means by which you can get PWNED!!!
If you head over to Laravel's validation page you’ll see a whole bunch of validation rules.
Moving Files to the Cloud
Okay, your site is now an adult, it has many visitors and you decide it’s time to move to the cloud. Or maybe from the beginning, you decided your files will live on separate server. The good news is Laravel comes with support for many cloud providers, but, for this tutorial, let's stick with Amazon.
Earlier we installed league/flysystem-aws-s3-v3 through composer. Laravel will automatically look for it if you choose to use Amazon S3 or throw an exception.
To upload files to the cloud, just use:
$request->file('photo')->store('photos', 's3');
For multiple file uploads:
foreach ($photos as $photo) { $extension = $photo->getClientOriginalExtension(); $filename = 'profile-photo-' . time() . '.' . $extension; $paths[] = $photo->storeAs('photos', $filename, 's3'); }
Users may have already uploaded files before you decide to switch to a cloud provider, you can check the upcoming sections for what to do when files already exist.
Note: you’ll have to configure your Amazon s3 credentials in config/filesystems.php**.**
Sending Files as Email Attachments
Before we do this, let's quickly configure our mail environment. In .env file you will see this section
MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null
We need a username and password which we can get at Mailtrap.io. Mailtrap is really good for testing emails during development as you don’t have to crowd your email with spam. You can also share inboxes with team members or create separate inboxes.
First, create an account and login:
Create a new inbox
Click to open inbox
Copy username and password under SMTP section
youtube
After copying credentials, we can modify .env to:
MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=8a1d546090493b MAIL_PASSWORD=328dd2af5aefc3 MAIL_ENCRYPTION=null
Don't bother using mine, I deleted it.
Create your mailable
php artisan make:mail FileDownloaded
Then, edit its build method and change it to:
public function build() { return $this->from('[email protected]') ->view('emails.files_downloaded') ->attach(storage_path('app/file.txt'), [ 'as' => 'secret.txt' ]); }
As you can see from the method above, we pass the absolute file path to the attach() method and pass an optional array where we can change the name of the attachment or even add custom headers. Next we need to create our email view.
Create a new view file in resources/views/emails/files_downloaded.blade.php and place the content below.
<h1>Only you can stop forest fires</h1> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Labore at reiciendis consequatur, ea culpa molestiae ad minima est quibusdam ducimus laboriosam dolorem, quasi sequi! Atque dolore ullam nisi accusantium. Tenetur!</p>
Now, in routes/web.php we can create a new route and trigger a mail when we visit it.
use App\Mail\FileDownloaded;
Route::get('mail', function () { $email = '[email protected]'; Mail::to($email)->send(new FileDownloaded); dd('done'); });
If you head over to Mailtrap, you should see this.
Storage Facade for When Files Already Exist
In an application, it’s not every time we process files through uploads. Sometimes, we decide to defer cloud file uploads till a certain user action is complete. Other times we have some files on disk before switching to a cloud provider. For times like this, Laravel provides a convenient Storage facade. For those who don’t know, facades in Laravel are class aliases. So instead of doing something like Symfony\File\Whatever\Long\Namespace\UploadedFile, we can do Storage instead.
Choosing a disk to upload file. If no disk is specified, Laravel looks in config/filesystems.php and use the default disk.
Storage::disk('local')->exists('file.txt');
use default cloud provider
// Storage::disk('cloud')->exists('file.txt'); will not work so do: Storage::cloud()->exists('file.txt');
Create a new file with contents
Storage::put('file.txt', 'Contents');
Prepend to file
Storage::prepend('file.txt', 'Prepended Text');
Append to file
Storage::append('file.txt', 'Prepended Text');
Get file contents
Storage::get('file.txt')
Check if file exists
Storage::exists('file.txt')
Force file download
Storage::download('file.txt', $name, $headers); // $name and $headers are optional
Generate publicly accessible URL
Storage::url('file.txt');
Generate a temporary public URL (i.e files that won’t exists after a set time). This will only work for cloud providers as Laravel doesn’t yet know how to handle generation of temporary URLs for local disk.
Storage::temporaryUrl('file.txt’, now()->addMinutes(10));
Get file size
Storage::size('file.txt');
Last modified date
Storage::lastModified('file.txt')
Copy files
Storage::copy('file.txt', 'shared/file.txt');
Move files
Storage::move('file.txt', 'secret/file.txt');
Delete files
Storage::delete('file.txt');
// to delete multiple files Storage::delete(['file1.txt', 'file2.txt']);
Manipulating files
Resizing images, adding filters etc. This is where Laravel needs external help. Adding this feature natively to Laravel will only bloat the application since not installs need it. We need a package called intervention/image. We already installed this package, but for reference.
composer require intervention/image
Since Laravel can automatically detect packages, we don't need to register anything. If you are using a version of Laravel lesser than 5.5 read this.
To resize an image
$image = Image::make(storage_path('app/public/profile.jpg'))->resize(300, 200);
Even Laravel's packages are fluent.
You can head over to their website and see all the fancy effects and filters you can add to your image.
Don’t forget directories
Laravel also provides handy helpers to work with directories. They are all based on PHP iterators so they'll provide the utmost performance.
To get all files:
Storage::files
To get all files in a directory including files in sub-folders
Storage::allFiles($directory_name);
To get all directories within a directory
Storage::directories($directory_name);
To get all directories within a directory including files in sub-directories
Storage::allDirectories($directory_name);
Make a directory
Storage::makeDirectory($directory_name);
Delete a directory
Storage::deleteDirectory($directory_name);
Conclusion
If we left anything out, please let us know down in the comments. Also, checkout Mailtrap, they are really good and they will help you sail through the development phase with regards to debugging emails.
via Scotch.io http://ift.tt/2sHlNEp
0 notes
laravelvuejs · 6 years ago
Text
Laravel 5.8 Tutorial From Scratch - e19 - Handling a Contact Form Using a Laravel Mailable - Laravel
Laravel 5.8 Tutorial From Scratch – e19 – Handling a Contact Form Using a Laravel Mailable – Laravel
Laravel 5.8 Tutorial From Scratch – e19 – Handling a Contact Form Using a Laravel Mailable – Laravel
[ad_1]
Having a contact form where a user can submit their contact request is a very common thing in today’s modern websites. Follow along as we add a contact form and use a Mailable to send an email.
For the best experience, follow along in our interactive school at https://www.coderstape.com
Res…
View On WordPress
0 notes
laravelvuejs · 8 years ago
Text
[ Part 05 laravel 5.5 new features series ] Introduction to New Feature of Mailable in urdu 2018
[ Part 05 laravel 5.5 new features series ] Introduction to New Feature of Mailable in urdu 2018
[ad_1]
Hello Friends, Welcome to Part 05 of laravel 5.5 new features series by perfect web solutions. In this video tutorial, we will get Introduction to new Mailable Features in Urdu and Hindi language 2018. Laravel provides a clean, simple API over the popular SwiftMailer library with drivers for SMTP, Mailgun, SparkPost, Amazon SES, PHP’s mail function, and sendmail, allowing you to quickly…
View On WordPress
0 notes
airman7com · 5 years ago
Text
Laravel 7.x,6 Send Email Using Mailable Class Tutorial
In this article, we will show you how to send e-mails using classes available with examples. We will learn how to send e-mails using the SMTP driver. Laravel provides an API with driver support for SMTP, SendMail, Mailgun, Sendgrid, Mandrill, Amazon SES, SpartPost, etc. This example tutorial also works with laravel versions 7.x, 6.x, 5.x.
We will give you a very simple example of a mailable class…
View On WordPress
0 notes
mbaljeetsingh · 8 years ago
Text
Building a User Invitation System with Laravel
In the not too distant past at ubisend, we needed to build a solution to provide our users the ability to invite additional users to manage their account.
This is a pretty common problem.
Think about a CMS. It’s not much use if you are the only person able to create new content and you certainly don’t want to share your password to allow someone to proof an article.
Similarly, imagine you are building a multitenanted application and want to give your users the ability to add additional members to their team.
Sure, you could build out some CRUD methods for managing users, but wouldn’t it better if you could allow those users to set their own passwords rather than having to send it to them by email, insecurely, in plaintext?
This article will walk you through one approach to building this functionality.
Housekeeping
This task could be carried out in a multitude of ways. At its simplest, we could create a new user record (flagging it inactive) and store a token which is then used in a link to activate the account.
Here, though, we will tackle the problem in a different way using an additional invites table where we will store the user’s email address and activation token. Upon activation, we will use this data to create the new user.
We’ll be using a fresh install of Laravel 5.4, and you will need to have configured your database and mail settings.
Migrations
A default Laravel installation will give us a leg-up for the user migration as it ships by default with the framework.
For this tutorial, remove the name and password fields from the migration:
public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('email')->unique(); $table->rememberToken(); $table->timestamps(); }); }
We do need to create a migration for our invites. On the console from the root of your project, run php artisan make:migration create_invites_table.
This command will create a new migration file in the database/migrations directory. We’ll need to define an incrementing ID, a field to store the new user’s email address and a field for the unique token the new user will use when accepting the invite.
public function up() { Schema::create('invites', function (Blueprint $table) { $table->increments('id'); $table->string('email'); $table->string('token', 16)->unique(); $table->timestamps(); }); } public function down() { Schema::drop('invites'); }
Now, on the console from the root of your project, run php artisan migrate.
The database is good to go.
Models
We will need to create Eloquent models for managing both our team and user records.
As with migrations, Laravel ships with a default Eloquent user model so no need to create one.
For the invites model, head back to the console, and from the root of your project run php artisan make:model Invite.
Take a look in the app directory, and you will see your newly created invite model.
All we need to do here is define the fillable fields as follows. This will allow us to mass assign properties when creating updating models.
protected $fillable = [ 'email', 'token', ];
Routes
For this tutorial we’ll need to define three routes for the following scenarios:
Show the form to invite a new user
Process the form submission
Accept the invitation
In the app/routes/web.php file, add the following routes:
Route::get('invite', 'InviteController@invite')->name('invite'); Route::post('invite', 'InviteController@process')->name('process'); // {token} is a required parameter that will be exposed to us in the controller method Route::get('accept/{token}', 'InviteController@accept')->name('accept');
Controller
The eagle-eyed readers will have noticed when defining the routes above we referenced InviteController to process the requests.
That controller can, again, be created using artisan. On the console from the root of your project, run php artisan make:controller InviteController.
Open up app/Http/Controllers/InviteController.php and define the following methods:
public function invite() { // show the user a form with an email field to invite a new user } public function process() { // process the form submission and send the invite by email } public function accept($token) { // here we'll look up the user by the token sent provided in the URL }
Great, everything is set up. We can now flesh out these methods and make our invitation system come to life.
Business Logic
Here, we will work through each of the methods stubbed out above.
invite()
This is nice and simple. We need to return a view which presents a form to the user where they can enter the email address of the invitee.
The method will look something like this:
public function invite() { return view('invite'); }
Create the file resources/views/invite.blade.php. This view will need to contain a form that posts to /invite with an input called email:
// make use of the named route so that if the URL ever changes, // the form will not break #winning <form action="" method="post"> <input type="email" name="email" /> <button type="submit">Send invite</button> </form>
process()
This is where the bulk of our work will be carried out.
As part of this method, we need to notify the new user that someone has sent them an invitation. To do that, let’s make use of Laravel’s mailables.
To start, we need to create a mailable class. On the console from the root of your project, run php artisan make:mail InviteCreated.
This will generate a new class called, you guessed it, InviteCreated in your app/Mail directory. Open up this class and update the constructor to accept an invite model and assign this as a public property.
use App\Invite; public function __construct(Invite $invite) { $this->invite = $invite; }
Now, to send the email, define a build method. This will determine who to send the email from and which view to use to generate the email.
public function build() { return $this->from('[email protected]') ->view('emails.invite'); }
Next, we need to generate said view file. Create the file resources/views/emails/invite.blade.php. We’ll keep this super simple:
<p>Hi,</p> <p>Someone has invited you to access their account.</p> <a href="">Click here</a> to activate!
“How do we have access to the $invite variable in our view,” I hear you cry! Laravel will automatically make all public properties of your mailable class available to your views.
Now, back to our InviteController, we will need to generate a unique random token which can be used to identify the new user when they accept the invitation. We will store this record in the invites table along with the email address provided by the person carrying out the invite.
use App\Invite; use App\Mail\InviteCreated; use Illuminate\Support\Facades\Mail; ... public function process(Request $request) { // validate the incoming request data do { //generate a random string using Laravel's str_random helper $token = str_random(); } //check if the token already exists and if it does, try again while (Invite::where('token', $token)->first()); //create a new invite record $invite = Invite::create([ 'email' => $request->get('email'), 'token' => $token ]); // send the email Mail::to($request->get('email'))->send(new InviteCreated($invite)); // redirect back where we came from return redirect() ->back(); }
Nice work! That’s our new invite stored, and the new user notified.
accept()
Finally, we need to allow our new users to accept the invite. This is what will happen when the user clicks the activation email we sent above.
Usually, you would probably want to capture a password and any other user details you may need at this point, but to keep this simple, we’re just going to check for the existence of the token and create the user accordingly.
Remember, the token in the URL will be passed to us as a parameter from Laravel.
use App\User; use App\Invite; use App\Mail\InviteCreated; use Illuminate\Support\Facades\Mail; ... public function accept($token) { // Look up the invite if (!$invite = Invite::where('token', $token)->first()) { //if the invite doesn't exist do something more graceful than this abort(404); } // create the user with the details from the invite User::create(['email' => $invite->email]); // delete the invite so it can't be used again $invite->delete(); // here you would probably log the user in and show them the dashboard, but we'll just prove it worked return 'Good job! Invite accepted!'; }
Give It a Go!
Hit the invite URL in your browser (e.g. http://ift.tt/2mSv88Z), enter the email address of the person you are inviting and submit the form.
Take a look in the invites table of your database; you should see new record has been created with a new unique token. Now check your email; you should have received a message containing a link to activate the new user which contains the token stored in the database.
Finally, click the link and you will be greeted with “Good job! Invite accepted!” which is a good sign. To check everything worked as expected, the invite record should no longer be in the database, but instead, a new user record should have appeared in the users table.
That’s a Wrap
Nice work! You have successfully implemented a user invitation system.
Although this is a simple example, it provides a good base to build from.
It would be trivial to extend this example to capture new user details at the point they accept the invitation as well as allowing invites to be revoked and/or re-sent.
Additionally, you could modify the code to support multitenancy or team/user relationships—though this would be somewhat more complex.
via Laravel News http://ift.tt/2nmS0d7
0 notes