Adding a Create Job Button
To make it easy to access the job creation form, add a “Create Job” button in your layout’s header section. Use Tailwind CSS classes to style it like a button and position it using Flexbox utilities:
<a href="/jobs/create" class="your-tailwind-button-classes">Create Job</a>Consider extracting this into a reusable Blade component for cleaner code. Here’s how:
Firstly you need to make a new file in the components Directory and name it like this for example: “button.blade.php“. Then copy the <a></a> from above and adjust it so it looks like this:
<a {{ $attributes->merge(['class' => 'relative inline-flex items-center px-4 py-2 -ml-px text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 hover:text-gray-500 focus:z-10 focus:outline-none focus:ring ring-gray-300 focus:border-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150 rounded-md']) }}>{{ $slot }}</a>
Then you can adjust the layout file to this to pull in the button:
<x-button href="/jobs/create">Create Job</x-button>Defining Routes for Form Submission
Add a POST route to /jobs to handle form submissions. Initially, add a simple sanity check with dd('hello from POST') to confirm the route is hit.
Accessing Request Data
Use the request() helper to retrieve form inputs:
$request->all(); // all inputs
$request->input('title'); // specific inputServer-Side Validation
Use Laravel’s built-in validation method in your POST route:
$request->validate([
'title' => ['required', 'min:3'],
'salary' => ['required'],
]);If validation fails, Laravel automatically redirects back with error messages. Here’s a list of all different Validations rules in Laravel: Validation Rules
Displaying Validation Errors
In your Blade view, display errors globally:
@if ($errors->any())
<ul>
@foreach ($errors->all() as $error)
<li class="text-red-500">{{ $error }}</li>
@endforeach
</ul>
@endifOr display errors inline below each input using the @error directive:
@error('title')
<p class="text-red-500 text-sm">{{ $message }}</p>
@enderrorClient-Side Validation
Add the required attribute to inputs for instant browser validation, enhancing user experience.
Creating Records and Redirecting
After validation, create the job record with Eloquent:
Job::create([
'title' => $request->input('title'),
'salary' => $request->input('salary'),
'employer_id' => $employerId, // typically from authenticated user
]);
return redirect('/jobs');Remember to include all mass-assignable fields in your model’s $fillable array or disable mass assignment protection as needed.
