Laravel Messages
Messages is a Laravel contact form package: it stores the contact-us messages visitors and signed-in users send, with an optional attachment, and gives your team a read and unread inbox. You validate the request, then call Message::send() with the validated attributes, the signed-in user (or nobody, for a guest) and an optional attachment. The message lands in one messages table, its attachment is stored through Laravel Has Files, and a MessageReceived event tells your application it arrived. Your team then reads the inbox with the unread() scope and marks messages as read.
One Call to Store
Pass the attributes you validated, the sender and the attachment; the message is saved in one transaction.
Guests or Signed-in Senders
A signed-in sender fills the name, email and mobile the form left out, and stays linked to the message.
Optional Attachment
One file per message, stored on the disk and in the directory you configure.
Read and Unread
Mark messages read or unread and list either kind; a read message keeps its first read time.
Received Event
MessageReceived is dispatched once the message and its attachment are stored.
Your Table, Your Connection
Choose the table and the database connection the messages live on.
Messages never reads the request for you: validate the form in your controller and pass only what you accepted, including the IP when you want to keep it.
#Installation
Install the package with Composer. Laravel discovers the service provider, and the migration runs with your own.
#Requirements
- PHP 8.0
- Laravel 6.20 or newer within 6.x
pharaonic/laravel-has-files6.x, which bringspharaonic/laravel-uploaderfor attachments (installed automatically)
#Composer Installation
composer require pharaonic/laravel-messages#Run Migrations
The package loads its migration automatically. migrate creates the messages table, next to the uploads and files tables of Laravel Uploader and Has Files:
php artisan migrateSet the table and connection options before you run it: the migration reads them. To copy the migration into database/migrations instead, publish it:
php artisan vendor:publish --tag=messages-migrations#Publish Configuration
Publish the configuration file to config/pharaonic/messages.php when you need to change a default:
php artisan vendor:publish --tag=messages-configThe pharaonic and laravel-messages tags publish both the configuration and the migration.
6.0.0 renames columns and changes send(). Read Upgrading from 1.x before you install it in an existing application.
You're all set! Store your first message in Basic Usage.
#Configuration
The options live under pharaonic.messages. Publish config/pharaonic/messages.php with --tag=messages-config to change them.
1return [ 2 'table' => 'messages', 3 4 'connection' => null, 5 6 'attachment' => [ 7 'disk' => null, 8 'path' => 'messages/attachments', 9 ],10];| Option | Default | Description |
|---|---|---|
table | messages | The table the migration creates and the Message model reads and writes. |
connection | null | The database connection of the table; null uses your default connection. |
attachment.disk | null | The disk new attachments are stored on; null uses Laravel Uploader's disk. |
attachment.path | messages/attachments | The directory of new attachments, under the Uploader's base path. |
The migration reads table and connection when it runs. Changing them afterwards points the model at another table, but does not move the one you already have.
Has Files writes a message's attachment in the same transaction as the message, so a message with an attachment must be on the connection Has Files uses (pharaonic.files.connection). Keep both options equal when you move messages to another connection.
Attachments already stored keep their disk and directory when you change attachment.disk or attachment.path; only new ones go to the new place.
#Basic Usage
#Store a contact form message
Validate the contact form, then pass the attributes you accepted to Message::send(). The second argument is the sender (the signed-in user, or null for a guest), and the third is the uploaded attachment:
1use Illuminate\Http\Request; 2use Illuminate\Support\Arr; 3use Pharaonic\Laravel\Messages\Models\Message; 4 5class ContactController extends Controller 6{ 7 public function store(Request $request) 8 { 9 $data = $request->validate([10 'name' => ['nullable', 'string', 'max:255'],11 'email' => ['nullable', 'email'],12 'mobile_code' => ['nullable', 'string', 'max:8'],13 'mobile_number' => ['nullable', 'string', 'max:20'],14 'subject' => ['nullable', 'string', 'max:255'],15 'message' => ['required', 'string', 'max:5000'],16 'attachment' => ['nullable', 'file', 'max:5120'],17 ]);18 19 Message::send(20 Arr::except($data, 'attachment') + ['ip' => $request->ip()],21 $request->user(),22 $request->file('attachment')23 );24 25 return back()->with('status', 'Thank you, we will get back to you soon.');26 }27}send() returns the stored Message. The message column is the only one that cannot be empty; every other attribute is optional.
#Read the contact inbox
The unread() and read() scopes filter messages by their read state:
1$inbox = Message::unread()->latest()->paginate(20);2 3$message = Message::findOrFail($id);4$message->subject; // "Partnership"5$message->ip; // "203.0.113.7"6$message->isRead(); // false#Mark a message as read
1$message->markAsRead(); // true2$message->read_at; // Illuminate\Support\Carbon3$message->markAsUnread(); // true#Read the message attachment
The attachment is read through Has Files:
1$attachment = $message->file('attachment');2 3$attachment->exists(); // true4$attachment->url; // the file URL5$attachment->get(); // Pharaonic\Laravel\Files\Models\File, or nullSee Attachments for everything the handler does.
#Senders
A message can come from a guest or from any saved Eloquent model, usually your signed-in user. Pass that model as the second argument of send():
1$message = Message::send(['message' => 'Where is my order?'], $request->user());2 3$message->sender; // App\User4$message->sender_type; // "App\User"5$message->sender_id; // 42sender() is a polymorphic morphTo relation, so the sender can be a user, a customer, a vendor, or any other model. sender_id is a string column, so integer, UUID and ULID keys all fit.
#Filled from the sender
When the attributes leave out name, email, mobile_code or mobile_number, or set them to null, send() copies them from the sender, so the inbox shows who wrote even when the form only had a message field:
1$user = User::create(['name' => 'Raggi', 'email' => 'raggi@example.com']);2 3$message = Message::send(['message' => 'Hi', 'email' => null], $user);4 5$message->name; // "Raggi"6$message->email; // "raggi@example.com"Attributes you pass win over the sender's:
1Message::send(['message' => 'Hi', 'email' => 'work@example.com'], $user)->email; // "work@example.com"The sender fills only the attributes it has under the same names: name, email, mobile_code and mobile_number. A sender without them leaves those columns empty.
#Unsaved senders
A sender that is not saved yet is refused with an InvalidArgumentException before anything is written:
1Message::send(['message' => 'Hi'], new User); // InvalidArgumentException#Guests
Pass null, or leave the argument out, for a guest. The message then has no sender:
1$message = Message::send(['name' => 'Guest', 'email' => 'guest@example.com', 'message' => 'Hi']);2 3$message->sender; // null#Attachments
Each contact form message has one optional attachment, declared through Laravel Has Files and stored by Laravel Uploader. Pass the uploaded file as the third argument of send():
1$message = Message::send(['message' => 'See attached'], null, $request->file('attachment'));The message and its attachment are saved in one database transaction.
#Validate the file
Validate the attachment in your request, as you do for the other fields. Messages accepts any file you pass, so the rules decide which types and sizes are allowed:
1$request->validate([2 'attachment' => ['nullable', 'file', 'mimes:pdf,jpg,png', 'max:5120'],3]);#Read it
file('attachment') returns the Has Files handler, even when the message has no attachment:
1$attachment = $message->file('attachment');2 3$attachment->exists(); // true4$attachment->url; // the file URL5$attachment->mime; // "application/pdf"6$attachment->size; // 482137$attachment->temporaryUrl(10); // a URL valid for 10 minutes, on disks that support them8$attachment->get(); // Pharaonic\Laravel\Files\Models\File, or null#Remove it
1$message->file('attachment')->remove();#Where it is stored
New attachments go to the attachment.disk and attachment.path options (see Configuration):
1'attachment' => [2 'disk' => 's3',3 'path' => 'contact/attachments',4],Load files with the messages you list, and each message reads its attachment without another query: Message::with('files')->latest()->get().
#Read State
A message is unread until someone marks it as read. The read_at column keeps when that happened.
#Mark messages
1$message->markAsRead(); // true2$message->isRead(); // true3$message->read_at; // Illuminate\Support\Carbon4 5$message->markAsUnread(); // true6$message->isUnread(); // true7$message->read_at; // nullBoth methods write only when the state changes. Marking a read message as read again returns true and keeps its first read time, so read_at always tells you when the message was first opened.
Both return false, and write nothing, for a message that is not saved.
#Query by state
1Message::unread()->count(); // 32Message::read()->latest('read_at')->get();3Message::unread()->where('email', 'guest@example.com')->get();#Mark many at once
The scopes return a query builder, so a bulk update works as usual:
1Message::unread()->whereKey($ids)->update(['read_at' => now()]);A bulk update() runs one query and skips the model, so it fires no model events. Use markAsRead() on each message when your application listens to them.
#Events
#MessageReceived
Use this event to notify your team, send an auto-reply or push the message to a help desk.
Pharaonic\Laravel\Messages\Events\MessageReceived is dispatched by Message::send(), once per message, after the message and its attachment are stored and their transaction committed. Its public $message property is the stored message.
Register a listener in your EventServiceProvider:
1use App\Listeners\NotifySupportTeam;2use Pharaonic\Laravel\Messages\Events\MessageReceived;3 4protected $listen = [5 MessageReceived::class => [6 NotifySupportTeam::class,7 ],8]; 1namespace App\Listeners; 2 3use App\Notifications\NewContactMessage; 4use App\User; 5use Illuminate\Support\Facades\Notification; 6use Pharaonic\Laravel\Messages\Events\MessageReceived; 7 8class NotifySupportTeam 9{10 public function handle(MessageReceived $event)11 {12 Notification::send(User::where('is_support', true)->get(), new NewContactMessage($event->message));13 }14}send() refuses an unsaved sender before it writes anything, and a failed write throws, so the event is never dispatched for a message that was not stored.
#Testing
Fake only this event, so the attachment is still stored through its model events:
1use Illuminate\Support\Facades\Event; 2use Pharaonic\Laravel\Messages\Events\MessageReceived; 3 4Event::fake([MessageReceived::class]); 5 6$this->post('/contact', ['message' => 'Hi']); 7 8Event::assertDispatched(MessageReceived::class, function (MessageReceived $event) { 9 return $event->message->message === 'Hi';10});Event::fake() without a list also fakes the model events Has Files uses to store attachments, so the attachment would not be saved in that test.
#Upgrading from 1.x
6.0.0 is the first release of the per-Laravel lines and changes the 1.x API. Plan the upgrade as a breaking one.
#What changed
| 1.x | 6.x |
|---|---|
Pharaonic\Laravel\Messages\Message | Pharaonic\Laravel\Messages\Models\Message |
Message::send($request) | Message::send($attributes, $sender, $attachment) |
IP column | ip |
mobile_country_code column | mobile_code |
has_read column | read_at timestamp, isRead(), read() and unread() |
$message->attachment | $message->file('attachment') |
laravel/framework and Has Files 2.x or 3.x | the illuminate/* components and Has Files 6.x |
#1. Convert the table
The package migration keeps its 1.x file name, so Laravel does not run it again on a table 1.x created. Convert that table with a migration of your own before you deploy 6.x. On PostgreSQL and SQLite:
1use Illuminate\Database\Migrations\Migration; 2use Illuminate\Database\Schema\Blueprint; 3use Illuminate\Support\Facades\DB; 4use Illuminate\Support\Facades\Schema; 5 6class UpgradeMessagesTable extends Migration 7{ 8 public function up() 9 {10 DB::statement('alter table messages rename column "IP" to ip');11 DB::statement('alter table messages rename column mobile_country_code to mobile_code');12 13 Schema::table('messages', function (Blueprint $table) {14 $table->timestamp('read_at')->nullable();15 });16 17 DB::table('messages')->where('has_read', true)->update([18 'read_at' => DB::raw('coalesce(updated_at, created_at)'),19 ]);20 21 Schema::table('messages', function (Blueprint $table) {22 $table->dropColumn('has_read');23 });24 }25}On MySQL 8, write the renames with backticks: rename column `IP` to `ip`. Before Laravel 10, dropColumn() on SQLite needs doctrine/dbal.
A read message gets its last update time as read_at, the closest value 1.x kept.
#2. Update the imports
1use Pharaonic\Laravel\Messages\Message; // 1.x2use Pharaonic\Laravel\Messages\Models\Message; // 6.x#3. Validate, then send
1.x read the request itself and let its input override the signed-in user's name and email. 6.x stores only what you pass:
1// 1.x2Message::send($request);3 4// 6.x5$data = $request->validate(['message' => ['required', 'string']]);6 7Message::send($data + ['ip' => $request->ip()], $request->user(), $request->file('attachment'));#4. Read state and attachments
Move queries on has_read to the scopes, and $message->attachment to the Has Files handler:
1Message::where('has_read', false)->get(); // 1.x2Message::unread()->get(); // 6.x3 4$message->attachment; // 1.x5$message->file('attachment')->url; // 6.xHas Files 6 is a redesign with no upgrade path from 3.x, so attachments stored by 1.x are not read by 6.x. Keep the old files table and storage if you still need them.
#Deprecated
These still work in 6.x and will be removed in a later breaking line:
$message->IPand$message->has_readreadipandisRead().Message::messageable($request, $minutes)and the@messageable($minutes)Blade condition check whether the request's IP sent a message in the last minutes. Throttle your contact route with Laravel'sthrottlemiddleware orRateLimiterinstead.
#API Reference
#Message model
Pharaonic\Laravel\Messages\Models\Message
| Method | Description | Returns |
|---|---|---|
Message::send(array $attributes, ?Model $sender = null, ?UploadedFile $attachment = null) | Stores a message, fills missing name, email, mobile_code and mobile_number from the sender, stores the attachment, then dispatches MessageReceived. Throws InvalidArgumentException for an unsaved sender. | Message |
sender() | The polymorphic sender relation. | MorphTo |
file('attachment') | The Has Files handler of the attachment. | SingleFile |
isRead() | Whether the message was read. | bool |
isUnread() | Whether the message was not read yet. | bool |
markAsRead() | Sets read_at on a saved message that was not read; keeps an existing read time. | bool (false when unsaved) |
markAsUnread() | Clears read_at on a saved message. | bool (false when unsaved) |
Message::read() | Scope: messages with a read_at. | Builder |
Message::unread() | Scope: messages without a read_at. | Builder |
#Columns
| Column | Type | Description |
|---|---|---|
id | big integer | Primary key. |
name | string, nullable | Sender name. |
email | string, nullable | Sender email. |
mobile_code | string, nullable | Mobile country code. |
mobile_number | string, nullable | Mobile number. |
subject | string, nullable | Subject. |
message | text | The message. Required. |
ip | string, nullable | The IP you passed. |
read_at | timestamp, nullable | When the message was first read; cast to Carbon. |
sender_type | string, nullable | Morph type of the sender. |
sender_id | string, nullable | Key of the sender. |
created_at, updated_at | timestamps |
name, email, mobile_code, mobile_number, subject, message, ip and attachment are fillable. sender_type, sender_id and read_at are not: the sender comes only from the send() argument, and the read state only from markAsRead() and markAsUnread().
#Event
| Class | Properties | Dispatched |
|---|---|---|
Pharaonic\Laravel\Messages\Events\MessageReceived | $message | By send(), once the message and its attachment are stored. |
#Configuration and publish tags
| Key | Default |
|---|---|
pharaonic.messages.table | messages |
pharaonic.messages.connection | null |
pharaonic.messages.attachment.disk | null |
pharaonic.messages.attachment.path | messages/attachments |
| Tag | Publishes |
|---|---|
messages-config, pharaonic-config | config/pharaonic/messages.php |
messages-migrations, pharaonic-migrations | the migration, into database/migrations |
laravel-messages, pharaonic | both |
#Deprecated
| Member | Use instead |
|---|---|
Message::messageable(Request $request, int $minutes = 10) | Laravel's throttle middleware or RateLimiter |
@messageable($minutes) Blade condition | Laravel's throttle middleware or RateLimiter |
$message->IP | $message->ip |
$message->has_read | $message->isRead() or read_at |
#Examples
#1. A Laravel contact form with an attachment
A throttled route, a controller that validates and sends, and a form with an attachment field.
1Route::get('/contact', 'ContactController@create')->name('contact');2Route::post('/contact', 'ContactController@store')->middleware('throttle:3,10'); 1namespace App\Http\Controllers; 2 3use Illuminate\Http\Request; 4use Illuminate\Support\Arr; 5use Pharaonic\Laravel\Messages\Models\Message; 6 7class ContactController extends Controller 8{ 9 public function create()10 {11 return view('contact');12 }13 14 public function store(Request $request)15 {16 $data = $request->validate([17 'name' => ['required_without:email', 'nullable', 'string', 'max:255'],18 'email' => ['nullable', 'email'],19 'subject' => ['nullable', 'string', 'max:255'],20 'message' => ['required', 'string', 'max:5000'],21 'attachment' => ['nullable', 'file', 'mimes:pdf,jpg,png', 'max:5120'],22 ]);23 24 Message::send(25 Arr::except($data, 'attachment') + ['ip' => $request->ip()],26 $request->user(),27 $request->file('attachment')28 );29 30 return back()->with('status', 'Thank you, we will get back to you soon.');31 }32}1<form method="POST" action="/contact" enctype="multipart/form-data">2 @csrf3 <input name="name" value="{{ old('name') }}">4 <input name="email" type="email" value="{{ old('email') }}">5 <input name="subject" value="{{ old('subject') }}">6 <textarea name="message">{{ old('message') }}</textarea>7 <input name="attachment" type="file">8 <button type="submit">Send</button>9</form>The throttle:3,10 middleware allows three messages per visitor every ten minutes.
#2. An admin inbox for contact messages
List unread messages first, and mark a message as read when it is opened:
1namespace App\Http\Controllers\Admin; 2 3use App\Http\Controllers\Controller; 4use Pharaonic\Laravel\Messages\Models\Message; 5 6class MessageController extends Controller 7{ 8 public function index() 9 {10 return view('admin.messages.index', [11 'unread' => Message::unread()->with('files', 'sender')->latest()->get(),12 'read' => Message::read()->latest('read_at')->paginate(20),13 ]);14 }15 16 public function show(Message $message)17 {18 $message->markAsRead();19 20 return view('admin.messages.show', ['message' => $message]);21 }22}#3. Email the support team about new messages
Queue a mail for every new contact message:
1namespace App\Listeners; 2 3use App\Mail\NewContactMessage; 4use Illuminate\Contracts\Queue\ShouldQueue; 5use Illuminate\Support\Facades\Mail; 6use Pharaonic\Laravel\Messages\Events\MessageReceived; 7 8class EmailSupport implements ShouldQueue 9{10 public function handle(MessageReceived $event)11 {12 Mail::to('support@example.com')->send(new NewContactMessage($event->message));13 }14}#4. Support messages from customers
Any saved model can be the sender. A customer portal passes the customer, whose name and email fill the form:
1Message::send(2 ['subject' => $data['subject'], 'message' => $data['message'], 'ip' => $request->ip()],3 $request->user('customer')4);Give the customer model the inverse relation to list what each customer sent:
1use Pharaonic\Laravel\Messages\Models\Message;2 3public function messages()4{5 return $this->morphMany(Message::class, 'sender');6}#5. An unread messages badge
Show how many messages wait in the admin navigation:
1<a href="/admin/messages">2 Messages3 @if ($count = \Pharaonic\Laravel\Messages\Models\Message::unread()->count())4 <span class="badge">{{ $count }}</span>5 @endif6</a>#Troubleshooting
#Column not found: ip, mobile_code or read_at
The table was created by 1.x, which named the columns IP, mobile_country_code and has_read. The package migration does not run again on an existing table: convert it as shown in Upgrading from 1.x.
#Table not found after changing the table or connection
The migration creates the table with the table and connection options it reads when it runs. Changing them afterwards points the model at a table that does not exist. Set them before php artisan migrate, or move the table yourself.
#The attachment is refused on another connection
Has Files stores attachments on its own connection (pharaonic.files.connection) and refuses a message on another one. Set pharaonic.messages.connection and pharaonic.files.connection to the same connection.
#The sender's name and email are empty
send() copies only name, email, mobile_code and mobile_number from the sender, by those exact attribute names. A user model with full_name or phone fills nothing: pass those values in the attributes instead.
#The attachment is not saved in a test
Event::fake() without a list fakes the model events Has Files saves attachments with. Fake only the event you assert: Event::fake([MessageReceived::class]).
#InvalidArgumentException: The sender of a message must be a saved model
The sender passed to send() has no row yet. Save it first, or pass null for a guest.
#$message->attachment is null
6.x reads the attachment through Has Files: use $message->file('attachment').
Contributors
Amazing people who made this package possible
This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Laravel Messages!
Want to Contribute?
We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.
Was this page helpful?
Thanks, that helps us decide what to improve.
Something wrong or missing? Report it on GitHub .