### Install Dependencies and Build Assets Source: https://context7.com/resend/resend-laravel-example/llms.txt Install PHP and JavaScript dependencies using Composer and npm, then build frontend assets with npm. This is the initial setup for the project. ```bash # 1. Install PHP and JS dependencies composer install && npm install # 2. Build frontend assets ``` ```bash npm run build ``` -------------------------------- ### Install Composer and NPM Dependencies Source: https://github.com/resend/resend-laravel-example/blob/main/README.md Run this command to install the necessary PHP and JavaScript dependencies for the Laravel project. ```bash composer install && npm install ``` -------------------------------- ### Bootstrap Environment and Generate Key Source: https://context7.com/resend/resend-laravel-example/llms.txt Bootstrap the environment by copying the example .env file and generating an application key. Ensure you have a .env file before proceeding. ```bash # 3. Bootstrap environment php -r "file_exists('.env') || copy('.env.example', '.env');" php artisan key:generate --ansi ``` -------------------------------- ### Create .env File Source: https://github.com/resend/resend-laravel-example/blob/main/README.md This command copies the example environment file to .env if it doesn't already exist, which is used for application configuration. ```bash php -r "file_exists('.env') || copy('.env.example', '.env');" ``` -------------------------------- ### Serve Laravel Application Source: https://github.com/resend/resend-laravel-example/blob/main/README.md Starts the local development server for your Laravel application, making it accessible via a URL. ```bash php artisan serve ``` -------------------------------- ### Start All Services Concurrently Source: https://context7.com/resend/resend-laravel-example/llms.txt Start all development services, including the web server, queue worker, log viewer, and Vite HMR. This command runs multiple processes simultaneously. ```bash # 6. Start all services concurrently (server + queue + logs + vite) composer run dev # Equivalent to: # php artisan serve → http://localhost:8000 # php artisan queue:listen → processes email jobs # php artisan pail → log viewer # npm run dev → Vite HMR ``` -------------------------------- ### ChirpCreated Event Class Source: https://context7.com/resend/resend-laravel-example/llms.txt A simple Dispatchable event that carries the newly created Chirp model to listeners. The example shows the event constructor and how it can be manually dispatched (though not needed in the normal flow). ```php // app/Events/ChirpCreated.php namespace App\Events; use App\Models\Chirp; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class ChirpCreated { use Dispatchable, SerializesModels; public function __construct(public Chirp $chirp) {} } // Manually dispatching the event (not needed in normal flow, handled by model) ChirpCreated::dispatch($chirp); ``` -------------------------------- ### Chirp Model - Dispatch Event on Creation Source: https://context7.com/resend/resend-laravel-example/llms.txt The Chirp model automatically dispatches the ChirpCreated event when a new Chirp is saved, decoupling email logic from controllers. Usage example shows creating a Chirp, which triggers the event. ```php // app/Models/Chirp.php namespace App\Models; use App\Events\ChirpCreated; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class Chirp extends Model { protected $fillable = ['message']; // Automatically dispatches ChirpCreated when a Chirp is created protected $dispatchesEvents = [ 'created' => ChirpCreated::class, ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } } // Usage: creating a Chirp (triggers event automatically) $chirp = $request->user()->chirps()->create([ 'message' => 'Hello Chirper world!', ]); // ChirpCreated event is now in the queue ``` -------------------------------- ### SendChirpCreatedNotifications Listener - Process Queued Jobs Source: https://context7.com/resend/resend-laravel-example/llms.txt This listener handles ChirpCreated events by sending notifications to users. It uses `cursor()` for memory efficiency with large user tables. The example also shows the command to process queued jobs. ```php // app/Listeners/SendChirpCreatedNotifications.php namespace App\Listeners; use App\Events\ChirpCreated; use App\Models\User; use App\Notifications\NewChirp; use Illuminate\Contracts\Queue\ShouldQueue; class SendChirpCreatedNotifications implements ShouldQueue { public function handle(ChirpCreated $event): void { // Send notification to every user except the chirp author foreach (User::whereNot('id', $event->chirp->user_id)->cursor() as $user) { $user->notify(new NewChirp($event->chirp)); } } } // Process queued jobs (run in a separate terminal): // php artisan queue:listen --tries=1 ``` -------------------------------- ### OrderShipped Mailable via Resend Source: https://context7.com/resend/resend-laravel-example/llms.txt A standard Laravel Mailable class for sending transactional emails with full API support, including envelope, content, and attachments, through Resend. This example demonstrates how to configure the email's subject, view, and attachments. Use `Mail::to(...)->send(...)` for immediate delivery or `Mail::to(...)->queue(...)` for asynchronous delivery. ```php // app/Mail/OrderShipped.php namespace App\Mail; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; class OrderShipped extends Mailable { public function __construct() {} public function envelope(): Envelope { return new Envelope(subject: 'Order Shipped'); } public function content(): Content { return new Content(view: 'emails.order-shipped'); } public function attachments(): array { return []; } } // Dispatching the mailable via Resend transport use Illuminate\Support\Facades\Mail; Mail::to('customer@example.com')->send(new OrderShipped()); // Or queue it for async delivery Mail::to('customer@example.com')->queue(new OrderShipped()); ``` -------------------------------- ### Build Frontend Assets Source: https://github.com/resend/resend-laravel-example/blob/main/README.md Execute this command to compile and build the Javascript and CSS files required for the frontend of the application. ```bash npm run build ``` -------------------------------- ### Run Database Migrations Source: https://context7.com/resend/resend-laravel-example/llms.txt Run database migrations to set up the necessary database schema. This command will automatically create the SQLite database if it doesn't exist. ```bash # 5. Run migrations (creates SQLite DB automatically) php artisan migrate ``` -------------------------------- ### Migrate Database Source: https://github.com/resend/resend-laravel-example/blob/main/README.md Applies pending database migrations to set up the necessary tables for the application. ```bash php artisan migrate ``` -------------------------------- ### Configure .env for Resend Source: https://context7.com/resend/resend-laravel-example/llms.txt Edit the .env file to add your Resend API key and configure mailer settings. This step is crucial for enabling Resend as the email driver. ```bash # 4. Edit .env — add your Resend API key # RESEND_API_KEY=re_xxxxxxxxxxxx # MAIL_MAILER=resend # MAIL_FROM_ADDRESS="noreply@yourdomain.com" ``` -------------------------------- ### Configure Resend as Mail Transport (.env) Source: https://context7.com/resend/resend-laravel-example/llms.txt Set MAIL_MAILER to 'resend' and provide your RESEND_API_KEY in the .env file to use Resend for sending emails. ```ini # .env APP_NAME=Resend APP_URL=http://localhost DB_CONNECTION=sqlite QUEUE_CONNECTION=database RESEND_API_KEY=re_your_api_key_here MAIL_MAILER=resend MAIL_FROM_ADDRESS="noreply@resend.dev" MAIL_FROM_NAME="${APP_NAME}" ``` -------------------------------- ### ChirpController Resource Routes and Actions Source: https://context7.com/resend/resend-laravel-example/llms.txt Defines RESTful resource routes for Chirps, requiring authentication and email verification. Includes store, update, and destroy actions with validation, event triggering, and authorization checks using Laravel's Gate/Policy system. Ensure ChirpPolicy is correctly implemented for authorization. ```php // routes/web.php Route::resource('chirps', ChirpController::class) ->only(['index', 'store', 'edit', 'update', 'destroy']) ->middleware(['auth', 'verified']); // app/Http/Controllers/ChirpController.php — store action public function store(Request $request): RedirectResponse { $validated = $request->validate([ 'message' => 'required|string|max:255', ]); // Creates chirp, triggers ChirpCreated event, emails all other users $request->user()->chirps()->create($validated); return redirect(route('chirps.index')); } // update action (owner-only via ChirpPolicy) public function update(Request $request, Chirp $chirp): RedirectResponse { Gate::authorize('update', $chirp); // fails for non-owners $validated = $request->validate([ 'message' => 'required|string|max:255', ]); $chirp->update($validated); return redirect(route('chirps.index')); } // destroy action public function destroy(Chirp $chirp): RedirectResponse { Gate::authorize('delete', $chirp); $chirp->delete(); return redirect(route('chirps.index')); } ``` -------------------------------- ### Generate Application Key Source: https://github.com/resend/resend-laravel-example/blob/main/README.md Generates a new application key for your Laravel project, essential for security and encryption. ```bash php artisan key:generate --ansi ``` -------------------------------- ### Database Migration for Chirps Table Source: https://context7.com/resend/resend-laravel-example/llms.txt Defines the database schema for the `chirps` table, including an auto-incrementing ID, a foreign key to the `users` table (`user_id`), a `message` column, and timestamps. The `cascadeOnDelete` option ensures that chirps are automatically removed when their associated user is deleted. ```php // database/migrations/2025_02_01_020926_create_chirps_table.php Schema::create('chirps', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->cascadeOnDelete(); $table->string('message'); $table->timestamps(); }); // Run migrations // php artisan migrate ``` -------------------------------- ### Register Resend Transport in config/mail.php Source: https://context7.com/resend/resend-laravel-example/llms.txt Register the 'resend' transport in the mailers array within config/mail.php to enable Laravel to route mail through Resend's API. ```php // config/mail.php 'default' => env('MAIL_MAILER', 'log'), 'mailers' => [ 'resend' => [ 'transport' => 'resend', ], // other mailers (smtp, ses, postmark, log, …) ], 'from' => [ 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), 'name' => env('MAIL_FROM_NAME', 'Example'), ], ``` -------------------------------- ### NewChirp Notification via Resend Source: https://context7.com/resend/resend-laravel-example/llms.txt A Laravel notification class that constructs a MailMessage for sending emails through the Resend transport. It includes dynamic subject and body content based on the chirp author and a truncated message preview. Ensure the 'mail' channel is configured to use the Resend transport. ```php // app/Notifications/NewChirp.php namespace App\Notifications; use App\Models\Chirp; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; use Illuminate\Support\Str; class NewChirp extends Notification { public function __construct(public Chirp $chirp) {} public function via(object $notifiable): array { return ['mail']; // routed through Resend transport } public function toMail(object $notifiable): MailMessage { return (new MailMessage()) ->subject("New Chirp from {$this->chirp->user->name}") ->greeting("New Chirp from {$this->chirp->user->name}") ->line(Str::limit($this->chirp->message, 50)) ->action('Go to Chirper', url('/')) ->line('Thank you for using our application!'); } } // Sending the notification directly (outside listener context) $user->notify(new NewChirp($chirp)); // Email delivered via Resend will appear in https://resend.com/emails ``` -------------------------------- ### ChirpPolicy Authorization Rules Source: https://context7.com/resend/resend-laravel-example/llms.txt Enforces authorization rules for Chirp model operations, ensuring only the chirp's author can update or delete it. Laravel automatically discovers this policy. The `update` method checks if the authenticated user is the author, and the `delete` method reuses the `update` logic. ```php // app/Policies/ChirpPolicy.php class ChirpPolicy { // Only the chirp's author may edit or delete it public function update(User $user, Chirp $chirp): bool { return $chirp->user()->is($user); } public function delete(User $user, Chirp $chirp): bool { return $this->update($user, $chirp); } } // Enforcement in controller Gate::authorize('update', $chirp); // throws AuthorizationException if not owner Gate::authorize('delete', $chirp); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.