mercredi 17 mars 2021

Frontend user also Logged in When Admin Login in Laravel(both details are on users table) and also logout

Here I using Role Model and Roletype Model but how to stop frontend login when admin gets login? please help me!

User Model:-

protected $fillable = [
    'f_name', 'l_name','email','phone_no', 'password','user_password','api_token','status','provider_name','provider_id'
];

Role Model:-

protected $table = 'roles';
protected $fillable = ['name','display_name','description'];
protected $visible = ['id','name','display_name','description'];
public $timestamps = true;

RoleUser Model:-

protected $table = 'role_user';
protected $fillable = ['user_id','role_id'];
protected $visible = ['user_id','role_id'];
public $timestamps = true;

Wher User Login:-

public function user_login_check(Request $request){
    $msg = [
        'email.required' => 'Enter Your Email',
        'password.required' => 'Enter Your Password',
    ];
    $this->validate($request, [
        'email' => 'bail|required',
        'password' => 'bail|required'

    ], $msg);
    $email = $request->get('email');
    $pass = $request->get('password');
    $uid = User::where('email', $email)->orwhere('phone_no',$email)->value('id');
    $status = User::where('email', $email)->orwhere('phone_no',$email)->value('status');
    $role_id = RoleUser::where('user_id', $uid)->value('role_id');
    $role = Role::where('id', $role_id)->value('name');
    $remember = false;
    if($request->get('remember') !=null){
        $remember = true;
    }
    if ($role == 'user') {
        if($status=='Active'){
            if (Auth::attempt(array('email' => $email, 'password' => $pass,'status'=>'Active'), $remember) || Auth::attempt(array('phone_no' => $email, 'password' => $pass,'status'=>'Active'), $remember)) {
                if($request->session()->has('checkout')){
                    $request->session()->forget('checkout');
                    return redirect(url('/proceed-to-checkout'));
                }else{
                    return redirect(url('/'));
                }
            } else {
                return redirect()->back()->with('login_error', 'Login Failed !!! Please check Your Email/Phone and Password.');
            }
        }else{
            return redirect()->back()->with('login_error', 'Login Failed !!! Please verify your email for login or reset password.');
        }
    }else{
        return redirect()->back()->with('login_error', 'Login Failed !!! Please register first.');
    }
}

Where Admin Login:-

public function Check_login(Request $request)
{
    //  dd($request->all());

    $msg = [
        'email.required' => 'Enter Your Email',
        'password.required' => 'Enter Your Password',
    ];
    $this->validate($request, [
        'email' => 'bail|required|email',
        'password' => 'bail|required|alphaNum|min:3'

    ], $msg);

    $email = $request->get('email');
    $pass = $request->get('password');
    $uid = User::where('email', $email)->value('id');
    if ($uid == '') {
        return redirect()->back()->with('error', 'Login Failed !!! Please check Your Email and Password.');
    } else {
        $role_id = RoleUser::where('user_id', $uid)->value('role_id');
        $role = Role::where('id', $role_id)->value('name');

        if ($role == 'admin') {
            if (Auth::attempt(array('email' => $email, 'password' => $pass, 'status' => 'Active'), true)) {
                $check_email = Auth::user()->email;
                $request->session()->put('email', $check_email);
                $user_type = Auth::user()->user_type;
                $request->session()->put('user_type', $user_type);
                return redirect(route('admin::dashboard'));
            } else {
                return redirect()->back()->with('error', 'Login Failed !!! Please check Your Email and Password.');
            }
        } else if ($role == 'sub admin') {
            if (Auth::attempt(array('email' => $email, 'password' => $pass, 'status' => 'Active'), true)) {
                $check_email = Auth::user()->email;
                $request->session()->put('email', $check_email);
                $user_type = Auth::user()->user_type;
                $request->session()->put('user_type', $user_type);
                return redirect(route('admin::dashboard'));
            } else {
                return redirect()->back()->with('error', 'Login Failed !!! Please check Your Email and Password.');
            }
        }
    }
}

My Middleware:-

public function handle($request, Closure $next)
{
    if ( isset(Auth::user()->id) && (Auth::user()->hasRole(['admin', 'sub admin']))) {
        return $next($request);
    }else{
        return redirect(route('admin'));
    }
}

I check everything before login but why this happen? why I logged in as admin user also gets login with same email ID



via Chebli Mohamed

Randomly Generate 4 digit Code & Check if exist, Then re-generate

My code randomly generates a 4 or 5 digit code along with 3 digit pre-defined text and checks in database, If it is already exists, then it regenerates the code and saves into database.

But sometimes the queries get stuck & become slower, if each pre-defined keyword has around 1000 record.

Lets take an example for one Keyword "XYZ" and Deal ID = 100 and lets say it has 8000 records in database. The do while loops take a lot of time.

$keyword = "XYZ"; // It is unique for each deal id.
dealID = 100; // It is Foreign key of another table.
$initialLimit = 1;
$maxLimit = 9999;

do {
    $randomNo = rand($initialLimit, $maxLimit);
    $coupon = $keyword . str_pad($randomNo, 4, '0', STR_PAD_LEFT);

    $findRecord = DB::table('codes')
        ->where('code', $coupon)
        ->where('deal_id', $dealID)
        ->exists();

    } while ($findRecord == 1);

As soon as the do-while loops end, Record is being inserted into database after above code. But the Above code takes too much time,

The above query is printed as follow in MySQL. like for above example deal id, it has already over 8000 records. The above code keeps querying until it finds. When traffic is high, app becomes slower.

select exists(select * from `codes` where `code` = 'XYZ1952' and `deal_id` = '100');
select exists(select * from `codes` where `code` = 'XYZ2562' and `deal_id` = '100');
select exists(select * from `codes` where `code` = 'XYZ7159' and `deal_id` = '100');

Multiple queries like this get stuck in database. The codes table has around 500,000 records against multiple deal ids. But Each deal id has around less than 10,000 records, only few has more than 10,000.

Any suggestions, How can I improve the above code?

Or I should use the MAX() function and find the code and do the +1 and insert into db?



via Chebli Mohamed

Fetch row betwwen two dates laravel

I have submitted_date column in my database where date is stored like this it is of varchar type

07/10/2020

now i'm retrieving rows using this query if certain row exists between the given dates

 $start_date = \Carbon\Carbon::parse($request->start_date)->format('d/m/Y');
 $end_date=\Carbon\Carbon::parse($request->end_date)->format('d/m/Y');
 $Data = Pos::where('submitted_date', '>=', $start_date)->where('submitted_date', '<=', $end_date)->get();

this query does not return proper result.



via Chebli Mohamed

Query buider Laravel

I have a table to store my articles. I have no pictures in this table, and my photos are in another table. I have added 5 posts and each post has 3 pictures. Now I want to get 5 posts and each post only takes 1 out of 3 pictures of it, how to do ?? i need help, thanks

enter image description here

enter image description here



via Chebli Mohamed

mardi 16 mars 2021

PDF file is not opening on some computers which is created by laravel?

We are creating pdf file whith hepl of laravel This file is opening on majority of laptops and software but not opening in few computers. can't figure out the reason. this is the error they are getting

enter image description here

Code I am using to creating pdf file

 $apiInstance = resolve(\XeroAPI\XeroPHP\Api\AccountingApi::class);
        $result = $apiInstance->getInvoiceAsPdf($this->xeroCredentials->getTenantId(), $invoice->xero_invoice_id, "application/pdf");

        $content = $result->fread($result->getSize());

        Storage::disk('s3')->put(getSettingValue('s3_invoice_pdfs') .$invoice->xero_invoice_number.'.pdf', $content, 'public');


via Chebli Mohamed

Laravel 5.5 Queue Job doesn't respect timeout

I have a job in Laravel 5.5 that doesn't respect the value in the variable public $timeout set on the job as described in the laravel documentation.

If I set the value of $timeout to, for example, 120 seconds I would expect the job to be terminated after it has ran for 120 seconds. I'm using RabbitMQ on a Heroku dyno.

Codebase: Laravel 5.5

Extension: RabbitMQ Queue driver for Laravel

Platform: Heroku dyno (Amazon).

Example code:

class ExampleJob implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 120;

    public function handle()
    {
        DB::statement($this->buildCallStatement());
    }
}

Example Procfile:

worker: php artisan queue:listen rabbitmq --queue=high,medium,low --tries=1 --memory=512 --timeout=0


via Chebli Mohamed

My laravel form is not submitting. What can I do? Please help me and Thank you in advance

Name of my controller is CustomerController. This is my controller. There are 5 fillable field out of which 1 is image.

public function store(Request $request)
{
    $request->validate([
        'name' => 'required',
        'category' => 'required',
        'mobile_number_1' => 'required|min:10|max:10',
        'mobile_number_2' => 'min:10|max:10',
        'aadhar_card' => 'required',
    ]);
    $aadhar_card = $request->file('aadhar_card');
    $new_name = rand() . '.' . $aadhar_card->getClientOriginalExtension();
    $aadhar_card->move(public_path('aadhar_card'), $new_name);
    $form_data = array(
        'aadhar_card' => $new_name,
    );
    Customer::create($form_data);
    $customer = Customer::create([
        'name' => $request->input('name'),
        'category' => $request->input('category'),
        'mobile_number_1' => $request->input('mobile_number_1'),
        'mobile_number_2' => $request->input('mobile_number_2'),
    ]);

    return redirect('customers.index')->with('success', 'Data added successfully.');
}

This is my create form. There are 5 fillable field 1. name ,2. mobile number 1 ,3. mobile number 2 ,Category and aadhar card.

<form method="post" action="" enctype="multipart/form-data">
        @csrf
        <table>
            <tr>
                <td>Name :</td>
                <td><input type="text" name="name" class="form-control" placeholder="Name"></td>
            </tr>
            <tr>
                <td>Category :</td>
                <td>
                    <select name="category" id="category">
                        <option value="Painter">Painter</option>
                        <option value="Contractor">Contractor</option>
                        <option value="Carpenter">Carpenter</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Mobile Number 1 :</td>
                <td><input type="text" name="mobile_nubmer_1" class="form-control" placeholder="Mobile Number"></td>
            </tr>
            <tr>
                <td>Mobile Number 2 :</td>
                <td><input type="text" name="mobile_nubmer_2" class="form-control" placeholder="Mobile Number ( Optional )"></td>
            </tr>
            <tr>
                <td>Aadhar Card :</td>
                <td><input type="file" name="aadhar_card" class="form-control"></td>
            </tr>
            <tr><button type="submit" name="submit" id="submit" class="btn btn-primary">Submit</button></tr>
        </table>
    </form>


via Chebli Mohamed