Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kbuczynski's avatar

Requesting Modal HTML with Ajax how to handle

Hi I wonder about how should I restructure my controllers. Each time I try to edit or remove something an ajax is fired to fetch modal HTML onto my page which is generated using PHP.

I wonder whats the best way to handle/structure the controllers. Should I move all the ajax request for modal to its own controllers or leave it where they are

this is an example of user controller any sort of review would be great :)

/**
 * Class UsersController
 * Controller for Admin User Interactions
 *
 * @package App\Http\Controllers
 */
class UsersController extends Controller
{
    private array  $params;
    private string $returnUrl;

    public function __construct()
    {
        $this->params = [
            'pageTitle' => 'Users',
            'usersdata' => User::paginate(10),
        ];

        $this->returnUrl = URL::to('/admin/users');
    }

    /**
     * Index function to return a index html
     *
     * @return Factory|View
     */
    public function show()
    {
        $this->params['user'] = new User();

        return view('admin.users.index', $this->params);
    }

    /**
     * Function to return a ajax modal or process a "New User" request
     *
     * @param Request $request
     *
     * @return Factory|JsonResponse|RedirectResponse|View|object
     * @throws Throwable
     */
    public function create(Request $request)
    {
        $request->validate(
            [
                'name'  => 'required | string',
                'email' => 'required | email',
            ],
            [
                'name.required'  => __('app_admin_user.name_validation_required'),
                'name_string'    => __('app_admin_user.name_validation_string'),
                'email.required' => __('app_admin_user.email_validation_required'),
                'email.email'    => __('app_admin_user.email_validation_email'),
            ]
        );

        if (!empty(User::where('email', $request->email)->first())) {
            return redirect()
                ->intended($this->returnUrl)
                ->withErrors([__('app_admin_user.user_validation_exist')]);
        }

        $requestData = $request->only(['name', 'email', 'password']);

        $user = new User();
        $user->addNewUser((object)$requestData);

        return redirect()
            ->intended($this->returnUrl)
            ->with('alert_success', __('app_admin_user.user_validation_create_success', ['email' => $user->email]));
    }

    /**
     * Return a ajax modal or process edit request
     *
     * @param int     $id
     * @param Request $request
     *
     * @return JsonResponse|object
     */
    public function edit(int $id, Request $request)
    {
        $request->validate(
            [
                'id'    => 'required | integer',
                'email' => 'required',
                'name'  => 'required | string',
            ],
            [
                'id.required'    => __('app_admin_user.id_validation_required'),
                'id.integer'     => __('app_admin_user.id_validation_integer'),
                'email.required' => __('app_admin_user.email_validation_required'),
                'name.required'  => __('app_admin_user.name_validation_required'),
                'name_string'    => __('app_admin_user.name_validation_string'),
            ]
        );

        $user = User::where('id', $id)->firstOrFail();

        $requestData = $request->only('id', 'email', 'password', 'name');

        $user->updateUser((object)$requestData);
        return redirect()
            ->intended($this->returnUrl)
            ->with('alert_success', __('app_admin_user.user_validation_update_success', ['email' => $user->email]));
    }

    /**
     * Get Modal for create form
     *
     * @return JsonResponse|object
     */
    public function showModalCreate()
    {
        $response = new stdClass();

        $modalOptions = new ModalFormComponentOptions("/admin/user/create", 'POST');
        $modalOptions->setHeading('app_admin_user.user_modal_new_header');

        $response->body = (new CustomBladeComponent(ModalForm::class, $modalOptions))
            ->toHTML(view('admin.users.modal_create'));

        return response()
            ->json($response)
            ->setStatusCode(200);
    }

    /**
     * Get Modal for edit form
     *
     * @param int $id
     *
     * @return JsonResponse|object
     */
    public function showModalEdit(int $id)
    {
        $response = new stdClass();

        $user = User::where('id', $id)->firstOrFail();

        $modalOptions = new ModalFormComponentOptions("/admin/users/edit/$id", 'POST');
        $modalOptions->setHeading(_('app_admin_user.user_modal_edit_header', ['name' => $user->name]));

        $response->body = (new CustomBladeComponent(ModalForm::class, $modalOptions))
            ->toHTML(view('admin.users.modal_edit', ['user'=> $user]));

        return response()
            ->json($response)
            ->setStatusCode(200);
    }
}
0 likes
2 replies
Tray2's avatar

I would keep the modals on the client side and not load them from your controller like you are doing. Just add the model code to the blade template for the pages it's needed on.

kbuczynski's avatar

i see... is there way to have content passed to them too from the $user object too so the fields will get filled for the edit modal ?

Please or to participate in this conversation.