Laravel 11 DeepSeek API Integration: Boost SEO with AI-Powered Keyword Generation

featured_img1739005269.webp

Laravel 11 DeepSeek API Integration: Boost SEO with AI-Powered Keyword Generation

Table of Contents

    DeepSeek offers a powerful API that can be seamlessly integrated into Laravel applications using Laravel’s built-in HTTP client (Http::post()) or Guzzle. By leveraging DeepSeek’s AI capabilities, you can enhance your application with features like automated content generation, intelligent chatbots, and data-driven insights. This guide will walk you through integrating DeepSeek into Laravel 11 to generate SEO-friendly keywords and tags effortlessly.

    What is DeepSeek ?

    DeepSeek is a leading artificial intelligence (AI) company specializing in natural language processing (NLP), machine learning, and AI-driven solutions. It provides tools for tasks such as text generation, question answering, and data analysis. Unlike OpenAI, DeepSeek operates independently, offering unique AI solutions tailored for various industries.

    Why Use DeepSeek in Your Laravel Project?

    Integrating DeepSeek into your Laravel application unlocks a range of possibilities:

    • Chatbot Integration: Use DeepSeek to build a chatbot for your website or app.
    • Content Generation: Automatically generate blog posts, emails, or product descriptions.
    • Data Analysis: Analyze user data to provide personalized recommendations.
    • Automation: Automate repetitive tasks like responding to FAQs or processing user inputs.

    Step 1: Sign Up for the DeepSeek API

    1. Open your browser and go to the official DeepSeek website: DeepSeek Platform.

      Click on the "Sign Up" button to create an account, Choose your preferred sign-up method

      Follow the verification process, such as confirming your email or logging in with your linked account.

    2. Once your account is created, log in to the DeepSeek platform.

      In the API dashboard, navigate to the "API Keys" option sidebar menu.

    3. Click the "Create New API Key" button to generate an API key.

    4. Copy the generated key. This key is important, as it allows your application to connect with the DeepSeek API.

    Step 2: Setting Up the Laravel Project

    If you don’t already have a Laravel project, create one with Composer:

                                        
                                            composer create-project laravel/laravel  deepseek-laravel-app
                                        
                                    

    Navigate to the app directory by running the following command in your terminal

                                        
                                            cd deepseek-laravel-app
                                        
                                    

    Step 3: Configure Your Environment

    Add your DeepSeek API key & API URL to the .env file:

                                        
                                            DEEPSEEK_API_KEY="your-api-key-here"
                                            DEEPSEEK_API_URL="https://api.deepseek.com"                                        
                                        
                                    

    Run the following command to clear and refresh your configuration cache:

                                        
                                            php artisan config:clear && php artisan config:cache
                                         
                                    

    Step 4: Create a API Service

    Create a service class to handle interactions with the DeepSeek API. Run the following Artisan command:

                                        
                                            php artisan make:class Services/DeepSeekAPIService
                                        
                                    

    Then, define the DeepSeek API logic in app/Services/DeepSeekService.php:

                                        
                                            namespace App\Services;
                                            use Illuminate\Support\Facades\Http;
    
                                            class DeepSeekAPIService
                                            {
                                            
                                                private $api_key, $base_url;
    
                                                public function __construct()
                                                {
                                                    $this->api_key = env('DEEPSEEK_API_KEY');
                                                    $this->base_url = env('DEEPSEEK_API_URL');
                                                }
    
                                                public function call_API($params_data)
                                                {
                                                    $endPoint = "/chat/completions";
                                                    return $this->executeApi($endPoint, "POST", $params_data);
                                                }
    
                                                private function executeApi($endPoint, $method, $data = [], $header = null)
                                                {
                                                    try {
    
                                                        $url = $this->base_url."".$endPoint;
                                                    
                                                        $BearerToken = $this->api_key;
                                                        $header = [
                                                            "Content-Type" => "application/json"                  
                                                        ];
    
                                                        $response_data = ["status" => false];
    
                                                        if (strcmp($method, 'GET') === 0) {               
                                                            $response = Http::withToken($BearerToken)->withHeaders($header)->get($url);
                                                        } else {
                                                            $response = Http::withToken($BearerToken)->withHeaders($header)->post($url, $data);
                                                        }          
    
                                                        if(isset($response) && $response->successful()){
                                                            $response_data['data'] = $response->json();
                                                            $response_data['status'] = $response->status();
                                                        }            
                                                    
                                                        return $response_data;
                                                    
                                                    } catch (\Exception $ex) {
                                                        $response_data['error_message'] = $ex->getMessage();
                                                        return $response_data;
                                                    }
                                                }
                                            }
                                        
                                    

    Step 5: Create a Controller

    Generate a controller to handle DeepSeek interactions:

                                        
                                            php artisan make:controller DeepSeekAPIController
                                        
                                    

    Inside the controller, you can process user queries and fetch responses from DeepSeek.

    Edit the controller file to include the logic for Keywords generation:

                                        
                                            namespace App\Http\Controllers;
    
                                            use Illuminate\Http\Request;
                                            use App\Services\DeepSeekAPIService;
                                            
                                            class DeepSeekAPIController extends Controller
                                            {
                                                public function index(Request $request)
                                                {
                                                    return view('query-chat');
                                                }
                                            
                                                public function search(Request $request)
                                                {
                                                    $request->validate([
                                                        'title' => 'required|string|max:255',
                                                    ]);
                                            
                                                    $title = $request->input('title');
                                            
                                                    try {
                                                        // Call DeepSeek API   
                                                        
                                                        $params_data = 
                                                        [
                                                            'name' => "Keywords-generator",
                                                            'api_type' => "openai",
                                                            'model' => 'deepseek-chat',
                                                            'temperature ' => 0.3,
                                                            'max_tokens' => 4096,
                                                            'messages' => [
                                                                ['role' => 'system', 'content' => 'You are a helpful assistant'],
                                                                ['role' => 'user', 'content' => "Find a Related Keywords for this title: '$title'"],
                                                            ],
                                                            'metadata'=> ["subject" => "Youtube keywords & Tags"],
                                                            "user_id" => 1001
                                                        ];
                                            
                                                        $response = (new DeepSeekAPIService())->call_API($params_data);
                                            
                                                        return response()->json([
                                                            'success' => true,
                                                            'data' => $response,
                                                        ]);
                                            
                                                    } catch (\Exception $e) {
                                                        return response()->json([
                                                            'success' => false,
                                                            'error' => $e->getMessage(),
                                                        ]);
                                                    }
                                                  
                                                }
                                            }                                  
                                        
                                    

    Step 6: Create a Blade View

    Create a view file at resources/views/query-chat.blade.php:

                                        
                                            php artisan make:view query-chat
                                        
                                    

    Customize the view to include an input box for user queries and a section to display responses.

        
                                        
                                         <!doctype html>
                                         <html lang="en">
                                         <head>
                                                 <meta charset="UTF-8">
                                                 <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
                                                 <title>Laravel 11 DeepSeek API Integration: Boost SEO with AI-Powered Keyword Generation</title>
                                                 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
                                         </head>
                                         <body>
                                         
                                                <div class="container mt-5">
                                                 <h1 class="text-center">>Laravel 11 DeepSeek API Integration: Boost SEO with AI-Powered Keyword Generation</h1>
                                                 <form id="DeepSeekQueryForm">
                                                     <div class="mb-3">
                                                         <label for="title" class="form-label">Enter Title</label>
                                                         <input type="text" class="form-control" id="title" name="title" required>
                                                     </div>
                                                     <button type="submit" class="btn btn-primary">Generate Keywords</button>
                                                 </form>
                                                 <div class="mt-4" id="tagsOutput"></div>
                                                 </div>
                                         
                                                 <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
                                                 <script>
                                         
                                                     $(document).ready(function () {
                                                         $('#DeepSeekQueryForm').submit(function (e) {
                                                             e.preventDefault();
                                 
                                                             let title = $('#title').val();
                                                             let KeywordsOutput = $('#DeepSeekQueryOutput');
                                 
                                                             $.ajax({
                                                                 url: "{{ route('deep-seek-query.search') }}",
                                                                 type: 'POST',
                                                                 data: {
                                                                     title: title,
                                                                     _token: '{{ csrf_token() }}' // Include CSRF token for security
                                                                 },
                                                                 beforeSend: function () {
                                                                    KeywordsOutput.html('<div class="alert alert-info">Generating tags...</div>');
                                                                 },
                                                                 success: function (response) {
                                                                     if (response.success) {
                                                                        KeywordsOutput.html(`<h3>Generated Keywords:</h3><p>${response.data.replace(/\n/g, '<br>')}</p>`);
                                                                     } else {
                                                                        KeywordsOutput.html(`<div class="alert alert-danger">Error: ${response.error}</div>`);
                                                                     }
                                                                 },
                                                                 error: function (xhr) {
                                                                    KeywordsOutput.html(`<div class="alert alert-danger">Error: ${xhr.responseJSON?.message || 'An error occurred'}</div>`);
                                                                 }
                                                             });
                                                         });
                                                     });
                                                 
                                           </script>
                                         </body>
                                         </html>                                       
                                         
                                       

    Step 7: Setting Up Routes And Run Project

    1. Add Route

      Define the route in routes/web.php

                                                  
                                                      use App\Http\Controllers\DeepSeekAPIController;
      
                                                      Route::get('/deep-seek-query', [DeepSeekAPIController::class, 'index'])->name('deep-seek-query.index');
                                                      Route::post('/deep-seek-query', [DeepSeekAPIController::class, 'search'])->name('deep-seek-query.search');
                                                  
                                              
    2. Run the Project

      Start the development server:

                                                  
                                                      php artisan serve                                         
                                                  
                                              
    3. Preview the Application

      Open your web browser and navigate to the following URL to view the code preview:

      Preview:

    Conclusion

    In this guide, we’ve successfully integrated the DeepSeek API into a Laravel 11 application, enabling AI-powered keyword generation for enhanced SEO. By structuring the integration with a service class and leveraging Laravel’s HTTP client, we’ve ensured a clean, modular, and maintainable approach. You can now expand this functionality by exploring additional features offered by DeepSeek, such as content generation and data analysis. For further enhancements, refer to the DeepSeek API documentation to unlock more advanced capabilities.

    Did this solution work for you? Drop a like or comment below!

    Satish Parmar

    Satish Parmar

    Experienced Full-Stack Web Developer

    I'm a passionate full-stack developer and blogger from India, dedicated to sharing web development tips and solutions. As the creator of TipInfoTrove.com, my goal is to help developers and tech enthusiasts solve real-world challenges with expertise in PHP, Laravel, JavaScript, Vue, React, and more. Through detailed guides and practical insights, I strive to empower others to excel in their projects and stay ahead in the ever-evolving world of technology.

    0 Comments

    Post Comment

    Your email address will not be published. Required fields are marked *