PHP code example of hosnyadeeb / laravel-model-actions
1. Go to this page and download the library: Download hosnyadeeb/laravel-model-actions library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hosnyadeeb / laravel-model-actions example snippets
use App\Actions\User\UserIndexAction;
use App\Actions\User\UserShowAction;
use App\Actions\User\UserStoreAction;
use App\Actions\User\UserUpdateAction;
use App\Actions\User\UserDeleteAction;
// Index - Get paginated users
$users = UserIndexAction::run(perPage: 15);
// Index - Get all users without pagination
$allUsers = UserIndexAction::run(getAll: true);
// Index - With eager loading
$usersWithRoles = UserIndexAction::run(with: ['roles', 'permissions']);
// Show - Get single user
$user = UserShowAction::run(selectValue: '1');
// Store - Create new user
$newUser = UserStoreAction::run(data: [
'name' => 'John Doe',
'email' => '[email protected]',
'password' => bcrypt('password'),
]);
// Update - Update existing user
$updatedUser = UserUpdateAction::run(
data: ['name' => 'Jane Doe'],
selectValue: '1'
);
// Delete - Delete a user
$deleted = UserDeleteAction::run(selectValue: '1');
use App\Actions\User\UserIndexAction;
// Using the run() helper
$users = run(new UserIndexAction(perPage: 10));
// With multiple parameters
$user = run(new UserShowAction(
selectValue: '1',
with: ['roles', 'posts']
));
use App\Actions\User\UserIndexAction;
// Create instance and execute
$action = new UserIndexAction(perPage: 10);
$users = $action->execute();
// Or using invokable
$users = $action();
namespace App\Actions\User;
use App\Actions\_Base\IndexAction;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
final class UserIndexAction extends IndexAction
{
public function __construct(
private ?int $perPage = null,
private bool $getAll = false,
private ?string $orderKey = null,
private ?string $orderDir = null,
private array $select = [],
private array $with = [],
private array $withOut = [],
private array $where = [],
private array $request = [],
) {
parent::__construct(
model: new User(),
perPage: $this->perPage,
getAll: $this->getAll,
orderKey: $this->orderKey,
orderDir: $this->orderDir,
select: $this->select,
with: $this->with,
withOut: $this->withOut,
where: $this->where,
);
}
protected function customBuilder(Builder $builder): void
{
// Add search functionality
if ($search = $this->request['search'] ?? null) {
$builder->where(function ($q) use ($search) {
$q->where('name', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%");
});
}
// Filter by status
if ($status = $this->request['status'] ?? null) {
$builder->where('status', $status);
}
// Date range filter
if ($from = $this->request['from'] ?? null) {
$builder->whereDate('created_at', '>=', $from);
}
}
}
namespace App\Actions\User;
use App\Actions\_Base\StoreAction;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
final class UserStoreAction extends StoreAction
{
public function __construct(
private array $data
) {
parent::__construct(
model: new User(),
data: $this->data,
);
}
public function __invoke(): mixed
{
// Hash password before storing
if (isset($this->data['password'])) {
$this->data['password'] = Hash::make($this->data['password']);
}
// Create user
$user = User::create($this->data);
// Assign default role
$user->assignRole('user');
// Send welcome email
$user->notify(new WelcomeNotification());
return $user;
}
}
namespace App\Http\Controllers;
use App\Actions\User\UserIndexAction;
use App\Actions\User\UserShowAction;
use App\Actions\User\UserStoreAction;
use App\Actions\User\UserUpdateAction;
use App\Actions\User\UserDeleteAction;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(Request $request)
{
$users = UserIndexAction::run(
perPage: $request->input('per_page', 15),
with: ['roles'],
request: $request->all()
);
return response()->json($users);
}
public function show(string $id)
{
$user = UserShowAction::run(
selectValue: $id,
with: ['roles', 'permissions']
);
return response()->json($user);
}
public function store(Request $request)
{
$request->validate([
'name' => '
namespace App\Actions\User;
use App\Actions\_Base\StoreAction;
use App\Models\User;
use Illuminate\Support\Facades\Log;
final class UserStoreAction extends StoreAction
{
public function __construct(private array $data)
{
parent::__construct(model: new User(), data: $this->data);
}
/**
* Called before handle() executes.
*/
protected function before(): void
{
Log::info('Creating new user', ['email' => $this->data['email'] ?? null]);
}
/**
* Called after handle() executes successfully.
*/
protected function after(mixed $result): mixed
{
// Send welcome email
$result->notify(new WelcomeNotification());
// Log success
Log::info('User created successfully', ['id' => $result->id]);
return $result;
}
/**
* Called when an exception is thrown.
*/
protected function onError(\Throwable $e): void
{
Log::error('Failed to create user', [
'email' => $this->data['email'] ?? null,
'error' => $e->getMessage()
]);
}
}
namespace App\Actions\User;
use App\Actions\Action;
use App\Models\User;
use Illuminate\Support\Facades\Log;
final class UserActivateAction extends Action
{
public function __construct(
private int $userId,
private ?string $activatedBy = null
) {}
public function handle(): User
{
$user = User::findOrFail($this->userId);
$user->update([
'status' => 'active',
'activated_at' => now(),
'activated_by' => $this->activatedBy,
]);
return $user->fresh();
}
protected function before(): void
{
Log::info("Activating user {$this->userId}");
}
protected function after(mixed $result): mixed
{
// Send notification
$result->notify(new AccountActivatedNotification());
return $result;
}
}
namespace App\Actions\User;
use App\Actions\Action;
final class UserRegisterAction extends Action
{
public function __construct(
private array $userData,
private string $role = 'user'
) {}
public function handle(): array
{
// Create user
$user = UserStoreAction::run(data: $this->userData);
// Assign role
$user->assignRole($this->role);
// Create profile
$profile = ProfileStoreAction::run(data: [
'user_id' => $user->id,
]);
return compact('user', 'profile');
}
}
// Usage
$result = UserRegisterAction::run(
userData: ['name' => 'John', 'email' => '[email protected]'],
role: 'subscriber'
);
namespace App\Actions\User;
use App\Actions\Action;
use App\Models\User;
use HosnyAdeeb\ModelActions\Traits\Filterable;
final class UserSearchAction extends Action
{
use Filterable;
protected array $searchable = ['name', 'email', 'profile.bio'];
public function __construct(
private array $filters = []
) {
$this->setFilters($this->filters);
}
public function handle(): mixed
{
$query = User::query()->with('profile');
$this->applyFilters($query);
return $query->paginate(20);
}
}
namespace App\Actions\User;
use App\Actions\_Base\IndexAction;
use App\Models\User;
use HosnyAdeeb\ModelActions\Traits\Filterable;
final class UserIndexAction extends IndexAction
{
use Filterable;
// Columns that can be searched
protected array $searchable = ['name', 'email', 'profile.bio'];
// Default sorting
protected string $defaultSort = 'created_at';
protected string $defaultSortDirection = 'desc';
public function __construct(
private array $filters = [],
private ?int $perPage = null,
) {
parent::__construct(model: new User(), perPage: $this->perPage);
$this->setFilters($this->filters);
}
public function handle(): mixed
{
$query = User::query();
// Apply all filters (search, sort, date range, where conditions)
$this->applyFilters($query);
return $query->paginate($this->perPage ?? 20);
}
}
public function index(Request $request)
{
$users = UserIndexAction::run(
filters: $request->all(),
perPage: $request->input('per_page', 15)
);
return response()->json($users);
}