›
byrcsc/laravel-mentions · 1.x
Create a comment that mentions a user and query both sides of the relation.
By the end of this tutorial, saving a comment that contains @jane creates a
mention you can query from either the comment or Jane. Start with the package
installed, its migration applied, and the User lookup from installation.
Generate a model and migration:
php artisan make:model Comment -mCreate a body column in the generated migration:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::create('comments', function (Blueprint $table): void {
$table->id();
$table->text('body');
$table->timestamps();
});Run the migration:
php artisan migrateAdd HasMentions and list the model attributes that contain mention text:
namespace App\Models;
use Byrcsc\Mentions\Concerns\HasMentions;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
use HasMentions;
protected $guarded = [];
/** @var list<string> */
protected array $mentionableAttributes = ['body'];
}HasMentions listens to the model's saved event. It scans body after each
save while automatic synchronization is enabled.
Create Jane before saving text that mentions her:
use App\Models\Comment;
use App\Models\User;
$jane = User::query()->create([
'name' => 'jane',
'email' => 'jane@example.test',
'password' => bcrypt('password'),
]);
$comment = Comment::query()->create([
'body' => 'Thanks @jane, can you review this?',
]);Saving the comment creates one mention row. Synchronization skips unknown handles instead of storing them with a null target.
Load the target models named by the comment:
$targets = $comment->mentioned();
$targets->first()->is($jane); // trueLoad the underlying records and their target relation:
$mentions = $comment->mentions()->with('target')->get();Query from Jane back to the source:
$mentions = $jane->mentionedIn()->with('source')->get();
$comments = Comment::query()->whereMentions($jane)->get();Update the text without @jane:
$comment->update([
'body' => 'Thanks, the review is complete.',
]);The next synchronization removes the mention row. Jane remains unchanged.