Add Cross-Posting support for multiple social accounts

- Create post_social_account pivot table for many-to-many relationship
- Add migration to migrate existing social_account_id to pivot table
- Remove social_account_id column from posts table
- Update Post model with socialAccounts() BelongsToMany relationship
- Update Posts Livewire component to use array of selectedAccountIds
- Update Posts view with checkboxes for selecting multiple accounts
- Update PublishPostJob to iterate through all social accounts of matching type
- Update Publisher interface to accept optional SocialAccount parameter
- Update all Publishers (WordPress, Reddit, Twitter, LinkedIn) to support cross-posting
- Display multiple social accounts as badges in posts table

Now a single post can be published to multiple social accounts of the same type.
For example: a Twitter post can be published to multiple Twitter accounts.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
m105
2026-07-27 21:24:49 +03:00
parent 44f979820f
commit 90f313c134
12 changed files with 183 additions and 33 deletions
+44 -6
View File
@@ -21,7 +21,7 @@ class PublishPostJob implements ShouldQueue
public function handle(PublisherManager $publishers): void
{
$post = Post::with(['site', 'socialAccount'])->find($this->postId);
$post = Post::with(['site', 'socialAccounts'])->find($this->postId);
if (! $post) {
return;
@@ -34,6 +34,24 @@ class PublishPostJob implements ShouldQueue
return;
}
$results = [];
$errors = [];
$urls = [];
// Get all social accounts that match the post's type
$socialAccounts = $post->socialAccounts->filter(
fn ($account) => $account->network === $post->type
);
if ($socialAccounts->isEmpty()) {
$post->update([
'status' => 'draft',
'publish_error' => "No social accounts linked to this post for type '{$post->type}'.",
]);
return;
}
$publisher = $publishers->resolve($post);
if (! $publisher) {
@@ -42,19 +60,39 @@ class PublishPostJob implements ShouldQueue
return;
}
$result = $publisher->publish($post);
// Publish to each social account
foreach ($socialAccounts as $socialAccount) {
$result = $publisher->publish($post, $socialAccount);
$results[] = $result;
if ($result->success) {
$post->update(['status' => 'published', 'published_url' => $result->url, 'publish_error' => null]);
$urls[] = $result->url;
} else {
$errors[] = $result->error;
}
}
// If at least one succeeded, mark as published with the first URL
if (! empty($urls)) {
$post->update([
'status' => 'published',
'published_url' => $urls[0],
'publish_error' => ! empty($errors) ? implode('; ', $errors) : null,
]);
return;
}
// All failed
$post->update([
'status' => $result->attempted ? 'failed' : 'draft',
'publish_error' => $result->error,
'status' => 'failed',
'published_url' => null,
'publish_error' => implode('; ', $errors),
]);
Log::error('post publish failed', ['post_id' => $post->id, 'error' => $result->error]);
Log::error('post publish failed for all accounts', [
'post_id' => $post->id,
'errors' => $errors,
]);
}
}
+15 -8
View File
@@ -22,7 +22,7 @@ class Index extends Component
public string $siteId = '';
public string $socialAccountId = '';
public array $selectedAccountIds = [];
public string $type = '';
@@ -42,7 +42,7 @@ class Index extends Component
public function render()
{
$posts = Post::with(['site', 'socialAccount'])->orderByDesc('created_at')->get();
$posts = Post::with(['site', 'socialAccounts'])->orderByDesc('created_at')->get();
return view('livewire.posts.index', [
'posts' => $posts,
@@ -111,10 +111,10 @@ class Index extends Component
public function edit(int $id): void
{
$post = Post::findOrFail($id);
$post = Post::with('socialAccounts')->findOrFail($id);
$this->editingId = $post->id;
$this->siteId = (string) $post->site_id;
$this->socialAccountId = $post->social_account_id ? (string) $post->social_account_id : '';
$this->selectedAccountIds = $post->socialAccounts->pluck('id')->map(fn ($id) => (string) $id)->toArray();
$this->type = $post->type;
$this->title = (string) $post->title;
$this->body = $post->body;
@@ -129,7 +129,8 @@ class Index extends Component
{
$validated = $this->validate([
'siteId' => ['required', 'integer', 'exists:sites,id'],
'socialAccountId' => ['nullable', 'integer', 'exists:social_accounts,id'],
'selectedAccountIds' => ['array'],
'selectedAccountIds.*' => ['integer', 'exists:social_accounts,id'],
'type' => ['required', 'string', 'in:' . implode(',', Post::TYPES)],
'title' => ['nullable', 'string', 'max:255'],
'body' => ['required', 'string'],
@@ -139,9 +140,8 @@ class Index extends Component
'scheduledAt' => ['nullable', 'date'],
]);
Post::updateOrCreate(['id' => $this->editingId], [
$post = Post::updateOrCreate(['id' => $this->editingId], [
'site_id' => $validated['siteId'],
'social_account_id' => $validated['socialAccountId'] ?: null,
'type' => $validated['type'],
'title' => $validated['title'] ?: null,
'body' => $validated['body'],
@@ -151,6 +151,13 @@ class Index extends Component
'scheduled_at' => $validated['scheduledAt'] ?: null,
]);
// Sync social accounts using pivot table
if ($this->editingId) {
$post->socialAccounts()->sync($validated['selectedAccountIds'] ?: []);
} else {
$post->socialAccounts()->attach($validated['selectedAccountIds'] ?: []);
}
$this->resetForm();
$this->showForm = false;
}
@@ -165,7 +172,7 @@ class Index extends Component
$this->editingId = null;
$this->templateId = null;
$this->siteId = '';
$this->socialAccountId = '';
$this->selectedAccountIds = [];
$this->type = '';
$this->title = '';
$this->body = '';
+3 -3
View File
@@ -5,6 +5,7 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Post extends Model
{
@@ -19,7 +20,6 @@ class Post extends Model
protected $fillable = [
'site_id',
'social_account_id',
'type',
'title',
'body',
@@ -40,8 +40,8 @@ class Post extends Model
return $this->belongsTo(Site::class);
}
public function socialAccount(): BelongsTo
public function socialAccounts(): BelongsToMany
{
return $this->belongsTo(SocialAccount::class);
return $this->belongsToMany(SocialAccount::class, 'post_social_account');
}
}
+3 -2
View File
@@ -13,13 +13,14 @@ class LinkedInPublisher implements Publisher
return $post->type === 'linkedin';
}
public function publish(Post $post): PublishResult
public function publish(Post $post, ?SocialAccount $socialAccount = null): PublishResult
{
if (! $post->body) {
return PublishResult::rejected("Post {$post->id} has no body, required for a LinkedIn post.");
}
$account = $post->socialAccount;
// Use the passed social account, or fall back to the first linked one
$account = $socialAccount ?: $post->socialAccounts->first();
if (! $account || $account->network !== 'linkedin') {
return PublishResult::rejected("Post {$post->id} has no linked LinkedIn social account.");
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Support\Publishing;
use App\Models\Post;
use App\Models\SocialAccount;
interface Publisher
{
@@ -12,5 +13,5 @@ interface Publisher
*/
public function supports(Post $post): bool;
public function publish(Post $post): PublishResult;
public function publish(Post $post, ?SocialAccount $socialAccount = null): PublishResult;
}
+3 -2
View File
@@ -13,7 +13,7 @@ class RedditPublisher implements Publisher
return $post->type === 'reddit';
}
public function publish(Post $post): PublishResult
public function publish(Post $post, ?SocialAccount $socialAccount = null): PublishResult
{
if (! $post->title) {
return PublishResult::rejected("Post {$post->id} has no title, required for a Reddit post.");
@@ -23,7 +23,8 @@ class RedditPublisher implements Publisher
return PublishResult::rejected("Post {$post->id} has no target subreddit set.");
}
$account = $post->socialAccount;
// Use the passed social account, or fall back to the first linked one
$account = $socialAccount ?: $post->socialAccounts->first();
if (! $account || $account->network !== 'reddit') {
return PublishResult::rejected("Post {$post->id} has no linked Reddit social account.");
+3 -2
View File
@@ -13,13 +13,14 @@ class TwitterPublisher implements Publisher
return $post->type === 'twitter';
}
public function publish(Post $post): PublishResult
public function publish(Post $post, ?SocialAccount $socialAccount = null): PublishResult
{
if (! $post->body) {
return PublishResult::rejected("Post {$post->id} has no body, required for a Twitter post.");
}
$account = $post->socialAccount;
// Use the passed social account, or fall back to the first linked one
$account = $socialAccount ?: $post->socialAccounts->first();
if (! $account || $account->network !== 'twitter') {
return PublishResult::rejected("Post {$post->id} has no linked Twitter social account.");
@@ -14,7 +14,7 @@ class WordPressPublisher implements Publisher
return $post->type === 'blog';
}
public function publish(Post $post): PublishResult
public function publish(Post $post, ?SocialAccount $socialAccount = null): PublishResult
{
if (! $post->title) {
return PublishResult::rejected("Post {$post->id} has no title, required to publish to WordPress.");
@@ -0,0 +1,25 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('post_social_account', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
$table->foreignId('social_account_id')->constrained()->cascadeOnDelete();
$table->timestamps();
$table->unique(['post_id', 'social_account_id']);
});
}
public function down(): void
{
Schema::dropIfExists('post_social_account');
}
};
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// Copy existing social_account_id values to pivot table
DB::table('posts')
->whereNotNull('social_account_id')
->orderBy('id')
->chunk(100, function ($posts) {
$now = now();
foreach ($posts as $post) {
DB::table('post_social_account')->insert([
'post_id' => $post->id,
'social_account_id' => $post->social_account_id,
'created_at' => $now,
'updated_at' => $now,
]);
}
});
}
public function down(): void
{
// On rollback, we can't easily restore the social_account_id column
// since we'll remove it in the next migration. This is fine for a fresh setup.
}
};
@@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->dropForeign(['social_account_id']);
$table->dropColumn('social_account_id');
});
}
public function down(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('social_account_id')
->nullable()
->constrained('social_accounts')
->nullOnDelete();
});
}
};
+24 -7
View File
@@ -45,7 +45,17 @@
@endif
</td>
<td class="p-3">{{ $post->scheduled_at?->format('Y-m-d H:i') ?? '—' }}</td>
<td class="p-3">{{ $post->socialAccount?->username ?? '—' }}</td>
<td class="p-3">
@if ($post->socialAccounts->count() > 0)
<span class="flex flex-wrap gap-1">
@foreach ($post->socialAccounts as $account)
<span class="text-xs bg-blue-100 text-blue-800 px-2 py-0.5 rounded">{{ $account->username }}</span>
@endforeach
</span>
@else
<span class="text-gray-400">—</span>
@endif
</td>
<td class="p-3 text-right space-x-2">
@if (in_array($post->type, ['blog', 'reddit', 'twitter', 'linkedin']) && in_array($post->status, ['draft', 'scheduled', 'failed']))
<button wire:click="publish({{ $post->id }})" class="text-green-700">Publish</button>
@@ -90,14 +100,21 @@
</div>
<div>
<label class="block text-sm font-medium">Social Account (optional)</label>
<select wire:model="socialAccountId" class="w-full border rounded p-2">
<option value="">None</option>
<label class="block text-sm font-medium">Social Accounts (optional - select multiple for cross-posting)</label>
<div class="border border-gray-200 rounded p-2 max-h-32 overflow-y-auto bg-gray-50">
@foreach ($accounts as $account)
<option value="{{ $account->id }}">{{ $account->username }} ({{ ucfirst($account->network) }})</option>
<label class="flex items-center gap-2 p-1 hover:bg-white rounded cursor-pointer">
<input
type="checkbox"
wire:model="selectedAccountIds"
value="{{ $account->id }}"
class="h-4 w-4 rounded"
>
<span class="text-sm">{{ $account->username }} ({{ ucfirst($account->network) }})</span>
</label>
@endforeach
</select>
@error('socialAccountId') <span class="text-red-600 text-sm">{{ $message }}</span> @enderror
</div>
@error('selectedAccountIds') <span class="text-red-600 text-sm">{{ $message }}</span> @enderror
</div>
<div>