Laravel

laravel post route and post request , post request using postman

Aug 6, 2024, 4:30 PM
Blog Thumbnail

Laravel POST Route Example

1. Define a POST Route


use App\Http\Controllers\PostController;

Route::post('/submit-data', [PostController::class, 'store']);

                    

2. Create the Controller


php artisan make:controller PostController

                    

3. Handle the Request in the Controller


namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
        // Validate incoming request
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email',
            'message' => 'required|string',
        ]);

        // Save the data (example)
        // Message::create($validatedData);

        return response()->json([
            'success' => true,
            'message' => 'Data successfully submitted!',
            'data' => $validatedData,
        ], 201);
    }
}

                    

4. Make a POST Request

Using Axios


axios.post('/submit-data', {
    name: 'John Doe',
    email: 'john.doe@example.com',
    message: 'Hello, this is a test message.',
})
.then(response => {
    console.log('Success:', response.data);
})
.catch(error => {
    console.error('Error:', error.response.data);
});

                            

Using Postman

In Postman:

  • Select POST as the request method.
  • Enter the URL: http://your-laravel-app.test/submit-data.
  • Provide JSON data in the body:

{
    "name": "John Doe",
    "email": "john.doe@example.com",
    "message": "This is a test message."
}

                            

5. Response Example


{
    "success": true,
    "message": "Data successfully submitted!",
    "data": {
        "name": "John Doe",
        "email": "john.doe@example.com",
        "message": "This is a test message."
    }
}