php Laravel cannot store input value to database

// HI, I am currently working on a laravel php project, the project previously connected with slack and send notifications to slack. Now I need to send notifications to Teams, so I need to follow the previous slack notifications. for the database, I have a user table contained slack_incoming_hook, and I added a column called ‘teams_incoming_hook’ just like “slack_incoming_hook”. Next, I modified user.php file, it has a creation function and a store function to create and store the input value. I added teams_incoming_hook following slack_incoming_hook.
// user.php:

class User extends Authenticatable
{
    protected $fillable = [
        
        'slack_incoming_hook',
        'teams_incoming_hook'
    ];
    static public function create(Request $request){
        $user = new User;
        
        $user->slack_incoming_hook = $request->slack_incoming_hook;
        $user->teams_incoming_hook = $request->teams_incoming_hook;
        
        $user->save();
    
 }
 static public function create(Request $request){
    $user->slack_incoming_hook = $request->slack_incoming_hook;
    $user->teams_incoming_hook = $request->teams_incoming_hook;
 }
 static public function store(Request $request){
    DB::transaction(function () use ($request) {
        $user = User::find($request->id);
        if($user){
            if($request->slack_incoming_hook != ""){
                $user->slack_incoming_hook = $request->slack_incoming_hook;
            }
            if($request->teams_incoming_hook != ""){
                $user->teams_incoming_hook = $request->teams_incoming_hook;
            }
            $user->update();
        }
 }

 }

// here is the edit-user.blade.php code:

<div class="col-span-3 sm:col-span-2">
    <label for="slack_incoming_hook" class="block text-sm font-medium text-gray-700">
        Slack Webhook Url
    </label>
    <div class="mt-1 flex rounded-md shadow-sm">
        <input type="text" name="slack_incoming_hook" id="slack_incoming_hook" class="focus:ring-green-200 focus:border-green-200 flex-1 block w-full rounded-none rounded-l-md rounded-r-md sm:text-sm border-gray-300" value="{{ $user['slack_incoming_hook']}}">
    </div>
    <x-small-text.danger class="slack_incoming_hook_error"></x-small-text.danger>

</div>
<div class="col-span-3 sm:col-span-2">
    <label for="teams_incoming_hook" class="block text-sm font-medium text-gray-700">
        Teams Webhook Url
    </label>
    <div class="mt-1 flex rounded-md shadow-sm">
        <input type="text" name="teams_incoming_hook" id="teams_incoming_hook" class="focus:ring-green-200 focus:border-green-200 flex-1 block w-full rounded-none rounded-l-md rounded-r-md sm:text-sm border-gray-300" value="{{ $user['teams_incoming_hook']}}">
    </div>
    <x-small-text.danger class="teams_incoming_hook_error"></x-small-text.danger>
</div>

and I tried to modify the User table directly and the value can show on the UI page.
Please help me to figure it out. Many THX!

Executing MySQL query after every 2 minutes with PHP [duplicate]

Am working on a project where a database row will be updated every 2 minutes and I have written a code for it but the problem is when I refresh the page I have included the code to confirm if the database row is been updated after every 2 minutes, I discovered the database row gets updated even before 2 minutes.

$plan_amount = 100; // plan amount
$inc_profits = 0.05 * $plan_amount; // increase profit by 5%

        // Get current timestamp
        $currentTime = time();

        // Calculate next 2 mins timestamp
        $next24Hours = strtotime($plan_amount_time) + (2 * 60);

        // Check if it's time to execute the query
        if ($currentTime >= $next24Hours) {

            // SQL query to insert data into the database
            $insert = "UPDATE users SET active_plan_amount_time = CURRENT_TIMESTAMP, profits = profits + ? WHERE id = ?";
            $stmt = mysqli_prepare($db, $insert);
            mysqli_stmt_bind_param($stmt, "ii", $inc_profits, $id);
            mysqli_stmt_execute($stmt);

        } else {
            // 2 mins have not passed yet. No action taken
        }

The above code is the code I have written to solve the problem but I still face difficulties. Note that $plan_amount_time is a row with the current timestamp of when last the row was updated.

I updated $plan_amount_time with default timestamp which the code will use to check if current time passed is 2 mins but I still face the same problem.

Target three dots or the ellipsis character

I have this regex:

 $text = preg_replace_callback('/(d+.d+|b[A-Z](?:.[A-Z])*b.?)|([.,;:!?)])s*/', function ($matches) {
        return $matches[1] ? $matches[1] : $matches[2] . ' ';
    }, $text);

Which targets the end of sentences and avoids abbreviations like N.B.C.

It works fine. The problem is that it doesn’t detect tree dots ... or the ellipsis symbol as the end of the sentence.

How can I adjust the regex to include it as well?

$_POST how to check for email and password? [closed]

if(!isset($_POST['email'], $_POST['password'])) {
    exit('Please fill both the email and password fields!');
}

I put both the email and password into the input fields but it is saying the error. How do I solve this? Thank you.

If both inputs are filled, it should do this but it doesn’t:

if($stmt = $con->prepare('SELECT id, password FROM accounts WHERE email = ?')) {
    $stmt->bind_param('s', $_POST['email']);
    $stmt->execute();
    $stmt->store_result();

    if($stmt->num_rows > 0) {
        $stmt->bind_result($id, $password);
        $stmt->fetch();

        if(password_verify($_POST['password'], $password)) {
            session_regenerate_id();
            $_SESSION['loggedin'] = true;
            $_SESSION['name'] = $_POST['email'];
            $_SESSION['id'] = $id;
            echo 'Welcome' . $_SESSION['name'] . '!';
        } else {
            echo 'Incorrect email and/or password!';
        }
    } else {
        echo 'Incorrect email and/or password';
    }

    $stmt->close();

HTML CODE:

        <form action="authenticate.php" method="post">
                  <div style="display: inline-block; text-align:left;">

      <div>
      <label for="name">Email Address:</label>
      <input type="email" name="email" id="email" placeholder="Enter your email address" />
      </div>
      <div>
      <label for="password">Password:</label>
      <input type="password" name="password" id="password"  placeholder="Enter your password" />
      </div>

  </div>

     <div class="checkbox">
     <label><input type="checkbox" class="checkbox" />Remember me</label>
      </div>

<input type="submit" value="Login" />

How to display the MAC Address in Web?

Is there a way to display the MAC address of a computer using PHP or JavaScript?

I have not tried anything yet but I am still researching on a way to do that.

I do hope that you can help me or give me an idea on how can I get the MAC Address.

Page not found error on Few Pages . that is hosted on hostinger using Almalinux

HI i am hosting my php website on Hostinger using AlmaLinux8 64bit. i having issue with my website few pages not loading , i am getting page not found error. but in my local Wamp server its working fine. i am attaching the both apache httpd file and my .htaccess file please help.

httpd
https://docs.google.com/document/d/1rB5miyBDuzt_uiX9O3BIMLH-wIlzdmk7q9V4ypXeWdI/edit?usp=drive_link

.htaccess
https://docs.google.com/document/d/10jzW_BHBnWaKztlBrfhMikVn-b-3RxrVBSAJAWhvXko/edit?usp=drive_link

I am getting an “Page Not Found error”

PHP YouTube API not working on my hosting

I am getting mp4 URL from YouTube API with PHP. But it works on local server and not on hosting.

Here is a screenshot of the error I got:
screenshot

I am getting mp4 URL of video from YouTube API with PHP. I am using these codes:


<?php

function getVideoInfo($video_id){

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'https://www.youtube.com/youtubei/v1/player?key=[key]');

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, '{  "context": {    "client": {      "hl": "en",      "clientName": "WEB",      "clientVersion": "2.20210721.00.00",      "clientFormFactor": "UNKNOWN_FORM_FACTOR",   "clientScreen": "WATCH",      "mainAppWebInfo": {        "graftUrl": "/watch?v='.$video_id.'",           }    },    "user": {      "lockedSafetyMode": false    },    "request": {      "useSsl": true,      "internalExperimentFlags": [],      "consistencyTokenJars": []    }  },  "videoId": "'.$video_id.'",  "playbackContext": {    "contentPlaybackContext": {        "vis": 0,      "splay": false,      "autoCaptionsDefaultOn": false,      "autonavState": "STATE_NONE",      "html5Preference": "HTML5_PREF_WANTS",      "lactMilliseconds": "-1"    }  },  "racyCheckOk": false,  "contentCheckOk": true}');

    curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $headers = array();

    $headers[] = 'Content-Type: application/json';

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);

    if (curl_errno($ch)) {

        echo 'Error:' . curl_error($ch);

    }

    curl_close($ch);

    return $result;

}

print_r(getVideoInfo("[video_id]"));

There is no problem running on local server. I am able to get the mp4 URL of the video. But when I upload the files to the hosting and run it, the URL from the API tells me “This content isn’t available.” fetches an mp4 file containing the text. How can I solve this? Both are the same code, but what could be the reason why it works on local server and not on hosting?

Krizalys Onedrive session client state

I’m using this library https://github.com/krizalys/onedrive-php-sdk. The starting steps look good, after successful authentication, I can use $_SESSION['onedrive.client.state'] to work.

$client = Onedrive::client(
$config['ONEDRIVE_CLIENT_ID'],[
'state' => $_SESSION['onedrive.client.state'],
]
);

But when the session expires, it gives error Fatal error: Uncaught MicrosoftGraphExceptionGraphException: [0]: No access token has been provided I can’t start index.php and ‘rediect.php’ over again every time.

I have many search but not found results.

Thanks

Fatal error: Uncaught MicrosoftGraphExceptionGraphException: [0]: No access token has been provided

PHP: Equal Sides Of An Array

I’m trying to build a function that returns the index of an array where equal sides of the array sum to the same value.

I can get all tests to pass apart from this one:
$this->assertSame(6,find_even_index([10,-80,10,10,15,35,20]));

I don’t understand why this test has been added by Codewars when it doesn’t seem correct? Index 6 is the last item, and doesn’t have a right side to equate.

Challenge was taken from Codewars:
https://www.codewars.com/kata/5679aa472b8f57fb8c000047/solutions/php

Code:

$numbers = [10,-80,10,10,15,35,20];

echo getEqualSidesIndex($numbers) . PHP_EOL;

function getEqualSidesIndex(array $numbers) : int {
    foreach ($numbers as $key => $value) {
        if ($key < 1) {
            continue; 
        }
    
        $itemsBeforeCurrent = array_slice($numbers, 0, $key - 1);
        $itemsAfterCurrent = array_slice($numbers, $key, count($numbers) - 1);

        if (array_sum($itemsBeforeCurrent) == array_sum($itemsAfterCurrent)) {
            return $key - 1;
        }
    }

    return -1;
}

Tests:

class FindEvenIndexTest extends TestCase
{
    public function testIt() {
      $this->assertSame(3,find_even_index(array(1,2,3,4,3,2,1)));
      $this->assertSame(1,find_even_index([1,100,50,-51,1,1]));
      $this->assertSame(-1,find_even_index([1,2,3,4,5,6]));
      $this->assertSame(3,find_even_index([20,10,30,10,10,15,35]));
      $this->assertSame(0,find_even_index([20,10,-80,10,10,15,35]));
      $this->assertSame(6,find_even_index([10,-80,10,10,15,35,20]));
      $this->assertSame(-1,find_even_index(range(1,100)));
      $this->assertSame(0,find_even_index([0,0,0,0,0]),"Should pick the first index if more cases are valid");
      $this->assertSame(3,find_even_index([-1,-2,-3,-4,-3,-2,-1]));
      $this->assertSame(-1,find_even_index(range(-100,-1)));

    }
}

Instructions:

You are going to be given an array of integers. Your job is to take
that array and find an index N where the sum of the integers to the
left of N is equal to the sum of the integers to the right of N. If
there is no index that would make this happen, return -1.

For example:

Let’s say you are given the array {1,2,3,4,3,2,1}: Your function will
return the index 3, because at the 3rd position of the array, the sum
of left side of the index ({1,2,3}) and the sum of the right side of
the index ({3,2,1}) both equal 6.

Let’s look at another one. You are given the array {1,100,50,-51,1,1}:
Your function will return the index 1, because at the 1st position of
the array, the sum of left side of the index ({1}) and the sum of the
right side of the index ({50,-51,1,1}) both equal 1.

Last one: You are given the array {20,10,-80,10,10,15,35} At index 0
the left side is {} The right side is {10,-80,10,10,15,35} They both
are equal to 0 when added. (Empty arrays are equal to 0 in this
problem) Index 0 is the place where the left side and right side are
equal.

Note: Please remember that in most programming/scripting languages the
index of an array starts at 0.

Input: An integer array of length 0 < arr < 1000. The numbers in the
array can be any integer positive or negative.

Output: The lowest index N where the side to the left of N is equal to
the side to the right of N. If you do not find an index that fits
these rules, then you will return -1.

Note: If you are given an array with multiple answers, return the
lowest correct index.

PHP – How would I save user theme preferences in an SQL database so when users login it changes themes?

I’m currently making a music streaming website for fun and trying to add some cool features to it. One of them I came up with is storing dark mode, light mode and background theme preferences (CSS) in the users SQL data so when they login to any device on the same account it will automatically adjust to their theme preferences without having to fiddle around in settings again and again.

Looking at basic tutorials, none of them really mention storing themes in user accounts and more focus on a temporary cookies approach with I personally really don’t like.

Anyone got any ideas? It would literally just be a choice between light-mode.css or dark-mode.css and changing links to the backgrounds.

Thanks,

That’s Interesting.

Nothing, this is just a random idea and need some code to make it work!

Failed to load resource: the server responded with a status of 403 (Forbidden) laravel

Why the browser is not showing the full path which includes the the name of the image, instead it ends at the last folder “uploads”?
Elements tab
When I inspect from the browser it shows me this error in the “console” tab: “Failed to load resource: the server responded with a status of 403 (Forbidden)”.
Console tab
This is my code:

<img class="custom_img" src="{{ asset('assets/admin/uploads').'/'.$data['photo'] }}"  alt="لوجو الشركة">

It is connected to a table in MySQL database on XAMPP, every other column in the table is updated without a problem except the image.
DB table

I have tried to clear the cache in the browser, and tried “php artisan dump-autoload”.

Get Top 3 from a table in Access with SUM

I’m trying to get a Top 3 from a table in MS Access with SQL but I can’t wrap my head around it.

My_table:

ControlPoint / Points /  Date      / ByWho
---------------------------------------------
   FlagA         6      202305    DepartmentA
   FlagB         5      202305    DepartmentA
   FlagC         1      202305    DepartmentA
   FlagA         3      202305    DepartmentA
   FlagD         3      202305    DepartmentA

   FlagA         1      202305    DepartmentB
   FlagA         3      202304    DepartmentA

The user chooses a “DepartamentX” and “Date”. After that I want to show the top 3 “ControlPoint” according to the SUM of points. So in this case for “Date: 202305” and “DepartmentA” the result would be =
FlagA 9
FlagB 5
FlagD 3

So what is the best way to do this? By sorting as top 3 direct in SQL or make an array in PHP and then sort it? And then how?

PHP Time Slots Dropdown Issue

Using help from here I have built a page with a dropdown that displays timeslots between a start and end date and time. The time intervals then loop through every 15 minutes or 30 minutes depending on the setting.

It is day of week based, but the client now wants us to add the feature to block out a certain date/time within a season.

EG:

Season 1 – 1 April 2023 to 1st October 2023 (open from 07:30 to 21:00)

Rule 1 – 1st June 2023 closed between 09:00 and 11:00
Rule 2 – 2nd June 2023 closed between 09:00 and 11:00

With my example code below I have adapted line 67 but it doesnt display the times as closed, can anyone help please?

<?php

$airfield_id = '1';

include "../admin/includes/global.php";

if(!isset($_GET['date'])){                  
    $date = date('d-m-Y');          
}else{          
    $date = $_GET['date'];          
} 

if(!isset($_GET['date'])){
    list($day, $month, $year) = explode('-', date('d-m-Y 00:00:00')); 
    $timestamp = $month.'/'.$day.'/'.$year; 
    $timestamp = strtotime($timestamp);
}else{
    list($day, $month, $year) = explode('-', $_GET['date']); 
    $timestamp = $month.'/'.$day.'/'.$year; 
    $timestamp = strtotime($timestamp);
}

// see what season we are in
$sql = "SELECT * FROM `seasons` WHERE `season_from` <= '".$timestamp."' AND `season_to` >= '".$timestamp."' AND `airfield_id` = '".$airfield_id."' LIMIT 1";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
    $season_id = $row['season_id'];
    $open_from = $row['open_from'];
    $open_to = $row['open_to'];
}

$startTime     = $open_from;
$endTime       = $open_to;
$interval      = 15; // minutes
$weekNumber    = date('w', strtotime($_GET['date']));
$allowed = 1;

$sql2 = "SELECT * FROM timetable WHERE airfield_id = '".$airfield_id."' AND season = '".$season_id."'"; 
$result2 = $conn->query($sql2);
$excludedSlots = array();
while($row = $result2->fetch_assoc()) {
    foreach(json_decode($row['timetable_days']) as $tday){
        $excludedSlots[] = array('day' => $tday, 'start' => $row['start_time'], 'end' => $row['end_time'], 'start_date' => $row['start_date'], 'end_date' => $row['end_date']);
    }
}

print_r($excludedSlots);

//$excludedSlots = [
    //['day' => '4', 'start' => '10:00', 'end' => '12:00'],
    //['day' => '4', 'start' => '12:30', 'end' => '13:30'],
    //['day' => '4', 'start' => '15:30', 'end' => '16:00']
//];

$timeRange = generateTimeRange($startTime, $endTime, $interval, $weekNumber, $excludedSlots, $conn, $airfield_id, $allowed);
echo $timeRange;

function generateTimeRange($startTime, $endTime, $interval, $weekNumber, $excludedSlots, $conn, $airfield_id, $allowed) {
    $timeRange = '';
    $currentTime = $startTime;
    $currentDate = time();

    while ($currentTime <= $endTime) {
        $isExcluded = false;

        foreach ($excludedSlots as $excludedSlot) {
            if ($weekNumber == $excludedSlot['day'] && $currentTime >= $excludedSlot['start'] && $currentTime <= $excludedSlot['end'] && $currentDate >= $excludedSlot['start_date'] && $currentDate <= $excludedSlot['end_date']) {
                $isExcluded = true;
                break;
            }
        }
        
        if(!isset($_GET['date'])){                  
            $date = date('d-m-Y');          
        }else{          
            $date = $_GET['date'];          
        } 
        
        $timestamp = strtotime($date." ".$currentTime);
        
        $booked = "SELECT * FROM `requests` WHERE `date` = '".$timestamp."' AND `airfield_id` = '".$airfield_id."' AND status != 'denied'";  
        $result = $conn->query($booked);
        $num_reqs = mysqli_num_rows($result);       


        if (!$isExcluded && !$num_reqs >= $allowed) {
            $timeRange .= "<option value='{$currentTime}'>{$currentTime}</option>";
        } else {
            $timeRange .= "<option value='{$currentTime}' disabled>{$currentTime} (Unavailable)</option>";
        }

        $currentTime = date('H:i', strtotime($currentTime) + ($interval * 60));
    }

    return $timeRange;
}
?>

Edited line 67 by adding:

&& $currentDate >= $excludedSlot['start_date'] && $currentDate <= $excludedSlot['end_date']

And adding:

$currentDate = time();

How to get the Data in a Wordpad to the MySql DB using php [closed]

The requirement is to save the data in the wordpad to the mysql Database and show the exact same output that the user is entering in the wordpad to a new webpage. The Wordpad Image and the code is given below.
enter image description here

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="../css/froala_editor.css">
  <link rel="stylesheet" href="../css/froala_style.css">
  <link rel="stylesheet" href="../css/plugins/code_view.css">
  <link rel="stylesheet" href="../css/plugins/colors.css">
  <link rel="stylesheet" href="../css/plugins/emoticons.css">
  <link rel="stylesheet" href="../css/plugins/image_manager.css">
  <link rel="stylesheet" href="../css/plugins/image.css">
  <link rel="stylesheet" href="../css/plugins/line_breaker.css">
  <link rel="stylesheet" href="../css/plugins/table.css">
  <link rel="stylesheet" href="../css/plugins/char_counter.css">
  <link rel="stylesheet" href="../css/plugins/video.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css">

  <style>
    body {
      text-align: center;
    }

    div#editor {
      width: 81%;
      margin: auto;
      text-align: left;
    }
  </style>
</head>

<body>
  <div id="editor">
    <div id='edit' style="margin-top: 30px;">
      <h1>Full Page</h1>

      <p>Using the <a href="https://www.froala.com/wysiwyg-editor/v2.0/docs/options#fullPage" title="fullPage option"
          target="_blank">fullPage</a> option allows the usage of <code>HTML</code>, <code>HEAD</code>,
        <code>BODY</code> tags and <code>DOCTYPE</code> declaration. Switch to Code view to see the HTML code.</p>
      dolor sit amet, consectetur <strong>adipiscing <em>elit.</em> Donec</strong> facilisis diam in odio iaculis
      blandit. Nunc eu mauris sit amet purus <strong>viverra</strong><em> gravida</em> ut a dui.<br />
      <ul>
        <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pharetra ante vitae finibus tristique. Nunc interdum dolor ac mattis ultricies. Fusce in ex vitae turpis varius porttitor. Integer sed molestie nisi. Aliquam venenatis sem a felis lobortis, vitae facilisis tortor consequat. Ut lacinia lacinia semper. Quisque et tempus ante.</li>
        <li>Sed leo ligula, interdum in neque eget, convallis efficitur felis. Nam at massa sed ex luctus ullamcorper. Sed vestibulum pellentesque tincidunt. Quisque molestie a nunc id congue. Maecenas ut condimentum mauris, vel iaculis risus. Nullam fringilla nisl nibh, nec facilisis mi cursus non. Quisque eros risus, rutrum a sagittis eget, fermentum et massa. Nunc vehicula nisl ante, non rutrum ligula ullamcorper non
            <li>Nam lacus nulla, consequat ac lacus sit amet, accumsan pellentesque risus. Aenean viverra mi at urna
              mattis fermentum.</li>
              <li>Nam lacus nulla, consequat ac lacus sit amet, accumsan pellentesque risus. Aenean viverra mi at urna
                mattis fermentum.</li>
          </ol>
        </li>
      </ul>
    </div>
  </div>

  <script type="text/javascript"
    src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.js"></script>
  <script type="text/javascript"
    src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/xml/xml.min.js"></script>
  <script type="text/javascript" src="../js/froala_editor.min.js"></script>
  <script type="text/javascript" src="../js/plugins/align.min.js"></script>
  <script type="text/javascript" src="../js/plugins/code_beautifier.min.js"></script>
  <script type="text/javascript" src="../js/plugins/code_view.min.js"></script>
  <script type="text/javascript" src="../js/plugins/colors.min.js"></script>
  <script type="text/javascript" src="../js/plugins/draggable.min.js"></script>
  <script type="text/javascript" src="../js/plugins/emoticons.min.js"></script>
  <script type="text/javascript" src="../js/plugins/font_size.min.js"></script>
  <script type="text/javascript" src="../js/plugins/font_family.min.js"></script>
  <script type="text/javascript" src="../js/plugins/image.min.js"></script>
  <script type="text/javascript" src="../js/plugins/image_manager.min.js"></script>
  <script type="text/javascript" src="../js/plugins/line_breaker.min.js"></script>
  <script type="text/javascript" src="../js/plugins/link.min.js"></script>
  <script type="text/javascript" src="../js/plugins/lists.min.js"></script>
  <script type="text/javascript" src="../js/plugins/paragraph_format.min.js"></script>
  <script type="text/javascript" src="../js/plugins/paragraph_style.min.js"></script>
  <script type="text/javascript" src="../js/plugins/table.min.js"></script>
  <script type="text/javascript" src="../js/plugins/video.min.js"></script>
  <script type="text/javascript" src="../js/plugins/url.min.js"></script>
  <script type="text/javascript" src="../js/plugins/entities.min.js"></script>
  <script type="text/javascript" src="../js/plugins/char_counter.min.js"></script>
  <script type="text/javascript" src="../js/plugins/inline_style.min.js"></script>
  <script type="text/javascript" src="../js/plugins/save.min.js"></script>

  <script>
    (function () {
      new FroalaEditor("#edit", {
        fullPage: true
      })
    })()
  </script>
</body>

</html>

Example- The user is typing one word in a sentence in Bold. The webpage which shows the output should also have the word Bold. How can implement this?

Thank you in advance.

How manage unauthorized request error response using laravel passport

I am using laravel 10.17.1 and for api using 11.*.

I have add multi authenticate for passport like this in config/auth.php :

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'user-api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
    'customer' => [
        'driver' => 'session',
        'provider' => 'customers',
    ],
    'customer-api' => [
        'driver' => 'passport',
        'provider' => 'customers',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => User::class,
    ],
    'customers' => [
        'driver' => 'eloquent',
        'model' => Customer::class,
    ],
],

And also add scope app/Providers/AuthServiceProvider.php :

public function boot(): void
{
    Passport::tokensCan([
        'user' => 'User Type',
        'customer' => 'Customer User Type',
    ]);

}

Add scope class in app/Http/Kernel.php in $middlewareAliases array for passport :

'scopes' => LaravelPassportHttpMiddlewareCheckScopes::class,
    'scope' => LaravelPassportHttpMiddlewareCheckForAnyScope::class,

Add routes for api :

Route::middleware([
'api',
])->prefix('api')->group(function () {
    
Route::post('customer/login',[ApiAuthController::class, 'customerLogin'])->name('customer.Login');
Route::group( ['prefix' => 'customer','middleware' => ['auth:customer-api','scopes:customer'] ],function(){
    Route::get('dashboard',[ApiCustomerController::class, 'clientDashboard']);
    Route::get('/',[ApiCustomerController::class, 'getCustomer']);
});

});

Function view like this ApiAuthController.php :

public function customerLogin(Request $request)
{
    $validator = Validator::make($request->all(), [
        'email' => 'required|email',
        'password' => 'required',
    ]);

    if($validator->fails()){
        return response()->json(['error' => $validator->errors()->all()]);
    }

    $credentials = $request->only(['email', 'password']);
    if (Auth::guard('customer')->attempt($credentials)) {
        $tokenMenager = Auth::guard('customer')->user()->createToken('cutomerToken', ['customer']);
        $success ['token'] = $tokenMenager->accessToken;
        $success ['customer'] = Auth::guard('customer')->user();

        return $this->sendResponse($success, "Customer login successfully.");
        } else {
                return response()->json([
                        'error' => 'Incorrect email or password.',
        ], 401);
    }
}

Function view like this ApiCustomerController.php :

/**
 * Get customer data
 */
public function getCustomer()
{
    return $this->sendResponse(auth()->user(), 'Customer collection');
}

And also changed Authenticate.php Middleware file like this :

protected function redirectTo(Request $request): ?string
{
    if ($request->expectsJson()) {
        return null;
    } else {
        if ($request->is('api/*')) {
            return response()->json([
                'status' => 401,
                'message' => 'Unauthorized',
            ], 401);
            // return response()->json(['success' => false, 'message' => "Unauthorized Request"], 401);
        } elseif ($request->getHttpHost() == config('constants.app_host')) {
            return route('admin.login');
        } else {
            return route('login');
        }
    }
}

When I hit login api I got token in response and than add token in get customer api, this api check authentication if I don’t sent token with request It will redirect to login page because I have changed Authenticate.php file now I also update for api request and I have added response as json but in response, I am getting error :

ErrorException: Header may not contain more than a single header, new line detected in file /var/www/html/photoapp/vendor/symfony/http-foundation/Response.php on line 376

enter image description here

How can I send error message in response if customer unauthorized ?