28 June 2023

How to use Mutators and Accessors in Laravel?

Mutators and Accessors in Laravel     


Set file path in model

public function getFilePathAttribute($file_path)

    {

        if(!empty($file_path))

        {

             return $filepath = URL::to('/') . '/upload/' . $file_path;

/*             return asset('/upoad/' . $file_path); */


        }

    }

Set created time ago in model

protected $appends = ["created_time_ago"];

public function getCreatedTimeAgoAttribute()

    {

        $created_at = $this->attributes['created_at'];

        // Convert the date/time to a Carbon instance

        $carbonCreatedAt = Carbon::parse($created_at);

        // Get the "time ago" format

        $timeAgo = $carbonCreatedAt->diffForHumans();

        // Set the modified value to the column

        return $timeAgo;

    }

Set created time ago in model

public function getRequestedTimeAttribute($requested_time)

    {

        if(!empty($requested_time))

        {

             return date_format($requested_time,"Y-m-d");

        }

    }

How to upload multi file by base64 url in laravel?

Multi file upload by base64 url in laravel

Function


function uploadBase64File($base64_url){

    $response = array();

    $base64Data = $base64_url;

    $pattern = '/data:(.*);base64,([^"]*)/';

    // Perform the regular expression match

    preg_match($pattern, $base64Data, $matches);

    if (!empty($matches[1])) {

        $mime = $matches[1];

        // Remove the data:image/jpeg;base64, part from the string

        $mimeToExt = [

            'image/jpeg' => 'jpg',

            'image/png' => 'png',

            'image/gif' => 'gif',

            'image/bmp' => 'bmp',

            'image/webp' => 'webp',

            'application/pdf' => 'pdf',

            'application/msword' => 'doc',

            'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',

            // Add more mappings as needed

        ];

        // Check if the MIME type exists in the mapping

        if (isset($mimeToExt[$mime])) {

            $extension = $mimeToExt[$mime];

        }

        

        $base64Data = str_replace('data:' . $matches[1] . ';base64,', '', $base64Data);

        // Decode the base64 data into binary format

        $fileData = base64_decode($base64Data);

        $urlParts = parse_url($base64Data);

        $queryString = $urlParts['query'];

        parse_str($queryString, $queryParameters);

        $original_filename = uniqid() . "-" . $queryParameters['filename'];

        if(empty($queryParameters['filename'])){

        // Generate a unique file name for the uploaded file

        $original_filename = uniqid() . "." . $extension;

        }

        $response["file_name"] = $original_filename; 

        $response["file_extension"] = $extension; 

        $response["file_data"] = $fileData; 

        return $response;

    }

}




=====================================================

Add base 64 url

$base64url = "";

$Base64File = uploadBase64File($base64url);

if(!empty($Base64File["file_name"])){

$original_filename = $Base64File["file_name"];

$file_extension = $Base64File["file_extension"];

$file_data = $Base64File["file_data"];

$storagePath = "service-requests/location-images" . "/" . $original_filename;

$filePath = Storage::disk('uploads')->put($storagePath, $file_data);

$ServiceRequestsDocs = ServiceRequestsDocs::create([

'file_extensions' => $file_extension,

'file_name' => $original_filename,

'file_path' => $storagePath,

]

);

}


Add below code in config\filesystem.php file

        'uploads' => [

            'driver' => 'local',

            'root' => public_path() .'/upload',

            'visibility' => 'public',

       ]


Add in Model file   
 public function getFilePathAttribute($file_path)

    {

        if(!empty($file_path))

        {

             return $filepath = URL::to('/') . '/upload/' . $file_path;

/*             return asset('/upoad/' . $file_path); */


        }

    }

How to use autofill google place APi(google Map APi)?

 <html>

    <head>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBcRA4LijSY8e-FG4lN1sTYChasKAEsrGo&libraries=places"></script>
    </head>
    <body>
    <input type="text" id="autocomplete-input" placeholder="Enter a location">
    </body>
    <script>
    // Replace 'YOUR_API_KEY' with your actual API key
    const apiKey = 'AIzaSyBcRA4LijSY8e-FG4lN1sTYChasKAEsrGo';

    // Initialize the autocomplete object
    const autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete-input'), {
    types: ['geocode'],  // Restrict the results to geographical locations
    apiKey: apiKey       // Provide your API key
    });

    // Add an event listener for when a place is selected
    autocomplete.addListener('place_changed', onPlaceSelected);

    // Handle the selected place
    function onPlaceSelected() {
    const place = autocomplete.getPlace();
    console.log(place); // You can access the selected place object here
    }
    </script>
</html>

How to preview, add more and remove file before upload?

 <!DOCTYPE html>

<?php
function decode_base64($base64Data){
$extension = null;
$pattern = '/data:(.*);base64,([^"]*)/';
// Perform the regular expression match
preg_match($pattern, $base64Data, $matches);
if(!empty($matches[1])){
$mime = $matches[1];
// Map MIME type to extension
$mimeToExt = [
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/gif' => 'gif',
    'image/bmp' => 'bmp',
    'image/webp' => 'webp',
    'application/pdf' => 'pdf',
    'application/msword' => 'doc',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
    // Add more mappings as needed
];
// Check if the MIME type exists in the mapping
if (isset($mimeToExt[$mime])) {
    $extension = $mimeToExt[$mime];
}
/*     print_r($matches);
    die('here'); */

// Remove the data:image/jpeg;base64, part from the string
 $base64Data = str_replace('data:' . $matches[1] . ';base64,', '', $base64Data);
// $base64Data = str_replace('data:image/jpeg;base64,', '', $base64Data);
// Decode the base64 data into binary format
$image_data = base64_decode($base64Data);
$urlParts = parse_url($base64Data);
$queryString = $urlParts['query'];
parse_str($queryString, $queryParameters);
$original_filename = $queryParameters['filename'];
if(empty($original_filename)){
// Generate a unique file name for the uploaded file
$original_filename = uniqid() . "." . $extension;
}
// $filename = uniqid() . '.jpeg';
// Specify the file path where you want to save the uploaded file
$filepath = 'uploads/' . $original_filename;

// Write the decoded binary data to the file
if (file_put_contents($filepath, $image_data)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}
}
else{
/*     print_r($base64Data); */
}
}
if(isset($_POST['submit'])){
    echo 'starting';
    echo "<pre>";
    $files = $_POST["files"];
    foreach($files as $file){
        $data = decode_base64($file);
    }
    print_R($data);
    die();
}
?>
<html>
<head>
  <title>Multi-file Upload</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
  <style>
    .drop-zone {
      border: 2px dashed #ccc;
      width: 300px;
      height: 200px;
      padding: 20px;
      text-align: center;
      cursor: pointer;
    }

    .file-preview {
      display: flex;
      flex-wrap: wrap;
      margin-top: 10px;
    }

    .file-item {
      display: flex;
      align-items: center;
      margin-right: 10px;
      margin-bottom: 10px;
    }

    .file-item img {
      width: 50px;
      height: 50px;
      margin-right: 5px;
    }

    .remove-btn {
      cursor: pointer;
      color: red;
      font-weight: bold;
    }
    .file_preview_error{
      color:red;
    }
    .error{
      color:red;
      display:block;
    }
  </style>

</head>
<body>
<form action="" method="post" id="my_form" enctype="multipart/form-data">    
  <input type="text" name="username" >
  <div class="drop-zone" id="dropzone">
    <span>Drag and drop files here</span>
  </div>
  <div class="file-preview" id="file_preview"></div>
  <div class="file_preview_error"></div>
  <input type="submit" name="submit" value="submit" id="submit_bt">
</form>
  <script>
    window.addEventListener("DOMContentLoaded", () => {
  const dropZone = document.getElementById("dropzone");
  const filePreview = document.getElementById("file_preview");

  // Handle file drop
  dropZone.addEventListener("drop", (e) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    handleFiles(files);
  });

  // Handle file drag over
  dropZone.addEventListener("dragover", (e) => {
    e.preventDefault();
  });

  // Handle file input change
  dropZone.addEventListener("click", () => {
    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.multiple = true;
    fileInput.accept = "image/*";
    fileInput.addEventListener("change", (e) => {
      $(".file_preview_error").text("");
      const files = e.target.files;
      handleFiles(files);
    });
    fileInput.click();
  });

  // Handle file removal
  filePreview.addEventListener("click", (e) => {
    if (e.target.classList.contains("remove-btn")) {
      const fileItem = e.target.parentElement;
      const fileName = fileItem.getAttribute("data-file-name");
      fileItem.remove();
    }
  });

  function handleFiles(files) {
    for (const file of files) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const fileContent = e.target.result;
        displayFile(file, fileContent);
      };
      reader.readAsDataURL(file);
    }
  }

  function displayFile(file, fileContent) {
    const fileItem = document.createElement("div");
    fileItem.classList.add("file-item");
    fileItem.setAttribute("data-file-name", file.name);
    const image = document.createElement("img");
    image.src = fileContent;

    // Create the input element
    const inputElement = document.createElement("input");
    // Set the input type and value attributes
    inputElement.setAttribute("type", "hidden");
    inputElement.setAttribute("name", "files[]");
    inputElement.setAttribute("value", fileContent + "?filename=" + file.name);
    const fileName = document.createElement("span");
    fileName.innerText = file.name;
    const removeBtn = document.createElement("span");
    removeBtn.classList.add("remove-btn");
    removeBtn.innerText = "Remove";

    fileItem.appendChild(image);
    fileItem.appendChild(inputElement);
    fileItem.appendChild(fileName);
    fileItem.appendChild(removeBtn);
    filePreview.appendChild(fileItem);
  }
});

$(document).ready(function() {
  function jqueryValidations(){
    $("#my_form").validate({
      rules: {
        username: "required",
        },
      // In 'messages' user have to specify message as per rules
      messages: {
        username: "Username is required."
      }
    });
    return $("#my_form").valid();
  }

  function dropFileValidation(){
    var dropZone = $('#file_preview');
    $(".file_preview_error").text("");
    if (dropZone.is(':empty')) {
        // The drop zone is empty
        // Perform your validation logic here or take appropriate actions
  /*       console.log("The drop zone is empty."); */
        $(".file_preview_error").text("This field is required.");
        return false;
      }
    return true;
  }

  $('#submit_bt').click(function(e) {

      if (!jqueryValidations() || !dropFileValidation()) {
        dropFileValidation();
        event.preventDefault(); // Prevent form submission if any validation fails
      }
    });
});
</script>
</body>
</html>

How to use form validations(Jquery validations) in step form?

<!DOCTYPE html>
<html>
<head>
<title>Multi-file Upload</title>
<style>
fieldset {
  display: none;
}

fieldset:first-child {
  display: block;
}

button {
  margin-top: 10px;
}

.prev {
  margin-right: 10px;
}
.drop-zone {
  border: 2px dashed #ccc;
  width: 300px;
  height: 200px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
}
.file-preview {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}
.file-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
  margin-bottom: 10px;
}
.file-item img {
  width: 50px;
  height: 50px;
  margin-right: 5px;
}
.remove-btn {
  cursor: pointer;
  color: red;
  font-weight: bold;
}
.file_preview_error{
  color:red;
}
.error{
  color:red;
  display:block;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script>
$(document).ready(function() {
  // Initialize validation for the form
  $('#stepForm').validate({
    rules: {
      name: 'required',
      email: {
        required: true,
        email: true
      },
      password: {
        required: true,
        minlength: 6
      },
      confirmPassword: {
        required: true,
        equalTo: '#password'
      },
      username: 'required',
      address: 'required',
      city: 'required'
    },
    messages: {
      // Customize error messages for each field if needed
    },
    errorPlacement: function(error, element) {
      // Customize error placement if needed
      error.insertAfter(element);
    }
  });
  function thirdStepJqueryValidations(){
    $("#stepForm").validate({
      rules: {
        username: "required",
        },
      // In 'messages' user have to specify message as per rules
      messages: {
        username: "Username is required."
      }
    });
    return $("#stepForm").valid();
  }
  // Step navigation
  var currentStep = 0;
  var fieldsets = $('#stepForm fieldset');
  var stepsCount = fieldsets.length;

  function navigateTo(step) {
    // Hide all fieldsets
    fieldsets.hide();
    // Show the selected step
    $(fieldsets[step]).fadeIn('slow');
    // Disable previous button if on the first step
    $('.prev').prop('disabled', step === 0);
    // Change the text of the next button on the last step
    if (step === stepsCount - 1) {
      $('.next').text('Submit');
    } else {
      $('.next').text('Next');
    }
  }
  function dropFileValidation(){
    var dropZone = $('#file_preview');
    $(".file_preview_error").text("");
    if (dropZone.is(':empty')) {
        // The drop zone is empty
        // Perform your validation logic here or take appropriate actions
  /*       console.log("The drop zone is empty."); */
        $(".file_preview_error").text("This field is required.");
        return false;
      }
    return true;
  }
  $('.next').click(function() {
      console.log(currentStep);
      if(currentStep == 2){
        if(!thirdStepJqueryValidations() || !dropFileValidation()) {
          dropFileValidation();
          return false;
        }
      }
    if ($('#stepForm').valid()) {
        currentStep++;
        navigateTo(currentStep);
    }
  });
  $('.prev').click(function() {
    currentStep--;
    navigateTo(currentStep);
  });
});

window.addEventListener("DOMContentLoaded", () => {
  const dropZone = document.getElementById("dropzone");
  const filePreview = document.getElementById("file_preview");
  // Handle file drop
  dropZone.addEventListener("drop", (e) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    handleFiles(files);
  });
  // Handle file drag over
  dropZone.addEventListener("dragover", (e) => {
    e.preventDefault();
  });
  // Handle file input change
  dropZone.addEventListener("click", () => {
    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.multiple = true;
    fileInput.accept = "image/*";
    fileInput.addEventListener("change", (e) => {
      $(".file_preview_error").text("");
      const files = e.target.files;
      handleFiles(files);
    });
    fileInput.click();
  });
  // Handle file removal
  filePreview.addEventListener("click", (e) => {
    if (e.target.classList.contains("remove-btn")) {
      const fileItem = e.target.parentElement;
      const fileName = fileItem.getAttribute("data-file-name");
      fileItem.remove();
    }
  });
  function handleFiles(files) {
    for (const file of files) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const fileContent = e.target.result;
        displayFile(file, fileContent);
      };
      reader.readAsDataURL(file);
    }
  }
  function displayFile(file, fileContent) {
    const fileItem = document.createElement("div");
    fileItem.classList.add("file-item");
    fileItem.setAttribute("data-file-name", file.name);
    const image = document.createElement("img");
    image.src = fileContent;
    // Create the input element
    const inputElement = document.createElement("input");
    // Set the input type and value attributes
    inputElement.setAttribute("type", "hidden");
    inputElement.setAttribute("name", "files[]");
    inputElement.setAttribute("value", fileContent + "?filename=" + file.name);
    const fileName = document.createElement("span");
    fileName.innerText = file.name;
    const removeBtn = document.createElement("span");
    removeBtn.classList.add("remove-btn");
    removeBtn.innerText = "Remove";
    fileItem.appendChild(image);
    fileItem.appendChild(inputElement);
    fileItem.appendChild(fileName);
    fileItem.appendChild(removeBtn);
    filePreview.appendChild(fileItem);
  }
});
</script>
</head>
<body>
<form id="stepForm" method="post">
  <fieldset>
    <h2>Step 1</h2>
    <input type="text" name="name" id="name" placeholder="Name">
    <input type="email" name="email" id="email" placeholder="Email">
    <button type="button" class="next">Next</button>
  </fieldset>
  <fieldset>
    <h2>Step 2</h2>
    <input type="password" name="password" id="password" placeholder="Password">
    <input type="password" name="confirmPassword" id="confirmPassword" placeholder="Confirm Password">
    <button type="button" class="prev">Previous</button>
    <button type="button" class="next">Next</button>
  </fieldset>
  <fieldset>
    <h2>Uploader</h2>
    <input type="text" name="username" >
    <div class="drop-zone" id="dropzone">
    <span>Drag and drop files here</span>
  </div>
  <div class="file-preview" id="file_preview"></div>
  <div class="file_preview_error"></div>

    <button type="button" class="prev">Previous</button>
    <button type="button" class="next">Next</button>
  </fieldset>
  <fieldset>
    <h2>Step 3</h2>
    <input type="text" name="address" id="address" placeholder="Address">
    <input type="text" name="city" id="city" placeholder="City">
    <button type="button" class="prev">Previous</button>
    <button type="submit">Submit</button>
  </fieldset>
</form>
</body>
</html>

 

How to add re-captcha v3 on all Elementor forms using coding?

 Add re-captcha v3 on all Elementor forms using coding add_action('wp_footer',function(){     ?> <script src="https://www...