# Laravel Messages documentation (v7.x)

> Canonical: https://pharaonic.dev/packages/laravel/messages/7.x  
> Version: v7.x (latest release 7.0.0, 2026-11-29)  
> Install: composer require pharaonic/laravel-messages  
> Repository: https://github.com/Pharaonic/laravel-messages  
> All versions: https://pharaonic.dev/packages/laravel/messages/13.x.md https://pharaonic.dev/packages/laravel/messages/12.x.md https://pharaonic.dev/packages/laravel/messages/11.x.md https://pharaonic.dev/packages/laravel/messages/10.x.md https://pharaonic.dev/packages/laravel/messages/9.x.md https://pharaonic.dev/packages/laravel/messages/8.x.md https://pharaonic.dev/packages/laravel/messages/7.x.md https://pharaonic.dev/packages/laravel/messages/6.x.md

:::badges
- Laravel Package {color=blue}
- v7.0.0 {color=green}
- MIT License {color=purple}
:::

# 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](https://pharaonic.dev/packages/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.

:::features
### 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.
:::

:::info 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
- Laravel 7.30 or newer within 7.x
- `pharaonic/laravel-has-files` 7.x, which brings `pharaonic/laravel-uploader` for attachments (installed automatically)

### Composer Installation

```bash title="Terminal" no-line-numbers
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:

```bash title="Terminal" no-line-numbers
php artisan migrate
```

Set the [`table` and `connection` options](#configuration) before you run it: the migration reads them. To copy the migration into `database/migrations` instead, publish it:

```bash title="Terminal" no-line-numbers
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:

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=messages-config
```

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

:::warning Upgrading from 1.x?
6.0.0 renames columns and changes `send()`. Read [Upgrading from 1.x](#upgrading) before you install it in an existing application.
:::

:::success Installation Complete
You're all set! Store your first message in [Basic Usage](#basic-usage).
:::

## Configuration

The options live under `pharaonic.messages`. Publish `config/pharaonic/messages.php` with `--tag=messages-config` to change them.

```php title="config/pharaonic/messages.php"
return [
    'table' => 'messages',

    'connection' => null,

    'attachment' => [
        'disk' => null,
        'path' => 'messages/attachments',
    ],
];
```

| 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. |

:::warning 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.
:::

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

```php title="app/Http/Controllers/ContactController.php"
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Pharaonic\Laravel\Messages\Models\Message;

class ContactController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['nullable', 'string', 'max:255'],
            'email' => ['nullable', 'email'],
            'mobile_code' => ['nullable', 'string', 'max:8'],
            'mobile_number' => ['nullable', 'string', 'max:20'],
            'subject' => ['nullable', 'string', 'max:255'],
            'message' => ['required', 'string', 'max:5000'],
            'attachment' => ['nullable', 'file', 'max:5120'],
        ]);

        Message::send(
            Arr::except($data, 'attachment') + ['ip' => $request->ip()],
            $request->user(),
            $request->file('attachment')
        );

        return back()->with('status', 'Thank you, we will get back to you soon.');
    }
}
```

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

```php
$inbox = Message::unread()->latest()->paginate(20);

$message = Message::findOrFail($id);
$message->subject;     // "Partnership"
$message->ip;          // "203.0.113.7"
$message->isRead();    // false
```

### Mark a message as read

```php
$message->markAsRead();   // true
$message->read_at;        // Illuminate\Support\Carbon
$message->markAsUnread(); // true
```

### Read the message attachment

The attachment is read through Has Files:

```php
$attachment = $message->file('attachment');

$attachment->exists(); // true
$attachment->url;      // the file URL
$attachment->get();    // Pharaonic\Laravel\Files\Models\File, or null
```

See [Attachments](#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()`:

```php
$message = Message::send(['message' => 'Where is my order?'], $request->user());

$message->sender;      // App\User
$message->sender_type; // "App\User"
$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:

```php
$user = User::create(['name' => 'Raggi', 'email' => 'raggi@example.com']);

$message = Message::send(['message' => 'Hi', 'email' => null], $user);

$message->name;  // "Raggi"
$message->email; // "raggi@example.com"
```

Attributes you pass win over the sender's:

```php
Message::send(['message' => 'Hi', 'email' => 'work@example.com'], $user)->email; // "work@example.com"
```

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

```php
Message::send(['message' => 'Hi'], new User); // InvalidArgumentException
```

### Guests

Pass `null`, or leave the argument out, for a guest. The message then has no sender:

```php
$message = Message::send(['name' => 'Guest', 'email' => 'guest@example.com', 'message' => 'Hi']);

$message->sender; // null
```

## Attachments

Each contact form message has one optional `attachment`, declared through [Laravel Has Files](https://pharaonic.dev/packages/laravel/has-files) and stored by Laravel Uploader. Pass the uploaded file as the third argument of `send()`:

```php
$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:

```php
$request->validate([
    'attachment' => ['nullable', 'file', 'mimes:pdf,jpg,png', 'max:5120'],
]);
```

### Read it

`file('attachment')` returns the Has Files handler, even when the message has no attachment:

```php
$attachment = $message->file('attachment');

$attachment->exists();          // true
$attachment->url;               // the file URL
$attachment->mime;              // "application/pdf"
$attachment->size;              // 48213
$attachment->temporaryUrl(10);  // a URL valid for 10 minutes, on disks that support them
$attachment->get();             // Pharaonic\Laravel\Files\Models\File, or null
```

### Remove it

```php
$message->file('attachment')->remove();
```

### Where it is stored

New attachments go to the `attachment.disk` and `attachment.path` options (see [Configuration](#configuration)):

```php title="config/pharaonic/messages.php"
'attachment' => [
    'disk' => 's3',
    'path' => 'contact/attachments',
],
```

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

```php
$message->markAsRead();   // true
$message->isRead();       // true
$message->read_at;        // Illuminate\Support\Carbon

$message->markAsUnread(); // true
$message->isUnread();     // true
$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

```php
Message::unread()->count();               // 3
Message::read()->latest('read_at')->get();
Message::unread()->where('email', 'guest@example.com')->get();
```

### Mark many at once

The scopes return a query builder, so a bulk update works as usual:

```php
Message::unread()->whereKey($ids)->update(['read_at' => now()]);
```

:::info 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`:

```php title="app/Providers/EventServiceProvider.php"
use App\Listeners\NotifySupportTeam;
use Pharaonic\Laravel\Messages\Events\MessageReceived;

protected $listen = [
    MessageReceived::class => [
        NotifySupportTeam::class,
    ],
];
```

```php title="app/Listeners/NotifySupportTeam.php"
namespace App\Listeners;

use App\Notifications\NewContactMessage;
use App\User;
use Illuminate\Support\Facades\Notification;
use Pharaonic\Laravel\Messages\Events\MessageReceived;

class NotifySupportTeam
{
    public function handle(MessageReceived $event)
    {
        Notification::send(User::where('is_support', true)->get(), new NewContactMessage($event->message));
    }
}
```

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

```php
use Illuminate\Support\Facades\Event;
use Pharaonic\Laravel\Messages\Events\MessageReceived;

Event::fake([MessageReceived::class]);

$this->post('/contact', ['message' => 'Hi']);

Event::assertDispatched(MessageReceived::class, function (MessageReceived $event) {
    return $event->message->message === 'Hi';
});
```

:::warning 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.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:

```php title="database/migrations/2026_12_01_000000_upgrade_messages_table.php"
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class UpgradeMessagesTable extends Migration
{
    public function up()
    {
        DB::statement('alter table messages rename column "IP" to ip');
        DB::statement('alter table messages rename column mobile_country_code to mobile_code');

        Schema::table('messages', function (Blueprint $table) {
            $table->timestamp('read_at')->nullable();
        });

        DB::table('messages')->where('has_read', true)->update([
            'read_at' => DB::raw('coalesce(updated_at, created_at)'),
        ]);

        Schema::table('messages', function (Blueprint $table) {
            $table->dropColumn('has_read');
        });
    }
}
```

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

```php
use Pharaonic\Laravel\Messages\Message;        // 1.x
use 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:

```php
// 1.x
Message::send($request);

// 6.x
$data = $request->validate(['message' => ['required', 'string']]);

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

```php
Message::where('has_read', false)->get(); // 1.x
Message::unread()->get();                 // 6.x

$message->attachment;                     // 1.x
$message->file('attachment')->url;        // 6.x
```

:::warning 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`

| 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.

- ===Routes

  ```php title="routes/web.php"
  Route::get('/contact', 'ContactController@create')->name('contact');
  Route::post('/contact', 'ContactController@store')->middleware('throttle:3,10');
  ```

- ===Controller

  ```php title="app/Http/Controllers/ContactController.php"
  namespace App\Http\Controllers;

  use Illuminate\Http\Request;
  use Illuminate\Support\Arr;
  use Pharaonic\Laravel\Messages\Models\Message;

  class ContactController extends Controller
  {
      public function create()
      {
          return view('contact');
      }

      public function store(Request $request)
      {
          $data = $request->validate([
              'name' => ['required_without:email', 'nullable', 'string', 'max:255'],
              'email' => ['nullable', 'email'],
              'subject' => ['nullable', 'string', 'max:255'],
              'message' => ['required', 'string', 'max:5000'],
              'attachment' => ['nullable', 'file', 'mimes:pdf,jpg,png', 'max:5120'],
          ]);

          Message::send(
              Arr::except($data, 'attachment') + ['ip' => $request->ip()],
              $request->user(),
              $request->file('attachment')
          );

          return back()->with('status', 'Thank you, we will get back to you soon.');
      }
  }
  ```

- ===Blade View

  ```blade title="resources/views/contact.blade.php"
  <form method="POST" action="/contact" enctype="multipart/form-data">
      @csrf
      <input name="name" value="{{ old('name') }}">
      <input name="email" type="email" value="{{ old('email') }}">
      <input name="subject" value="{{ old('subject') }}">
      <textarea name="message">{{ old('message') }}</textarea>
      <input name="attachment" type="file">
      <button type="submit">Send</button>
  </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:

```php title="app/Http/Controllers/Admin/MessageController.php"
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Pharaonic\Laravel\Messages\Models\Message;

class MessageController extends Controller
{
    public function index()
    {
        return view('admin.messages.index', [
            'unread' => Message::unread()->with('files', 'sender')->latest()->get(),
            'read' => Message::read()->latest('read_at')->paginate(20),
        ]);
    }

    public function show(Message $message)
    {
        $message->markAsRead();

        return view('admin.messages.show', ['message' => $message]);
    }
}
```

### 3. Email the support team about new messages

Queue a mail for every new contact message:

```php title="app/Listeners/EmailSupport.php"
namespace App\Listeners;

use App\Mail\NewContactMessage;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
use Pharaonic\Laravel\Messages\Events\MessageReceived;

class EmailSupport implements ShouldQueue
{
    public function handle(MessageReceived $event)
    {
        Mail::to('support@example.com')->send(new NewContactMessage($event->message));
    }
}
```

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

```php title="app/Http/Controllers/Portal/SupportController.php"
Message::send(
    ['subject' => $data['subject'], 'message' => $data['message'], 'ip' => $request->ip()],
    $request->user('customer')
);
```

Give the customer model the inverse relation to list what each customer sent:

```php title="app/Customer.php"
use Pharaonic\Laravel\Messages\Models\Message;

public function messages()
{
    return $this->morphMany(Message::class, 'sender');
}
```

### 5. An unread messages badge

Show how many messages wait in the admin navigation:

```blade title="resources/views/admin/partials/nav.blade.php"
<a href="/admin/messages">
    Messages
    @if ($count = \Pharaonic\Laravel\Messages\Models\Message::unread()->count())
        <span class="badge">{{ $count }}</span>
    @endif
</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](#upgrading).

### 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')`.
