Created
June 18, 2024 10:54
-
-
Save perisicnikola37/e8947e6e2d055d42cc963c8244b20720 to your computer and use it in GitHub Desktop.
Action pattern in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Actions; | |
use App\Models\Team; | |
use App\Models\User; | |
class DeleteTeamAction | |
{ | |
public function handle(User $user, Team $team): void | |
{ | |
// Logic to handle deletion of the team | |
if ($user->can('delete', $team)) { | |
$team->delete(); | |
} else { | |
abort(403, 'Unauthorized action.'); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Requests; | |
use Illuminate\Foundation\Http\FormRequest; | |
class DeleteTeamRequest extends FormRequest | |
{ | |
public function authorize() | |
{ | |
return true; // Authorization is handled in DeleteTeamAction | |
} | |
public function rules() | |
{ | |
return [ | |
// Validation rules if needed | |
]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Models; | |
use Illuminate\Database\Eloquent\Model; | |
class Team extends Model | |
{ | |
protected $fillable = [ | |
'name', 'description', 'owner_id' | |
]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use App\Models\Team; | |
use App\Http\Requests\DeleteTeamRequest; | |
use App\Actions\DeleteTeamAction; | |
use Illuminate\Http\Response; | |
use Illuminate\Support\Facades\Redirect; | |
class TeamController extends Controller | |
{ | |
public function index() | |
{ | |
} | |
public function create() | |
{ | |
} | |
public function store() | |
{ | |
} | |
public function show() | |
{ | |
} | |
public function edit() | |
{ | |
} | |
public function update() | |
{ | |
} | |
public function destroy(DeleteTeamRequest $request, Team $team, DeleteTeamAction $action): Response | |
{ | |
$action->handle($request->user(), $team); | |
return Redirect::route('dashboard'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment