Nedavno sam se malo mučio pokušavajući postaviti stranicu za kontakt u Laravelu. Pa sam zaključio da bih trebao voditi blog o svom iskustvu, jer bi moglo pomoći nekome tko to želi učiniti.
Laravel je PHP okvir otvorenog koda koji se koristi za razvoj web aplikacija. Slijedi arhitektonski obrazac model-view-controller.
Preduvjeti
- Instalirajte skladatelj
- Postavljanje lokalnog poslužitelja (xampp, wamp)
- Obavezno instalirajte uređivač koda (uzvišeni tekst, vs kôd, atom itd.)
- Instalirajte Git (omogućuje kontrolu i upravljanje izvorima)
Početak rada
S instaliranim Gitom imate pristup Git bashu. Kada je bash otvoren možete raditi s terminalom na pokretanju naredbi koje vam omogućavaju laku instalaciju i upotrebu Laravela i njegovih paketa.
Instalirajte Laravel putem skladatelja
Nakon što ste zadovoljili sve gore navedene uvjete, upotrijebit ćemo naredbu u nastavku za postavljanje instalacijskog programa Laravel:
composer global require laravel/installer
Gornja naredba omogućuje nam preuzimanje instalacijskog programa Laravel pomoću skladatelja koji smo ranije instalirali.
laravel new project_name
Ovaj postupak instalacije traje neko vrijeme, pa budite strpljivi. Imajte na umu da će se instalacija izvršiti u direktoriju koji navedete na vašem bash terminalu ili bilo kojem terminalu koji ste odlučili koristiti.
Generiranje osnovne skele za provjeru autentičnosti
Nakon što instaliramo kopiju aplikacije Laravel, trebali bismo generirati osnovni skener za provjeru autentičnosti.
cd project_name composer require laravel/ui php artisan ui vue --auth
Gornja naredba instalirat će prikaz izgleda, prikaz registracije i prikaz prijave, kao i rute za provjeru autentičnosti svih korisnika.
Postavljanje varijabli okruženja u datoteci .env
Dalje moramo postaviti naše varijable okruženja i uspostaviti vezu s našom bazom podataka ( u ovom ćemo članku koristiti zajedničku lažnu ip adresu ).
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database_name DB_USERNAME=server_username DB_PASSWORD=server_password MAIL_DRIVER=smtp MAIL_HOST=domain.com MAIL_PORT=465 [email protected] MAIL_PASSWORD=domain_password MAIL_ENCRYPTION=ssl M[email protected] MAIL_FROM_NAME="${APP_NAME}"
Sada smo završili s postavljanjem veze s bazom podataka. U mom slučaju radim s Xamppom tamo gdje imam DB_USERNAME=root
i DB_PASSWORD=
. Također ne zaboravite pokrenuti lokalni poslužitelj kao što je prikazano u nastavku.

Izrada verzija baze podataka i pokretanje razvojnog poslužitelja
Prije nego što pokrenete migracije u Laravelu, morate uspostaviti vezu s bazom podataka. Budući da sam naveo your_database_name
u .env konfiguraciji gore, mogu kliknuti "create" i phpMyAdmin će izgraditi praznu bazu podataka.

U Git bash, dođite do cd-a u project_name
direktorij i pokrenite donju naredbu:
cd project_name php artisan migrate
Ovo će pokretati sve zadane migracije Laravela u našoj aplikaciji sve dok ste stvorili podudarnost DB_DATABASE
koju smo kreirali gore.
php artisan serve
Sada možemo pokrenuti naš razvojni poslužitelj:

Stvaranje datoteke contact.blade.php
Postavite stranicu s kontaktima u mapi resursi> prikazi poput ove:
@extends('layouts.client.app') @section('content') Contact Us
@if(session('status')) Success ! {{ session('status') }} × @endif @endsection
Gornji isječak koda proširit će datoteku izgleda koja sadrži odjeljak zaglavlja. Sadrži i naslov odjeljka "Kontaktirajte nas", zajedno s porukom koja je vraćena i prikazana Korisniku ako i samo ako je poštanska poruka uspješno poslana.
Ovdje je glavni fokus na odjeljku obrasca koji možete vidjeti u sljedećem isječku koda:
@csrf {{ __('Full Name') }} firstname) ? Auth::user()->firstname : '' }} {{ isset(Auth::user()->lastname) ? Auth::user()->lastname : '' }}" required autocomplete="Fullname" autofocus> @error('fullname') {{ $message }} @enderror {{ __('Email Address') }} email) ? Auth::user()->email : '' }}" required autocomplete="email" autofocus> @error('email') {{ $message }} @enderror {{ __('Phone Number') }} phone_number) ? Auth::user()->phone_number : '' }}" required autocomplete="phone_number" autofocus> @error('phone_number') {{ $message }} @enderror {{ __('Subject') }} @error('subject') {{ $message }} @enderror {{ __('Message') }} @error('message') {{ $message }} @enderror {{ __('Attach Screenshot') }} {{ __('Send Message') }}
Isječak gore sadrži različita polja za unos koja ćemo koristiti u obradi korisničkih podataka. Polja uključuju PUNO IME, E-MAIL ADRESU, BROJ TELEFONA, PREDMET ili SVRHA, PORUKA, UČITAJ SLIKU (ako postoji) i na kraju gumb POŠALJI PORUKU za obradu predaje obrasca.
Dalje ćemo spojiti oba isječka koda kako bismo ih učinili puno značajnijima.
@extends('layouts.client.app') @section('content') Contact Us
@if(session('status')) Success ! {{ session('status') }} × @endif @csrf {{ __('Full Name') }} firstname) ? Auth::user()->firstname : '' }} {{ isset(Auth::user()->lastname) ? Auth::user()->lastname : '' }}" required autocomplete="Fullname" autofocus> @error('fullname') {{ $message }} @enderror {{ __('Email Address') }} email) ? Auth::user()->email : '' }}" required autocomplete="email" autofocus> @error('email') {{ $message }} @enderror {{ __('Phone Number') }} phone_number) ? Auth::user()->phone_number : '' }}" required autocomplete="phone_number" autofocus> @error('phone_number') {{ $message }} @enderror {{ __('Subject') }} @error('subject') {{ $message }} @enderror {{ __('Message') }} @error('message') {{ $message }} @enderror {{ __('Attach Screenshot') }} {{ __('Send Message') }} @endsection
Slika u nastavku predstavlja jednostavan izgled stranice s kontaktima koja trenutno izgleda.

Dodajte rute kako biste omogućili GET & POST zahtjeve
Prvo ćemo postaviti rute u rute> web.php kako bismo stranicu s kontaktima generirali putem GET zahtjeva i poslali e-poštu putem zahtjeva POST (koji je naveden u atributu obrasca gore).
Route::get('/contact', '[email protected]')->name('contact'); Route::post('/contact', '[email protected]_mail')->name('addContact');
Dodavanje logike unutar HomeControllera
U aplikaciji> Http> Kontroleri, skela Laravel generirala je HomeController.
The Controller file is where the logic of the application resides. Laravel Scaffold already generated the default HomeController. So we will make do with that and create a function named
index
. We will use it to render the contact us page each time the user visits the route or URL in the application.
validate($request, [ 'fullname' => ['required', 'string', 'max:255' ], 'email' => ['required', 'string', 'email', 'max:255' ], 'phone_number' => ['string', 'max:255'], 'subject' => ['required', 'string', 'max:255'], 'message' => ['required', 'string', 'max:255'] ]); $contact = [ 'fullname' => $request['fullname'], 'email' => $request['email'], 'phone_number' => $request['phone_number'], 'subject' => $request['subject'], 'message' => $request['message'], 'screenshot' => $request->file('screenshot')->store('contact', 'public') ]; Mail::to('[email protected]')->send(new ContactFormMail($contact)); return redirect()->route('contact')->with('status', 'Your Mail has been received'); } }
In the same HomeController, we need to create another function named
send_mail
. The function will validate all user input and check to make sure fields are not left empty and the right data is parsed.
Next create a variable called
$create
to store the array values of all user data including image uploads.
Laravel ships with a filesystem that lets us work with images easily. The
Mail::to(....)
and send
ship with Illuminate\Support\Facade which I included at the top of the snippet. I have also included a Mailable, which I will explain soon.
We now need to alert users when the message has been dispatched and redirect them.
Bringing the code snippets together now will make the HomeController look somewhat like this:
validate($request, [ 'fullname' => ['required', 'string', 'max:255' ], 'email' => ['required', 'string', 'email', 'max:255' ], 'phone_number' => ['string', 'max:255'], 'subject' => ['required', 'string', 'max:255'], 'message' => ['required', 'string', 'max:255'] ]); $contact = [ 'fullname' => $request['fullname'], 'email' => $request['email'], 'phone_number' => $request['phone_number'], 'subject' => $request['subject'], 'message' => $request['message'], 'screenshot' => $request->file('screenshot')->store('contact', 'public') ]; Mail::to('[email protected]')->send(new ContactFormMail($contact)); return redirect()->route('contact')->with('status', ' Your Mail has been received'); } }
Having merged both of the above functions, we are done with the logic for the HomeController. Now let's proceed to the next step.
Generating Laravel Mailable
Each mail sent within the Laravel application is represented as a "mailable" just in case you're wondering about the name. Let's create a markdown mailable for contact information that we want to process:
php artisan make:mail ContactFormMail --markdown=template.client.contactform
The command above will generate a markdown file in the resources > views > template > client directory and also create a mailable file in app > Mail > ContactFormMail.php.
In ContactFormMail.php we have the following code snippet that lets us send mails without an attachment:
user = $data; } /** * Build the message. * * @return $this */ public function build() { return $this->from('[email protected]') ->markdown('template.client.contactform') ->with([ 'subject' => $this->user['subject'], 'message' => $this->user['message'], 'email' => $this->user['email'], 'phone_number' => $this->user['phone_number'], 'fullname' => $this->user['fullname'], ]); } }
Let's break this code down a bit.
In the
_construct
method I'm parsing all user data as a parameter and reassigning it. In the build
method, all of the mailable class configuration is done.
The
from
Method specifies the mail sender, that is who the mail is coming from (in my case [email protected]).
The
with
Method lets you choose to customize how mails will be rendered to the markdown which was generated. In this article we will assign all the fields to key and value pairs within the array so that within the markdown we can access each value with its own unique key.
The
markdown
Method accepts the name the of markdown template to be rendered with an optional data parameter (if we weren't making use of the with
method).
And lastly, the
to
Method specifies the recipient of the mail. In the HomeController above, change '[email protected]' to the actual recipient's address.
Add Data to the Markdown File
Now we need to configure the markdown file in the resources > views > template > client directory. Since we have key value pairs in place already, it's easier to reference with keys in the markdown file as shown below:
@component('mail::message') # {{$subject}} ## {{$message}} Feel free to contact me via {{$phone}} or {{$email}} Thanks,
{{$fullname}} {{ config('app.name') }} @endcomponent
U ovom smo trenutku gotovo gotovi ???. Svaka čast na praćenju ovog procesa. Sada ste naučili kako poslati e-poštu bez privitka. Sada pogledajmo kako to učiniti s privitkom.
Slanje pošte s privitkom
Laravel već isporučuje snažni datotečni sustav, pa slanje mailova s privitkom nije preteško. Iskoristit ćemo ovu značajku i stvoriti pohranu za korisnike u koju ćemo pohraniti njihove priložene datoteke unutar aplikacije.
php artisan storage:link
NAPOMENA : U gore navedenom HomeControlleru već sam odredio direktorij za pohranu za prijenose. To biste trebali učiniti stvaranjem mape (koja se naziva kontakt ) u pohrani> aplikacija> javni> kontakt .
Also in the config > filesystems.php check and make sure the default filesystem disk is set to return ['default' => 'public']
.
Now the ContactFormMail.php looks like this. We are now able to use the attachFromStorage
method which makes reference to the filepath.
user = $data; } /** * Build the message. * * @return $this */ public function build() { return $this->from('[email protected]') ->markdown('template.client.contactform') ->attachFromStorage($this->user['screenshot']) ->with([ 'subject' => $this->user['subject'], 'message' => $this->user['message'], 'email' => $this->user['email'], 'phone_number' => $this->user['phone_number'], 'fullname' => $this->user['fullname'] ]); } }
The only addition here will be attachFromStorage. It is used to process the attached files (either image or pdf) during the entire mailing process.
In the markdown file that we earlier used, we can slightly rework it to look like what's shown below:
{{$subject}}
{{$message}}
You can reach me via mail or telephone : {{$email}} or {{$phone_number}}
Thanks

Yaaay we can now do a happy dance because we're finally done ?????
via GIPHY
Now that you've made it through the entire article, you should be able to implement a similar emailing feature in your Laravel applications.
To learn more you can check out the official Laravel documentation here.