DEV Community

Ruhul Amin Sujon
Ruhul Amin Sujon

Posted on • Edited on

AS API Code Example

Controller:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Tv;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class TvController extends Controller
{
    public function index()
    {
        try {
            $tvs = Tv::where('status', 1)->get();

            return response()->json([
                'status' => true,
                'statusCode' => 200,
                'message' => 'TV list retrieved successfully',
                'data' => $tvs
            ]);
        } catch (Exception $e) {

            // Log the error
            Log::error('Error in retrieving TV: ', [
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'status' => false,
                'statusCode' => 500,
                'message' => 'Something went wrong!!!',
                'data' => []
            ], 500);
        }
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string',
            'channel_id' => 'required|string',
            'file' => 'required|file|image:jpg|image:png',
            'status' => 'nullable|in:0,1',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'statusCode' => 422,
                'message' => 'The given data was invalid',
                'data' => $validator->errors()
            ], 422);
        }

        try {
            // Handle file upload
            if ($request->hasFile('file')) {
                $filePath = $this->storeFile($request->file('file'));
                $img_url = $filePath ?? '';
            }

            $tv = Tv::create([
                'name' => $request->name,
                'channel_id' => $request->channel_id,
                'img_url' => $img_url,
                'status' => 1,
            ]);

            return response()->json([
                'status' => true,
                'statusCode' => 201,
                'message' => 'TV created successfully',
                'data' => $tv
            ], 201);
        } catch (Exception $e) {

            // Log the error
            Log::error('Error in storing TV: ', [
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'status' => false,
                'statusCode' => 500,
                'message' => 'Something went wrong!!!',
                'data' => []
            ], 500);
        }
    }
    public function show($id)
    {
        //
    }
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|exists:tvs,id',
            'name' => 'nullable|string',
            'channel_id' => 'nullable|string',
            'file' => 'nullable|file|image:jpg|image:png|image:jpeg',
            'status' => 'nullable|in:0,1',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'statusCode' => 422,
                'message' => 'The given data was invalid',
                'data' => $validator->errors()
            ], 422);
        }

        try {
            $tv = Tv::findOrFail($request->id);

            $requestData = $request->except(['file', 'id']);
            $requestData['name'] = $requestData['name'] ?? $tv->name;
            $requestData['channel_id'] = $requestData['channel_id'] ?? $tv->title;
            $requestData['status'] = $requestData['status'] ?? $tv->singer_name;
            $requestData['img_url'] = $tv->img_url;
            $requestData['updated_at'] = now();

            // Handle file upload
            if ($request->hasFile('file')) {
                $filePath = $this->updateFile($request->file('file'), $tv);
                $requestData['img_url'] = $filePath ?? '';
            }

            $tv->update($requestData);

            return response()->json([
                'status' => true,
                'statusCode' => 200,
                'message' => 'TV updated successfully',
                'data' => $tv
            ]);
        } catch (Exception $e) {

            // Log the error
            Log::error('Error in updating TV: ', [
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'status' => false,
                'statusCode' => 500,
                'message' => 'Something went wrong!!!',
                'data' => []
            ], 500);
        }
    }
    public function destroy($id)
    {
        //
    }

    private function storeFile($file)
    {
        // Define the directory path
        $filePath = 'files/music/mp3';
        $directory = public_path($filePath);

        // Ensure the directory exists
        if (!file_exists($directory)) {
            mkdir($directory, 0777, true);
        }

        // Generate a unique file name
        $fileName = uniqid('music_', true) . '.' . $file->getClientOriginalExtension();

        // Move the file to the destination directory
        $file->move($directory, $fileName);

        // path & file name in the database
        # $path = $filePath . '/' . $fileName;
        $path = $fileName;
        return $path;
    }
    public function getMusic($filename)
    {
        try {
            $path = public_path('files/music/mp3/' . $filename);

            if (!file_exists($path)) {
                return $this->sendResponse(false, '404, File not found.', []);
            }

            return response()->file($path);
        } catch (Exception $e) {

            // Log the error
            Log::error('Error in get File: ', [
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);

            return $this->sendResponse(false, 'Something went wrong!!!', [], 500);
        }
    }
    private function updateFile($file, $data)
    {
        // Define the directory path
        $filePath = 'files/music/mp3';
        $directory = public_path($filePath);

        // Ensure the directory exists
        if (!file_exists($directory)) {
            mkdir($directory, 0777, true);
        }

        // Generate a unique file name
        $fileName = uniqid('music_', true) . '.' . $file->getClientOriginalExtension();

        // Delete the old file if it exists
        $this->deleteOldFile($data);

        // Move the new file to the destination directory
        $file->move($directory, $fileName);

        // Store path & file name in the database
        # $path = $filePath . '/' . $fileName;
        $path = $fileName;
        return $path;
    }
    private function deleteOldFile($data)
    {
        if (!empty($data->img_url)) {
            $filePath = 'files/music/mp3';
            $directory = $data->img_url;
            $path = $filePath . '/' . $directory;

            $oldFilePath = public_path($path); // Use without prepending $filePath
            if (file_exists($oldFilePath)) {
                unlink($oldFilePath); // Delete the old file
                return true;
            } else {
                Log::warning('Old file not found for deletion', ['path' => $oldFilePath]);
                return false;
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

আপনি নিচের মতো একটি Laravel রুট তৈরি করে /clear-cache এ গিয়ে cache, config, route এবং view clear করতে পারেন

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Route;

Route::get('/clear-cache', function () {
    Artisan::call('cache:clear');
    Artisan::call('config:clear');
    Artisan::call('route:clear');
    Artisan::call('view:clear');

    return 'All caches (config, route, view, application) have been cleared!';
});

Enter fullscreen mode Exit fullscreen mode

Previous one file store with get full path

    private function storeFile($file)
    {
        // Define the directory path
        // TODO: Change path if needed
        $filePath = 'files/images/country'; # change path if needed
        $directory = public_path($filePath);

        // Ensure the directory exists
        if (!file_exists($directory)) {
            mkdir($directory, 0777, true);
        }

        // Generate a unique file name
        // TODO: Change path if needed
        $fileName = uniqid('flag_', true) . '.' . $file->getClientOriginalExtension();

        // Move the file to the destination directory
        $file->move($directory, $fileName);

        // path & file name in the database
        $path = $filePath . '/' . $fileName;
        return $path;
    }
    private function updateFile($file, $data)
    {
        // Define the directory path
        // TODO: Change path if needed
        $filePath = 'files/images/country'; # change path if needed
        $directory = public_path($filePath);

        // Ensure the directory exists
        if (!file_exists($directory)) {
            mkdir($directory, 0777, true);
        }

        // Generate a unique file name
        // TODO: Change path following storeFile function
        $fileName = uniqid('flag_', true) . '.' . $file->getClientOriginalExtension();

        // Delete the old file if it exists
        $this->deleteOldFile($data);

        // Move the new file to the destination directory
        $file->move($directory, $fileName);

        // Store path & file name in the database
        $path = $filePath . '/' . $fileName;
        return $path;
    }
    private function deleteOldFile($data)
    {
        // TODO: ensure from database
        if (!empty($data->flag)) { # ensure from database
            $oldFilePath = public_path($data->flag); // Use without prepending $filePath
            if (file_exists($oldFilePath)) {
                unlink($oldFilePath); // Delete the old file
                return true;
            } else {
                Log::warning('Old file not found for deletion', ['path' => $oldFilePath]);
                return false;
              }
          }
      }
Enter fullscreen mode Exit fullscreen mode

For Migration & other Commands

1. model & migration:

php artisan make:model BranchContactInfo -m

php artisan make:model BranchContactInfo -mcr

  • The -m flag creates a new migration file.
  • The -c flag creates a controller.
  • The -r flag specifies that it should be a resource controller, which includes all the standard methods for a CRUD (Create, Read, Update, Delete) application.

2. controller:

php artisan make:controller Api/PostController --api

php artisan make:controller ProductController --resource

3. Migration:

php artisan make:migration create_fields_table

php artisan make:migration add_telegram_group_link_to_settings_table

php artisan make:migration add_columns_to_users_table --table=users

Schema::create('rooms', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable();
            $table->unsignedBigInteger('hotel_id')->nullable();
            $table->unsignedBigInteger('floor_id')->nullable();

            $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('hotel_id')->constrained('hotels')->onDelete('cascade');
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('cascade');
            $table->foreignId('updated_by')->nullable()->constrained('users')->onDelete('cascade');

            $table->string('room_no')->nullable();
            $table->enum('bed_type', ['Single', 'Double', 'Triple'])->default('Single')->nullable();
            $table->boolean('has_ac')->default(true)->nullable();
            $table->text('description')->nullable();
            $table->enum('status', ['Active', 'Inactive'])->default('Active')->nullable();
$table->index(['id', 'lat', 'long'], 'idx_lat_long');
$table->string('status', 50)->nullable()->after('check_out')->default('confirmed');
            $table->decimal('rent',10, 2)->nullable()->default(0)->after('check_out');
            $table->timestamps();
        });
Enter fullscreen mode Exit fullscreen mode

ii. add_columns

public function up()
{
Schema::table('settings', function (Blueprint $table) {
$table->string('telegram_group_link')->nullable()->after('task_timing');

$table->foreignId('popular_place_id')->nullable()->constrained('popular_places')->onDelete('cascade')->after('package_id');

$table->dropForeign(['hotel_id']);
$table->dropColumn('hotel_id');

$table->dropForeign(['floor_id']);
$table->dropColumn('floor_id');

$table->dropForeign(['room_id']);
$table->dropColumn('room_id');

$table->enum('status', ['pending', 'confirmed', 'checked_in', 'checked_out', 'cancelled'])
                  ->default('pending')
                  ->nullable()
                  ->change();

$table->renameColumn('price', 'rent');
    });
}

public function down()
{
    Schema::table('settings', function (Blueprint $table) {
        $table->dropColumn('telegram_group_link');
    });
}
Enter fullscreen mode Exit fullscreen mode

4. seeder:

php artisan make:seeder UserSeeder

php artisan db:seed

5. Request Code

public function rules()
    {
        $data = $this->route('invitation_code');
        $id = $data?->id ?? null;

        return InvitationCode::rules($id);
    }
Enter fullscreen mode Exit fullscreen mode

2nd part

public function rules()
    {
        // Get the route name and apply null-safe operator
        $routeName = $this->route()?->getName();

        if ($routeName === 'events.update') {
            return Event::updateRules();
        }

        return Event::rules();
    }
Enter fullscreen mode Exit fullscreen mode

Postman token save

let responseData = pm.response.json();

if (responseData.success && responseData.data.token) {
    pm.collectionVariables.set("token", responseData.data.token);
    console.log("Token set in collection variable successfully.");
} else {
    console.error("Failed to set token. Check response structure or API call.");
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)