vendredi 28 juillet 2023

Writing Laravel code for the find total duration using data

I am facing one problem for finding total duration in Laravel 9. I tried many methods but it not getting correct hours and mins. Here is the data:

"Arrival_DateTime": "08/28/2023 21:50",
"Departure_DateTime": "08/28/2023 20:00",
"Arrival_DateTime1": "08/29/2023 03:10",
"Departure_DateTime1": "08/29/2023 02:00",

Output want below hours and mins

"duration": "8 h 40 m","layover": "4 hr 10m"

also if same calculation add tow more timing also please suggest me the code.

I tried using strtotime and total calculate but it

Output want below hours and mins

"duration": "8 h 40 m","layover": "4 hr 10m"


via Chebli Mohamed

mardi 25 juillet 2023

Class "App\Http\Controllers\User\Auth\Hash" no

I.m a noob @laravel, so i don't know what to do. its a password reset form that gives the error after the submit button is clicked.

Class "App\Http\Controllers\User\Auth\Hash" no

$user->password = Hash::make($request->password);

after receiving an otp code the user is redirected to this form to input new password but i get this error.

<?php

namespace App\Http\Controllers\User\Auth;

use App\Http\Controllers\Controller;
use App\Models\PasswordReset;
use App\Models\User;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;
use Illuminate\Validation\Rules\Password;

class ResetPasswordController extends Controller {
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;


    public function __construct() {
        parent::__construct();
        $this->middleware('guest');
    }

    public function showResetForm(Request $request, $token = null) {

        $email = session('fpass_email');
        $token = session()->has('token') ? session('token') : $token;
        if (PasswordReset::where('token', $token)->where('email', $email)->count() != 1) {
            $notify[] = ['error', 'Invalid token'];
            return to_route('user.password.request')->withNotify($notify);
        }
        return view($this->activeTemplate . 'user.auth.passwords.reset')->with(
            ['token' => $token, 'email' => $email, 'pageTitle' => 'Reset Password']
        );
    }

    public function reset(Request $request) {

        session()->put('fpass_email', $request->email);
        $request->validate($this->rules(), $this->validationErrorMessages());
        $reset = PasswordReset::where('token', $request->token)->orderBy('created_at', 'desc')->first();
        if (!$reset) {
            $notify[] = ['error', 'Invalid verification code'];
            return to_route('user.login')->withNotify($notify);
        }

        $user = User::where('email', $reset->email)->first();
        $user->password = Hash::make($request->password);
        $user->save();

        $userIpInfo = getIpInfo();
        $userBrowser = osBrowser();
        notify($user, 'PASS_RESET_DONE', [
            'operating_system' => @$userBrowser['os_platform'],
            'browser' => @$userBrowser['browser'],
            'ip' => @$userIpInfo['ip'],
            'time' => @$userIpInfo['time']
        ], ['email']);


        $notify[] = ['success', 'Password changed successfully'];
        return to_route('user.login')->withNotify($notify);
    }


    /**
     * Get the password reset validation rules.
     *
     * @return array
     */
    protected function rules() {
        $passwordValidation = Password::min(6);
        $general = gs();
        if ($general->secure_password) {
            $passwordValidation = $passwordValidation->mixedCase()->numbers()->symbols()->uncompromised();
        }
        return [
            'token' => 'required',
            'email' => 'required|email',
            'password' => ['required', 'confirmed', $passwordValidation],
        ];
    }
}

expecting the password of the user to be changed



via Chebli Mohamed

lundi 24 juillet 2023

Sort an eloquent query based on the field of a nested model

I have this eloquent query that brings me 10 reports in a paginated manner with their respective transactions and contracts

            $reports = Report::with([
                "transaccions",
                "status_report",
                "contracts",
            ])
                ->where(function ($query) use ($filter, $dates, $type_report, $dataservice) {
                    $query
                        ->where("type_report", ($dataservice == 'true' ? '<>' : '='), $type_report)
                        ->whereBetween("created_at", [$dates[0], $fechas[count($dates) - 1]])
                        ->whereHas('status_report', function ($q) {
                            $q->whereIn("status", ["VERIFYED"]);
                        })
                        ->where(function ($query) use ($filter) {
                            $query->where("id", "like", '%' . $filter . '%')
                                ->orWhereHas('contracts', function ($query) use ($filter) {
                                    $query->where('contract', 'like', '%' . $filter . '%')
                                        ->orWhereHas("rif", function ($query) use ($filter) {
                                            $query->where("rif", 'like', '%' . $filter . '%');
                                        })
                                        ->orWhere("name", 'like', '%' . $filter . '%');
                                })->orWhereHas('transaccions', function ($query) use ($filter) {
                                    $query->where('ref', 'like', '%' . $filter . '%')
                                        ->orWhere('amount', 'like', '%' . $filter . '%');
                                });
                        });
                })
                ->paginate($length);

This query shows a result that is processed in another function and shows something like this

        {
            "id": 45751,
            "status": "VERIFYED",
            "type_report": "MENSUALITY",
            "nota": "",
            "transaccions": [
                {
                    "id": 46358,
                    "ref": "22380011359",
                    "voucher": false
                }
            ],
            "total": "1,28",
            "contracts": [
                {
                    "name": "PERSON",
                    "contract": "123456",
                    "rif": "1122334455",
                    "status": "ACTIVE"
                }
            ],
            "created_at": "2022-08-26 14:18:00"
        },

These results are displayed in a table and I would like to be able to sort the results based on transactions.amount, contracts.contract (or any other field from the nested models) but I can't find the way to do it, I know that you can order the nested models in this way:

             "transaccions" => function ($query) use ($order_by, $order) {
                    $query->orderBy($order_by, $order);
                },

but I need is to sort all the results, because that only sorts me the nested objects, thanks.



via Chebli Mohamed

mercredi 19 juillet 2023

How to delete record using where 2 conditions (AND) in Laravel?

When I do delete record in controller, laravel deletes condition one by one. Not two conditions at once. Has anyone experienced this issue? what's the solution?

can delete records for 2 conditions that have been determined, not delete records every single condition.



via Chebli Mohamed

Laravel specify channel in logger()->

I have this multiple channels in logging.php, want to specify the logger()->'s channel so that I can specify the log. I know Log::channel('channel name')-> but I want to use logger(). I'm using laravel 5.6



via Chebli Mohamed

lundi 17 juillet 2023

AWS SQS crashed in Laravel/Lumen

I have setup lumen microservice v9.0 and installed the following dependecies

"php": "^8.0",
"aws/aws-sdk-php": "^3.263",
"dusterio/laravel-aws-worker": "^0.1.36",
"illuminate/redis": "^9.52",
"laravel/lumen-framework": "^9.0",
"predis/predis": "^2.1",
"pusher/pusher-php-server": "^7.2"

When I dispatch job from one microservice to this microservice, SQS job received but when is job received its crash with following error

ERROR: Unresolvable dependency resolving [Parameter #3 [ callable $isDownForMaintenance ]] in class Illuminate\Queue\Worker {"exception":"[object] (Illuminate\Contracts\Container\BindingResolutionException(code: 0): Unresolvable dependency resolving [Parameter #3 [ callable $isDownForMaintenance ]] in class Illuminate\Queue\Worker at /var/app/current/vendor/illuminate/container/Container.php:1118)

Even two days before this code was working fine but today after deployment its working stop and getting crashed. Can anyone help me to resolve this issue I have spent a lot of time to fix this issue but failed

bootstrap/app.php

$app->register(Dusterio\AwsWorker\Integrations\LumenServiceProvider::class);


via Chebli Mohamed

samedi 15 juillet 2023

Validation - Laravel [closed]

{
    "status": true,
    "message": {
        "main_1": {
            "chalet_main_facility_sub_facilities": [
                "sub_1",
                "sub_2",
                "sub_3"
            ]
        },
        "main_2": {
            "chalet_main_facility_sub_facilities": [
                "sub_1",
                "sub_2",
                "sub_3"
            ]
        },
        "ma": {
            "chalet_main_facility_sub_facilities": [
                "sub_1"
            ]
        }
    }
}

the array key "main_1", "main_2" and "ma" must be required|string|max:45 ??

I have a database like this chalet_main_facilities contains a title this title is 45 max length and each chalet_main_facilities contains chalet_main_facility_sub_facilities contains a title this title is 75 max length

chalet_main_facilities Table

chalet_main_facility_sub_facilities Table

laravel validator ↴

$validator = Validator($request->all(), [
    'chalet_main_facilities' => 'required|array|min:1',
    'chalet_main_facilities.*' => 'required|array|distinct|size:1',
    'chalet_main_facilities.*.chalet_main_facility_sub_facilities' => 'required|array|min:1',
    'chalet_main_facilities.*.chalet_main_facility_sub_facilities.*' => 'required|string|min:3|max:255',

]);


via Chebli Mohamed

Error authenticating user and displaying validation messages in Laravel

I'm facing difficulties with user authentication and displaying validation messages in Laravel. When attempting to log in, the user is not authenticated correctly, and the validation error messages are not displayed.

I followed the official Laravel documentation for authentication and validation, but I'm not getting the expected result even with the help of artificial intelligence. Here are some of my code snippets:

public function store(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    $credentials = $request->only('email', 'password');

    if (auth()->attempt($credentials)) {
        $user = auth()->user();
        $request->session()->put('user', $user);
        return redirect()->route('home');
    }

    throw ValidationException::withMessages([
        'email' => 'Invalid email or password.',
    ]);
}

Here is the HTML code:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <form action="/login" method="post">
    @csrf
        <input type="email" name="email" placeholder="Email">
        <input type="password" name="password" placeholder="Password">
        <input type="submit" value="Login">
    </form>
</body>
</html>

And finally, the routes:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\LoginController;

Route::get('/users', [UserController::class, 'index'])->name('users.index');
Route::get('/users/create', [UserController::class, 'create']);
Route::post('/users', [UserController::class, 'store']);
Route::get('/users/{user}', [UserController::class, 'show']);
Route::get('/users/{user}/edit', [UserController::class, 'edit']);
Route::put('/users/{user}', [UserController::class, 'update']);
Route::delete('/users/{user}', [UserController::class, 'destroy'])->name('users.destroy');

Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::get('/login', [LoginController::class, 'index'])->name('login');
Route::post('/login', [LoginController::class, 'store']);
?>

I attempted to authenticate the user using the credentials provided in the login form. I expected Laravel to correctly authenticate the user if the credentials were correct. I also set validation rules in the store() method of the LoginController using $request->validate([...]). I expected that if the email and password fields were not filled correctly, Laravel would display the error messages on the login.blade.php view.

When I submit the login form with correct credentials, Laravel doesn't authenticate the user correctly and redirects back to the login page without displaying any error messages. When I submit the form with empty fields or invalid data, the corresponding error messages are also not displayed on the view. Instead, the form is redirected back to the login page without any feedback.

I believe something is missing or configured incorrectly because Laravel is not authenticating the user correctly and not displaying the validation messages.

I would appreciate any help you can provide to solve this issue.



via Chebli Mohamed

mardi 11 juillet 2023

ErrorException: htmlspecialchars() expects parameter 1 to be string laravel . Not sending any data to blade

I am getting this exception even though I am not sending any data. Sometime it works when I logout and login again after getting error. Any clue what might be wrong?

Only things I am accessing in the blade are-



I tried commenting these, Then also I am getting the same error.

Menu item

<li class="menuItems" id="support"><a href="">Admin Support</a></li>

web.php

Route::get('/support','AdminSupport@support')->name('support');

Controller

public function support()
  {
    return view('Admin.support');
  }


via Chebli Mohamed

lundi 10 juillet 2023

laravel gates permission foreach

excuse me, i'm a junior developer and im still learn about laravel gates concept. i have a tables structure like this.

  1. Users = id, email, password, role_id.

  2. role = id, name, description.

  3. permission = id, name, slug.

  4. role_permission = permission_id, role_id. and this is my code

    $permission = Permission::all();

     foreach($permission as $p){
         Gate::define($p->slug, function(User $user) use ($p) {
             return $user->role_id === ???;
         });
     }
    

My Code

what should i return to protect gates, thanks.

im still learning about laravel gates concept, so i hope the other senior developers help me to explain about gates



via Chebli Mohamed

dimanche 2 juillet 2023

undefined variable client_details in laravel

I am new in laravel, I need assistance in displaying data from database on laravel blade view but I am getting the error, "undefined variable client_details" even though it is defined in my controller.

below is what I did in my controller:

namespace paylesotho\Http\Controllers;

use Illuminate\Http\Request;
use paylesotho\Utility_data;
use DB;


class UtilityManagementController extends Controller
{
    //display clients data on a table

    public function index(){
        $clients = Utility_data::latest()->paginate(6);
        return view('manage_utility', ['client_details' => $clients]);
    }
}

below is what I did in my routes

Route::get('/manage_utility', function () {
    return view('manage_utility');
});

Route::get('statistics/', 'UtilityManagementController@index')->name('index');

below is my blade file

div class="container" style="margin-top: 7%;"> 
            <table class="table table-hover">
                <thead>
                <tr>
                    <th>ID Number</th>
                    <th>Client Name</th>
                    <th>Phone Number</th>
                    <th>Address </th>
                    <th>Float Amount</th>
                    <th>Actions</th>
                </tr>
                </thead>
                <tbody>
                @foreach ($client_details as $item)
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td>
                            <a href="" class="btn btn-primary" data-toggle="modal" data-target="">Edit</a>
                            <a href="" class="btn btn-danger" data-action="" data-toggle="modal" data-target="">Delete</a>    
                        </td>
                    </tr> 
                @endforeach 
                </tbody> 
            </table>
            <div class="d-flex">
            {!! $client_details->links('pagination::bootstrap-4') !!}
            </div> 


via Chebli Mohamed