Laravel Observer for Automatic Logging

 76
Laravel Observer for Automatic Logging

πŸ“Œ Overview

This guide helps you implement automatic logging using Laravel Observer.

πŸ“Œ Step 1: Update the Model
Modify the model to include necessary properties and relationships.

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RescheduleHistory extends Model
{
    use HasFactory;

    protected $fillable = ['status', 'new_date', 'new_time', 'action_context', 'inspection_id'];

    public $action_context = null; // Holds context information for logging.

    /**
     *  Relationship: Each reschedule history entry belongs to an inspection.
     */
    public function inspection()
    {
        return $this->belongsTo(Inspection::class);
    }
}

 πŸ“Œ Step 2: Create the Observer for Logging πŸ•΅οΈβ€β™‚οΈ
Modify your observer to log all rescheduling events properly.

use App\Models\RescheduleHistory;
use App\Models\Inspection;

class RescheduleHistoryObserver
{
    /**
     * Handle the "created" event for RescheduleHistory.
     */
    public function created(RescheduleHistory $history): void
    {
        // Get related inspection details
        $inspection = $history->inspection;
        $inspectionTitle = $inspection ? $inspection->title : '';

        // Get the action context or set a default message
        $action = request()->input('action_context') ?? 'Inspection reschedule created';

        // Log activity
        user_log_activity("Inspection Rescheduled: $inspectionTitle", $action, RescheduleHistory::class, $history->id);
    }

    /**
     * Handle the "updated" event for RescheduleHistory.
     */
    public function updated(RescheduleHistory $history): void
    {
        if (!$history->wasChanged()) {
            return; // No changes detected, no need to log
        }

        // Fetch related inspection
        $inspection = $history->inspection;
        $inspectionTitle = $inspection ? $inspection->title : 'Unknown Inspection';

        // Determine action context
        $action = $history->action_context ?? 'Updated';

        // Check if status has changed to 'approved'
        if ($history->isDirty('status') && $history->status === 'approved') {
            user_log_activity("Inspection Confirmed: $inspectionTitle", $action, RescheduleHistory::class, $history->id);
        } else {
            user_log_activity("Inspection Update: $inspectionTitle", $action, RescheduleHistory::class, $history->id);
        }
    }
}

πŸ“Œ Step 3: Register the Observer in AppServiceProvider πŸ”
Ensure Laravel automatically listens for changes in RescheduleHistory.

use App\Models\RescheduleHistory;
use App\Observers\RescheduleHistoryObserver;

/**
 * Register model observers.
 */
public function boot()
{
    RescheduleHistory::observe(RescheduleHistoryObserver::class);
}

πŸ“Œ Step 4: Updating Inspection Schedule in Controller πŸ—οΈ
Ensure that when an inspection is reschedule, the necessary log message is captured.

use App\Models\RescheduleHistory;
use App\Models\Inspection;
use Illuminate\Http\Request;

public function rescheduleInspection(Request $request, $inspectionId)
{
    // Find the inspection
    $inspection = Inspection::findOrFail($inspectionId);

    // Format date and time
    $formattedDateTime = date('Y-m-d H:i:s', strtotime($request->new_date . ' ' . $request->new_time));

    // Update the inspection schedule
    $inspection->action_context = 'Inspection Rescheduled on ' . $formattedDateTime;
    $inspection->update([
        'date' => $request->new_date,
        'time' => $request->new_time,
    ]);

    // Create a reschedule history entry
    $logMessage = "Inspection Rescheduled on $formattedDateTime";
    $data_insert = [
        'status' => 'pending',
        'inspection_id' => $inspectionId,
        'new_date' => $request->new_date,
        'new_time' => $request->new_time,
        'action_context' => $logMessage,
    ];

    request()->merge(['action_context' => $logMessage]);
    RescheduleHistory::create($data_insert);

    return response()->json(['message' => 'Inspection rescheduled successfully.']);
}

πŸ“Œ Step 5:  Create a Global user_log_activity Helper (If Not Defined)πŸ› οΈ
Ensure this helper function exists to log activities.

if (!function_exists('user_log_activity')) {
    function user_log_activity($title, $message, $model, $modelId)
    {
        \App\Models\ActivityLog::create([
            'title' => $title,
            'message' => $message,
            'loggable_type' => $model,
            'loggable_id' => $modelId,
            'user_id' => auth()->id(),
        ]);
    }
}

Post a Comment

0Comments

* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Post a Comment (0)