Skip to content
Laravel Packagev9.0.0MIT License

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.

Quick Tip

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, 8.1 or 8.2
  • Laravel 9.33 or newer within 9.x
  • pharaonic/laravel-has-files 9.x, which brings pharaonic/laravel-uploader for attachments (installed automatically)

#Composer Installation

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

Terminal
php artisan migrate

Set the table and connection options before you run it: the migration reads them. To copy the migration into database/migrations instead, publish it:

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

Terminal
php artisan vendor:publish --tag=messages-config

The pharaonic and laravel-messages tags publish both the configuration and the migration.

Upgrading from 1.x?

6.0.0 renames columns and changes send(). Read Upgrading from 1.x before you install it in an existing application.

Installation Complete

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.

config/pharaonic/messages.php
1return [
2 'table' => 'messages',
3 
4 'connection' => null,
5 
6 'attachment' => [
7 'disk' => null,
8 'path' => 'messages/attachments',
9 ],
10];
OptionDefaultDescription
tablemessagesThe table the migration creates and the Message model reads and writes.
connectionnullThe database connection of the table; null uses your default connection.
attachment.disknullThe disk new attachments are stored on; null uses Laravel Uploader's disk.
attachment.pathmessages/attachmentsThe directory of new attachments, under the Uploader's base path.
Set the table and connection first

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.

Attachments and connections

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:

app/Http/Controllers/ContactController.php
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(); // true
2$message->read_at; // Illuminate\Support\Carbon
3$message->markAsUnread(); // true

#Read the message attachment

The attachment is read through Has Files:

1$attachment = $message->file('attachment');
2 
3$attachment->exists(); // true
4$attachment->url; // the file URL
5$attachment->get(); // Pharaonic\Laravel\Files\Models\File, or null

See 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\Models\User
4$message->sender_type; // "App\Models\User"
5$message->sender_id; // 42

sender() 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"
Matching attribute names

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(); // true
4$attachment->url; // the file URL
5$attachment->mime; // "application/pdf"
6$attachment->size; // 48213
7$attachment->temporaryUrl(10); // a URL valid for 10 minutes, on disks that support them
8$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):

config/pharaonic/messages.php
1'attachment' => [
2 'disk' => 's3',
3 'path' => 'contact/attachments',
4],
Eager loading

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(); // true
2$message->isRead(); // true
3$message->read_at; // Illuminate\Support\Carbon
4 
5$message->markAsUnread(); // true
6$message->isUnread(); // true
7$message->read_at; // null

Both 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(); // 3
2Message::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()]);
Bulk updates

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:

app/Providers/EventServiceProvider.php
1use App\Listeners\NotifySupportTeam;
2use Pharaonic\Laravel\Messages\Events\MessageReceived;
3 
4protected $listen = [
5 MessageReceived::class => [
6 NotifySupportTeam::class,
7 ],
8];
app/Listeners/NotifySupportTeam.php
1namespace App\Listeners;
2 
3use App\Notifications\NewContactMessage;
4use App\Models\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});
Fake the event by name

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.x6.x
Pharaonic\Laravel\Messages\MessagePharaonic\Laravel\Messages\Models\Message
Message::send($request)Message::send($attributes, $sender, $attachment)
IP columnip
mobile_country_code columnmobile_code
has_read columnread_at timestamp, isRead(), read() and unread()
$message->attachment$message->file('attachment')
laravel/framework and Has Files 2.x or 3.xthe 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:

database/migrations/2026_12_01_000000_upgrade_messages_table.php
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.x
2use 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.x
2Message::send($request);
3 
4// 6.x
5$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.x
2Message::unread()->get(); // 6.x
3 
4$message->attachment; // 1.x
5$message->file('attachment')->url; // 6.x
Attachments stored by 1.x

Has 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->IP and $message->has_read read ip and isRead().
  • 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's throttle middleware or RateLimiter instead.

#API Reference

#Message model

Pharaonic\Laravel\Messages\Models\Message

MethodDescriptionReturns
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

ColumnTypeDescription
idbig integerPrimary key.
namestring, nullableSender name.
emailstring, nullableSender email.
mobile_codestring, nullableMobile country code.
mobile_numberstring, nullableMobile number.
subjectstring, nullableSubject.
messagetextThe message. Required.
ipstring, nullableThe IP you passed.
read_attimestamp, nullableWhen the message was first read; cast to Carbon.
sender_typestring, nullableMorph type of the sender.
sender_idstring, nullableKey of the sender.
created_at, updated_attimestamps

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

ClassPropertiesDispatched
Pharaonic\Laravel\Messages\Events\MessageReceived$messageBy send(), once the message and its attachment are stored.

#Configuration and publish tags

KeyDefault
pharaonic.messages.tablemessages
pharaonic.messages.connectionnull
pharaonic.messages.attachment.disknull
pharaonic.messages.attachment.pathmessages/attachments
TagPublishes
messages-config, pharaonic-configconfig/pharaonic/messages.php
messages-migrations, pharaonic-migrationsthe migration, into database/migrations
laravel-messages, pharaonicboth

#Deprecated

MemberUse instead
Message::messageable(Request $request, int $minutes = 10)Laravel's throttle middleware or RateLimiter
@messageable($minutes) Blade conditionLaravel'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.

routes/web.php
1use App\Http\Controllers\ContactController;
2 
3Route::get('/contact', [ContactController::class, 'create'])->name('contact');
4Route::post('/contact', [ContactController::class, 'store'])->middleware('throttle:3,10');
app/Http/Controllers/ContactController.php
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}
resources/views/contact.blade.php
1<form method="POST" action="/contact" enctype="multipart/form-data">
2 @csrf
3 <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:

app/Http/Controllers/Admin/MessageController.php
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:

app/Listeners/EmailSupport.php
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:

app/Http/Controllers/Portal/SupportController.php
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:

app/Models/Customer.php
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:

resources/views/admin/partials/nav.blade.php
1<a href="/admin/messages">
2 Messages
3 @if ($count = \Pharaonic\Laravel\Messages\Models\Message::unread()->count())
4 <span class="badge">{{ $count }}</span>
5 @endif
6</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!

Moamen Eltouny

@MoamenEltouny

64 contributions

Karim Mohamed

@komtcho

1 contribution

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?

Something wrong or missing? Report it on GitHub .