PHP code example of maskow / livewire-combined-request

1. Go to this page and download the library: Download maskow/livewire-combined-request 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/ */

    

maskow / livewire-combined-request example snippets


// API Controller
class UpdateTeamRequest extends FormRequest { /* rules here */ }

// Livewire Component  
public function save() {
    $this->validate([ /* same rules again! */ ]);
    // Manual authorization check...
    // Manual parameter handling...
}

// One request class for everything
class UpdateTeamRequest extends CombinedFormRequest {
    protected array $ere */ }
}

// API Controller
public function update(UpdateTeamRequest $request, Team $team) { /* automatic */ }

// Livewire Component
public function save() {
    $validated = UpdateTeamRequest::validateLivewire($this, [
        'team' => $this->team,
        'workspace' => $this->workspace
    ]);
}



namespace App\Http\Requests;

use Maskow\CombinedRequest\CombinedFormRequest;
use Illuminate\Support\Facades\Gate;

class UpdateTeamRequest extends CombinedFormRequest
{
    /**
     * Define which parameters this request    ];

    public function authorize(): bool
    {
        // Use parameter() to access both route parameters (HTTP) and injected parameters (Livewire)
        $team = $this->parameter('team');
        $workspace = $this->parameter('workspace');
        
        return Gate::allows('update', $team) && 
               $this->user()->can('access', $workspace);
    }

    public function rules(): array
    {
        $team = $this->parameter('team');
        
        return [
            'name' => ['



namespace App\Http\Controllers;

use App\Http\Requests\UpdateTeamRequest;
use App\Models\Team;
use App\Models\Workspace;

class TeamController extends Controller
{
    /**
     * Route: PUT /workspaces/{workspace}/teams/{team}
     */
    public function update(UpdateTeamRequest $request, Workspace $workspace, Team $team)
    {
        // Required parameters are automatically satisfied by route model binding
        // $request->parameter('team') === $team
        // $request->parameter('workspace') === $workspace
        
        $validated = $request->validated();
        $team->update($validated);
        
        return response()->json($team);
    }
}

// routes/api.php
Route::middleware('auth:sanctum')->group(function () {
    Route::put('/workspaces/{workspace}/teams/{team}', [TeamController::class, 'update']);
});



namespace App\Livewire;

use App\Http\Requests\UpdateTeamRequest;
use App\Models\Team;
use App\Models\Workspace;
use Livewire\Component;

class EditTeamForm extends Component
{
    public Team $team;
    public Workspace $workspace;
    
    // Public properties for the form
    public string $name = '';
    public string $description = '';
    public bool $is_public = false;

    public function mount(Team $team, Workspace $workspace)
    {
        $this->team = $team;
        $this->workspace = $workspace;
        $this->name = $team->name;
        $this->description = $team->description ?? '';
        $this->is_public = $team->is_public;
    }

    public function save()
    {
        try {
            // The same validation rules and authorization logic!
            $validated = UpdateTeamRequest::validateLivewire($this, [
                'team' => $this->team,
                'workspace' => $this->workspace,
            ]);

            $this->team->update($validated);
            
            session()->flash('message', 'Team updated successfully!');
            
        } catch (\InvalidArgumentException $e) {
            // Missing 

class CreateProjectRequest extends CombinedFormRequest
{
    protected array $ct  
        'user_id',      // Primitive value
        'template_id',  // Optional: can be null
    ];

    public function authorize()
    {
        $workspace = $this->parameter('workspace');
        $team = $this->parameter('team');
        $userId = $this->parameter('user_id');
        
        return $this->user()->can('createProject', [$workspace, $team]) &&
               $this->user()->id === $userId;
    }
}

// Works in both HTTP and Livewire contexts
$team = $this->parameter('team');
$workspace = $this->parameter('workspace');
$userId = $this->parameter('user_id', auth()->id()); // with default

// Check if parameter exists
if ($this->hasParameter('optional_param')) {
    // ...
}

// Get all parameters
$allParams = $this->parameters();

// Route: PUT /workspaces/{workspace}/teams/{team}
// Parameters 'workspace' and 'team' are automatically available via route model binding

// In your Livewire component
public function save()
{
    $validated = CreateProjectRequest::validateLivewire($this, [
        'workspace' => $this->workspace,
        'team' => $this->selectedTeam,
        'user_id' => auth()->id(),
        'template_id' => $this->selectedTemplate?->id,
    ]);
}

// Exception message:
// "Missing rs when calling fromLivewire() or ensure they exist in the route."

// In your AppServiceProvider boot() method:

use Maskow\CombinedRequest\CombinedFormRequest;

public function boot(): void
{
    CombinedFormRequest::notifyAuthorizationUsing(function ($component, string $message): void {
        // Show a toast notification, flash message, or dispatch an event
        Toast::error($component, 'Oops… Das hat nicht geklappt!', $message);
        
        // Or use Laravel's session flash:
        // session()->flash('error', $message);
        
        // Or dispatch a browser event:
        // $component->dispatch('notify', ['type' => 'error', 'message' => $message]);
    });
}

class UpdateTeamRequest extends CombinedFormRequest
{
    protected function prepareForValidation(): void
    {
        // Normalize data before validation
        $this->merge([
            'slug' => Str::slug($this->name),
            'email' => strtolower($this->email),
        ]);
        
        // Set default values
        if (! $this->has('is_public')) {
            $this->merge(['is_public' => false]);
        }
    }
}

class CreateProjectRequest extends CombinedFormRequest
{
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            if ($this->hasExceededProjectLimit()) {
                $validator->errors()->add('project', 'You have reached your project limit.');
            }
        });
    }
    
    private function hasExceededProjectLimit(): bool
    {
        return $this->user()->projects()->count() >= 10;
    }
}

class UploadDocumentRequest extends CombinedFormRequest
{
    protected function passedValidation(): void
    {
        // Log successful validation, track analytics, etc.
        activity()->log('Document upload validated');
    }
}

class UpdateTeamRequest extends CombinedFormRequest
{
    public function messages(): array
    {
        return [
            'name.
        return [
            'is_public' => 'visibility setting',
            'max_members' => 'maximum team size',
        ];
    }
}

// In app/Providers/AppServiceProvider.php

use Maskow\CombinedRequest\CombinedFormRequest;

public function boot(): void
{
    // Enable automatic camelCase to snake_case conversion
    CombinedFormRequest::convertCamelCaseToSnakeCase(true);
}



namespace App\Livewire;

use App\Http\Requests\UpdateUserProfileRequest;
use Livewire\Component;

class EditProfile extends Component
{
    // Component properties use camelCase (Livewire convention)
    public string $firstName = '';
    public string $lastName = '';
    public string $emailAddress = '';
    public bool $isSubscribed = false;

    public function save()
    {
        // Validation happens automatically with snake_case rules
        $validated = UpdateUserProfileRequest::validateLivewire($this);
        
        // $validated contains camelCase keys matching your properties
        auth()->user()->update($validated);
        
        session()->flash('message', 'Profile updated!');
    }

    public function render()
    {
        return view('livewire.edit-profile');
    }
}



namespace App\Http\Requests;

use Illuminate\Auth\Access\Response;
use Maskow\CombinedRequest\CombinedFormRequest;

class UpdateUserProfileRequest extends CombinedFormRequest
{
    public function authorize(): bool|Response
    {
        return Response::allow();
    }

    public function rules(): array
    {
        // Rules use snake_case (Laravel convention)
        return [
            'first_name'    => ['mail_address.email'    => 'Please enter a valid email address.',
        ];
    }
}

// Component property
public array $userInfo = [
    'firstName' => 'John',
    'lastName' => 'Doe',
];

// Validation rules (snake_case)
public function rules(): array
{
    return [
        'user_info'            => ['

// In app/Providers/AppServiceProvider.php

use Maskow\CombinedRequest\CombinedFormRequest;

public function boot(): void
{
    // Enable conversion
    CombinedFormRequest::convertCamelCaseToSnakeCase(true);
    
    // Keep validated data in snake_case for database operations
    CombinedFormRequest::returnValidatedDataAsSnakeCase(true);
}

// Livewire Component
class ChangeEntryBoardModal extends Component
{
    public Entry $entry;
    public $boardId;    // camelCase property
    public $listId;     // camelCase property

    public function updateBoard(): void
    {
        try {
            // Validate and get data in snake_case
            $data = UpdateEntryRequest::validateLivewire($this, ['entry' => $this->entry]);
            
            // $data now contains: ['board_id' => ..., 'list_id' => ...]
            // Perfect for direct database operations!
            $this->entry->update($data);
            
        } catch (ValidationException $e) {
            // Errors still reference camelCase: 'boardId', 'listId'
            throw $e;
        }
    }
}

// FormRequest
class UpdateEntryRequest extends CombinedFormRequest
{
    public function rules(): array
    {
        return [
            'board_id' => ['