Forms

Forms

Defining Routes for Forms

When adding a route for creating a new job, use the URI jobs/create. Be mindful of route order: wildcard routes like jobs/{id} should come after specific routes like jobs/create to avoid conflicts.

Organizing Views

Group related views in folders, e.g., place all job-related views in a jobs directory. Use common naming conventions:

  • index.blade.php for listing all jobs
  • show.blade.php for displaying a single job
  • create.blade.php for the form to create a job

Use dot notation in views references, e.g., 'jobs.create'.

Building the Form

Use a Tailwind UI form template, trimming unnecessary sections and adjusting input fields to match your database columns (title, salary). Add placeholders and padding for better UX.

Handling Form Submission

By default, forms submit via GET to themselves. Change the form method to POST and set the action to /jobs to follow RESTful conventions for creating resources.

Add a POST route for /jobs in your routes file to handle form submissions.

Accessing Request Data

Use the request() helper to retrieve form data:

PHP
$request->all(); // all form data
$request->input('title'); // specific field

Creating Records

Create a new job record using Eloquent’s create() method with the request data:

PHP
Job::create([
    'title' => $request->input('title'),
    'salary' => $request->input('salary'),
    'employer_id' => $employerId, // typically from authenticated user
]);

Remember to include employer_id in your model’s $fillable array or disable mass assignment protection accordingly.

Redirecting After Submission

After creating the job, redirect the user back to the jobs listing page:

PHP
return redirect('/jobs');

Extracting Form Components

To build forms efficiently you should / need to create reusable Blade components for:

  • form-label.blade.php — for form labels
  • form-error.blade.php — for displaying validation errors
  • form-input.blade.php — for input fields

These components accept attributes and slots to make them flexible.
Here’s an example of the usage in a form:

PHP
<x-form-label for="title">Title</x-form-label>
<x-form-input id="title" name="title" required />
<x-form-error name="title" />

Tags: