Recording Activities
Introduction
An activity records a verb and its participants. Storyfeed is a side effect, never the source: in application code, publish from your own domain events that implement Storyfeed\Contracts\PublishesToFeed, as Publishing From Events shows, and let business listeners subscribe to those events. The builder below is what toFeedActivity() returns; call publish() on it directly only for imports, backfills, console commands and one-offs.
Publishing Activities
Assign the activity's roles and call the publish method:
<?php
namespace App\Http\Controllers;
use App\Http\Requests\PlaceOrderRequest;
use App\Models\Shop;
use Illuminate\Http\RedirectResponse;
use Storyfeed\Facades\Storyfeed;
class OrderController extends Controller
{
public function store(
PlaceOrderRequest $request,
Shop $shop,
): RedirectResponse {
$order = $shop->orders()->create($request->validated());
Storyfeed::activity()
->by($request->user())
->action('place', $order)
->to($shop)
->publish();
return to_route('orders.show', $order);
}
}<?php
namespace App\Http\Controllers;
use App\Http\Requests\PlaceOrderRequest;
use App\Models\Shop;
use Illuminate\Http\RedirectResponse;
use Storyfeed\Facades\Storyfeed;
class OrderController extends Controller
{
public function store(
PlaceOrderRequest $request,
Shop $shop,
): RedirectResponse {
$order = $shop->orders()->create($request->validated());
Storyfeed::record(
verb: 'place',
object: $order,
actor: $request->user(),
target: $shop,
);
return to_route('orders.show', $order);
}
}The first argument to the action method is the verb, a string describing the action. This example records place. Define its headline in The Feed File.
You may also call the record method on the Storyfeed facade, passing each role as a named argument.
Assigning Roles
| Role | Meaning | Example |
|---|---|---|
actor | who performed the action | the customer |
object | the entity acted on | the order |
target | the entity the action was directed at | the shop |
context | the containing entity | the shop where the action occurred |
origin | the source | the source of an accepted invitation |
result | the entity produced | a receipt or generated file |
instrument | the tool or service used | the device used to take an order |
location | where the action happened | the mall the shop is in |
generator | the app or agent that produced the activity | the app the order was placed from |
Containers above the object, target or context come from each model's parent() declaration.
Choose the role based on the entity's involvement. A tablet is a target when an order is sent to it, or an instrument when used to take the order.
use Storyfeed\Facades\Storyfeed;
Storyfeed::activity()
->by($order->customer)
->action('place', $order)
->to($order->shop)
->at($order->shop->mall)
->generator('iOS app')
->publish();use Storyfeed\Facades\Storyfeed;
Storyfeed::record(
verb: 'place',
object: $order,
actor: $order->customer,
target: $order->shop,
location: $order->shop->mall,
generator: 'iOS app',
);NOTE
A role names a participant: a model, a party, or an entity without a model. A nonempty string passed to a role method creates or reuses a named party. Store names, email addresses, amounts, dates, and settings in activity data. Use a dynamic headline to display those values, or bind them to headline tokens. Recording Value Changes compares the roles, data, and party queries for a rename.
These roles come from W3C Activity Streams 2.0.
Role Aliases
Each role has a method with the same name, such as actor or object. The verb method sets the verb. You may also use these aliases:
| Alias | Sets | Meaning |
|---|---|---|
->by() | actor | who performed the action |
->action() | verb and object | the action and affected entity |
->using() | instrument | the tool or service used |
->at() | location | where the action happened |
->resulting() | result | the entity produced |
->to() ->for() ->on() ->with() ->into() ->in() ->from() | target | the entity the action was directed at |
Entities Without a Model
To fill a role with something your application has no model for, such as a delivery booked through a courier's API, pass an array with a type and a label:
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Storyfeed\Facades\Storyfeed;
class BookDeliveryController extends Controller
{
public function __invoke(Request $request, Order $order): RedirectResponse
{
$delivery = Http::post('https://courier.example/deliveries', [
'reference' => $order->reference,
])->json();
Storyfeed::activity()
->by($request->user())
->action('book', $order)
->resulting([
'type' => 'delivery',
'id' => $delivery['id'],
'label' => "Delivery {$delivery['id']}",
'url' => $delivery['tracking_url'],
])
->publish();
return back();
}
}<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Storyfeed\Facades\Storyfeed;
class BookDeliveryController extends Controller
{
public function __invoke(Request $request, Order $order): RedirectResponse
{
$delivery = Http::post('https://courier.example/deliveries', [
'reference' => $order->reference,
])->json();
Storyfeed::record(
verb: 'book',
object: $order,
actor: $request->user(),
result: [
'type' => 'delivery',
'id' => $delivery['id'],
'label' => "Delivery {$delivery['id']}",
'url' => $delivery['tracking_url'],
],
);
return back();
}
}use App\Models\Order;
use Storyfeed\Facades\Story;
Story::for(Order::class)->verb('book')->headline(':actor booked :result for :object');| Key | Holds |
|---|---|
type | the entity's type; required |
label | the entity's label; required |
id | an identifier of up to 36 printable ASCII characters, without spaces |
url | the entity's link |
data | values stored with the entity |
body | the entity's bodies |
media | the entity's pictures: icon, image and preview (each a URL), and initials and color for its avatar |
Storyfeed stores the entity with the activity, exactly as recorded: nothing refreshes it later. The activity's inlineEntity method returns the stored array for a role, such as $activity->inlineEntity('result'), or null when the role holds a model, a party, or nothing. See Entities for its payload.
Assigning the Actor
The actor is the user or model that performed the activity. You may specify the actor using the by method:
use Storyfeed\Facades\Storyfeed;
Storyfeed::activity()
->by($order->customer)
->action('place', $order)
->to($order->shop)
->publish();use Storyfeed\Facades\Storyfeed;
Storyfeed::record(
verb: 'place',
object: $order,
actor: $order->customer,
target: $order->shop,
);With the default configuration and no scoped or verb-specific actor, omitting by records the authenticated user, or no actor when nobody is signed in. Other sources can supply the actor; see Role Precedence.
Use by(null) to bypass default actor selection explicitly. An anonymous activity has no recorded actor.
Adding Activity Data
Use the data method to store arbitrary values on an activity. Storyfeed returns them in the activity’s data field:
<?php
namespace App\Http\Controllers;
use App\Models\MenuItem;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Storyfeed\Facades\Storyfeed;
class MenuItemPriceController extends Controller
{
public function update(Request $request, MenuItem $menuItem): RedirectResponse
{
$from = $menuItem->price;
$menuItem->update(['price' => $request->integer('price')]);
Storyfeed::activity()
->by($request->user())
->action('reprice', $menuItem)
->data(['from' => $from, 'to' => $menuItem->price])
->publish();
return back();
}
}<?php
namespace App\Http\Controllers;
use App\Models\MenuItem;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Storyfeed\Facades\Storyfeed;
class MenuItemPriceController extends Controller
{
public function update(Request $request, MenuItem $menuItem): RedirectResponse
{
$from = $menuItem->price;
$menuItem->update(['price' => $request->integer('price')]);
Storyfeed::record(
verb: 'reprice',
object: $menuItem,
actor: $request->user(),
data: ['from' => $from, 'to' => $menuItem->price],
);
return back();
}
}[
{
"kind": "activity",
"id": "a-price",
"verb": "reprice",
"published_at": "1985-07-02T11:00:00.000000Z",
"starts_at": null,
"ends_at": null,
"headline_template": ":actor changed the price of :object",
"headline": null,
"bindings": null,
"glyph": "tag",
"glyph_intent": null,
"actor": {
"type": "user",
"id": "101",
"label": "Steve Harrington",
"link": {
"href": "/users/101",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": {
"src": "/media/worlds/stranger-things/avatars/scooper.jpg",
"mediaType": "image/jpeg",
"width": 256,
"height": 256,
"alt": null
},
"image": null,
"preview": null,
"initials": null,
"color": null,
"files": [],
"slots": []
},
"media_ref": "md08aeb0f13f95241",
"entity_ref": "e6b153676d8dbc853",
"body": null,
"tombstone": null
},
"object": {
"type": "menu_item",
"id": "101",
"label": "USS Butterscotch",
"link": {
"href": "/menu/butterscotch",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": null,
"image": null,
"preview": null,
"initials": "UB",
"color": "#0f766e",
"files": [],
"slots": []
},
"media_ref": "mf5acd255ffaa7539",
"entity_ref": "e8f1e747924c2a5dc",
"body": null,
"tombstone": null
},
"target": {
"type": "venue",
"id": "101",
"label": "Scoops Ahoy",
"link": {
"href": "/venues/scoops",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": null,
"image": null,
"preview": {
"src": "/media/worlds/stranger-things/parlour.jpg",
"mediaType": "image/jpeg",
"width": 960,
"height": 720,
"alt": "An ice cream counter"
},
"initials": "SA",
"color": "#9f1239",
"files": [],
"slots": []
},
"media_ref": "m1bcad7c79ddfc05d",
"entity_ref": "e352bb6f37b7d8bfe",
"body": [
{
"$body": "Storyfeed/Body/Image",
"$v": 3,
"alt": "Scoops Ahoy",
"caption": "Scoops Ahoy",
"image": "preview"
}
],
"tombstone": null
},
"context": null,
"origin": null,
"result": null,
"instrument": null,
"location": null,
"generator": null,
"featured": "object",
"data": {
"from": 275,
"to": 295
},
"tombstoned": [],
"redundant": false,
"missing_headline_template": null,
"missing_headline": null
}
]NOTE
On MySQL, JSON object key order may differ from the order you wrote because native JSON columns normalise it.
Declare the verb and its headline in routes/feed.php:
use App\Models\MenuItem;
use Storyfeed\Facades\Story;
Story::for(MenuItem::class)->verb('reprice')
->headline(':actor changed the price of :object');Binding Literal Values
A headline that shows user-entered text, such as a recipient's name or a menu's new title, should never build its template by concatenating that text in. Storyfeed reads [...] in a template as an optional segment and :word as a token, so a name like Pat [x] or Specials :object would not print as entered. Name a token in the headline instead, and bind the value when recording:
use App\Models\Invoice;
use Storyfeed\Facades\Story;
Story::for(Invoice::class)->verb('send')
->headline(':actor sent :object to :recipient');Storyfeed::activity()
->by($request->user())
->action('send', $invoice)
->bind('recipient', $request->string('name'))
->publish();Storyfeed::record(
verb: 'send',
object: $invoice,
actor: $request->user(),
bind: ['recipient' => $request->string('name')],
);InvoiceActivity::Sent->by($request->user())
->object($invoice)
->bind('recipient', $request->string('name'))
->publish();The value prints exactly as entered: brackets, colons, backslashes, % and markup are text. It never enters the template, so nothing reads it again. The payload keeps :recipient in headline_template and carries the text in bindings, which renderers draw as plain text. FeedItem::bindings() reads the map.
bind() accepts a string, an integer, a float or a Stringable, and stores it as text. A binding name is lowercase letters only, as in :recipient. A name that is already a headline token throws an InvalidArgumentException: a role in the singular or plural (target, targets), count, others or verb. Binding the same name twice keeps the last value.
A group headline can use a bound token only when every member binds it to the same text; otherwise that value stays out of the group.
Binding at Render Time
A headline can also bind its values when the feed is read, storing nothing. Return FeedHeadline::make() from a headline closure and bind the value there:
use App\Models\Invoice;
use Storyfeed\ActivityContext;
use Storyfeed\Facades\Story;
use Storyfeed\FeedHeadline;
Story::for(Invoice::class)->verb('send')->headline(
fn (ActivityContext $c) => FeedHeadline::make(':actor sent :object to :recipient')
->bind('recipient', $c->object?->recipientName() ?? 'a customer'),
);FeedHeadline::make() takes a literal template, used as written. bind() returns a new headline that carries the value; the original is unchanged. A headline registered directly, without a closure, can carry bindings too:
Story::for(Invoice::class)->verb('send')
->headline(FeedHeadline::make(':actor sent :object to :recipient')->bind('recipient', 'accounts'));A render-time value reaches every place a stored one does: the payload bindings, the resolved headline, the PHP Headline reader and the Activity Streams summary. It prints exactly as given, so renderers draw it with no change. Nothing is written to the bindings column, so render-time binding needs no migration.
Merging With Stored Bindings
Render-time bindings merge with the bindings an activity stored with ->bind() when it was recorded. When both bind the same name, the render-time value wins. The other stored values stay as they were.
Groups
A group carries only the values every member holds with the same text, counting stored and render-time values together. A value that differs between members stays out of the group, and a group headline that needs it is null. A group headline closure that returns a bound FeedHeadline adds its own values to the group.
Choosing Render Time or Publish Time
Bind when publishing when the value belongs to the moment it happened: the name a user typed, a title before it was renamed. The stored value is the record, and it reads the same forever.
Bind at render time when the value must not, or cannot, be stored:
- A privacy rule. An app that may not keep a recipient's name in its activity log binds the name from the live model as the feed is read. Erase the name from the model, and it is gone from the feed too.
- Old stories. Activities recorded before a headline named a token never stored a value for it. A render-time binding fills it for every activity, old and new.
- Values that should follow the source, such as a current display name.
Name Rules
Render-time names follow the same rules as stored ones. A binding name is lowercase letters only. A role in the singular or plural (target, targets), count, others, verb or any name that isn't lowercase letters throws an InvalidArgumentException. Binding the same name twice keeps the last value.
Upgrading an Existing Install
Bindings are stored in a nullable bindings JSON column on feed_activities. New installs get it from the create_feed_activities_table migration. An install from before v0.24.0 publishes and runs the additive add_bindings_to_feed_activities_table migration before it binds anything:
php artisan vendor:publish --tag=storyfeed-migrations
php artisan migrateAn app that never binds can skip it; storyfeed:doctor doesn't require the column.
Setting the Publication Time
To set an earlier publication time, such as when importing records, call the publishedAt method:
<?php
namespace App\Console\Commands;
use App\Models\MenuItem;
use App\Models\User;
use Illuminate\Console\Command;
use Storyfeed\Facades\Storyfeed;
class ImportPriceHistory extends Command
{
protected $signature = 'menu:import-prices {file}';
public function handle(): void
{
$rows = json_decode(file_get_contents($this->argument('file')), true);
foreach ($rows as $row) {
Storyfeed::activity()
->by(User::findOrFail($row['user_id']))
->action('reprice', MenuItem::findOrFail($row['menu_item_id']))
->data(['from' => $row['from'], 'to' => $row['to']])
->publishedAt($row['changed_at'])
->publish();
}
}
}<?php
namespace App\Console\Commands;
use App\Models\MenuItem;
use App\Models\User;
use Illuminate\Console\Command;
use Storyfeed\Facades\Storyfeed;
class ImportPriceHistory extends Command
{
protected $signature = 'menu:import-prices {file}';
public function handle(): void
{
$rows = json_decode(file_get_contents($this->argument('file')), true);
foreach ($rows as $row) {
Storyfeed::record(
verb: 'reprice',
object: MenuItem::findOrFail($row['menu_item_id']),
actor: User::findOrFail($row['user_id']),
data: ['from' => $row['from'], 'to' => $row['to']],
publishedAt: $row['changed_at'],
);
}
}
}Recording a Time Range
When an activity describes something that spans a period, such as a closure or a meeting, record its start and end with the startsAt and endsAt methods:
<?php
namespace App\Http\Controllers;
use App\Models\Shop;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Storyfeed\Facades\Storyfeed;
class CloseShopController extends Controller
{
public function __invoke(Request $request, Shop $shop): RedirectResponse
{
$request->validate([
'from' => ['required', 'date'],
'until' => ['required', 'date', 'after_or_equal:from'],
]);
Storyfeed::activity()
->by($request->user())
->action('close', $shop)
->startsAt($request->date('from'))
->endsAt($request->date('until'))
->publish();
return back();
}
}<?php
namespace App\Http\Controllers;
use App\Models\Shop;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Storyfeed\Facades\Storyfeed;
class CloseShopController extends Controller
{
public function __invoke(Request $request, Shop $shop): RedirectResponse
{
$request->validate([
'from' => ['required', 'date'],
'until' => ['required', 'date', 'after_or_equal:from'],
]);
Storyfeed::record(
verb: 'close',
object: $shop,
actor: $request->user(),
startsAt: $request->date('from'),
endsAt: $request->date('until'),
);
return back();
}
}use App\Models\Shop;
use Storyfeed\Facades\Story;
Story::for(Shop::class)->verb('close')->headline(':actor closed :object');
Storyfeed returns the range in the activity's starts_at and ends_at fields. It is stored beside published_at, which still orders the feed. Either end may be left out for an open range, and an end before the start throws an InvalidArgumentException.
Recording Multiple Objects
To record an activity involving multiple objects, call the objects method. Storyfeed stores a parent activity and one activity per object. Define the verb once; the same definition covers the parent activity:
use Storyfeed\Facades\Story;
Story::verb('upload')->headline(':actor uploaded :object');Then publish the photos:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Storyfeed\Facades\Storyfeed;
class PhotoController extends Controller
{
public function store(Request $request): RedirectResponse
{
$photos = collect($request->file('photos'))->map(
fn (UploadedFile $file) => $request->user()->photos()->create([
'path' => $file->store('photos'),
]),
);
Storyfeed::activity()
->by($request->user())
->verb('upload')
->objects($photos)
->publish();
return back();
}
}<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Storyfeed\Facades\Storyfeed;
class PhotoController extends Controller
{
public function store(Request $request): RedirectResponse
{
$photos = collect($request->file('photos'))->map(
fn (UploadedFile $file) => $request->user()->photos()->create([
'path' => $file->store('photos'),
]),
);
Storyfeed::record(
verb: 'upload',
objects: $photos,
actor: $request->user(),
);
return back();
}
}See Composites for how these activities appear in the feed and how to define their headlines.
Featuring Another Role
An activity features its object by default. To feature another role, call a featuring method:
use Storyfeed\Facades\Storyfeed;
Storyfeed::activity()
->by($order->customer)
->action('place', $order)
->to($order->shop)
->featuringTarget()
->publish();The activity's featured key names the role:
[
{
"kind": "activity",
"id": "j84",
"verb": "place",
"published_at": "1985-07-02T12:00:00.000000Z",
"starts_at": null,
"ends_at": null,
"headline_template": ":actor placed :object with :target",
"headline": null,
"bindings": null,
"glyph": "shopping-bag",
"glyph_intent": "pending",
"actor": {
"type": "user",
"id": "113",
"label": "Erica Sinclair",
"link": {
"href": "/users/113",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": {
"src": "/media/worlds/stranger-things/avatars/scout.jpg",
"mediaType": "image/jpeg",
"width": 256,
"height": 256,
"alt": null
},
"image": null,
"preview": null,
"initials": null,
"color": null,
"files": [],
"slots": []
},
"media_ref": "maa7c0cfb07af83e2",
"entity_ref": "ebe52ab4d5e63692e",
"body": null,
"tombstone": null
},
"object": {
"type": "order",
"id": "1035",
"label": "Order #1035",
"link": {
"href": "/orders/1035",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": null,
"image": null,
"preview": null,
"initials": "O1",
"color": "#4d7c0f",
"files": [],
"slots": []
},
"media_ref": "ma9527581042280f7",
"entity_ref": "e722f0b114fd1ec13",
"body": null,
"tombstone": null
},
"target": {
"type": "venue",
"id": "101",
"label": "Scoops Ahoy",
"link": {
"href": "/venues/scoops",
"modal": false,
"attributes": []
},
"data": [],
"media": {
"icon": null,
"image": null,
"preview": {
"src": "/media/worlds/stranger-things/parlour.jpg",
"mediaType": "image/jpeg",
"width": 960,
"height": 720,
"alt": "An ice cream counter"
},
"initials": "SA",
"color": "#9f1239",
"files": [],
"slots": []
},
"media_ref": "m1bcad7c79ddfc05d",
"entity_ref": "e352bb6f37b7d8bfe",
"body": [
{
"$body": "Storyfeed/Body/Image",
"$v": 3,
"alt": "Scoops Ahoy",
"caption": "Scoops Ahoy",
"image": "preview"
}
],
"tombstone": null
},
"context": null,
"origin": null,
"result": null,
"instrument": null,
"location": null,
"generator": null,
"featured": "target",
"data": null,
"tombstoned": [],
"redundant": false,
"missing_headline_template": null,
"missing_headline": null
}
]| Method | Features |
|---|---|
featuringObject() | the object; the default, to undo an earlier call |
featuringActor(), featuringTarget(), featuringOrigin(), featuringResult(), featuringInstrument(), featuringLocation(), featuringGenerator() | that role's entity |
withoutFeature() | no entity: featured is null; bodies in the activity's own data remain |
A context is never featured. Featuring a role other than the object that the activity leaves empty throws IncompleteActivity when the activity is recorded. If the featured entity is missing when the feed is read, the activity still appears.
To set a verb's default, call the same method in the feed file. An activity's own call wins:
use App\Models\Order;
use Storyfeed\Facades\Story;
Story::for(Order::class)
->verb('place')
->headline(':actor placed :object with :target')
->featuringTarget();Verb enums accept the same methods.