mercredi 28 décembre 2022

Insert has error when data column is double [closed]

Please help me

when i insert data to mysql has error

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect double value

But column in mysql I set double. I changed to int and float but same error.

I used laravel 5.5

thank you so much !

[[enter image description here](https://i.stack.imgur.com/8E9Qp.jpg)](https://i.stack.imgur.com/iSxoa.jpg)

i already change column price to int and float but same error



via Chebli Mohamed

Cannot use object of type stdClass as array (View: .../para-answers.blade.php)

<?php 
    $options = json_decode($question->answers); 
    $correct_answers = json_decode($question->correct_answers);
    
     $outer_index=0;

?>
<div class="row">
    <div class="col-md-12">
        <ul class="questions-container fullwidth">
          <?php 
          foreach($options as $option) { 
            // dd($user_answers);
            $cAnswer = $correct_answers[$outer_index]->answer;
            $uAnswer = $user_answers[$outer_index];
            // dd($uAnswer);
            // print_r($option->options[0]);
              $sub_options = (array)$option->options;
              $optionsl2  = null;
              // if(isset($option->optionsl2))
              // $optionsl2 = (array) $option->optionsl2; 


            foreach($sub_options as $key => $value)
             $sub_options = $value;
            ?>  
            <li>
                <div class="question">
                    <h3> <span class="language_l1">{!!$option->question !!}</span>
                     
                    </h3> </div>
               
                <div class="select-answer">
                    <ul class="row">
                    <?php $index=0; 
                     
                     foreach($sub_options as $key1 => $value1) { 
                        $correct_answer_class = '';
                        if($cAnswer==$index+1)
                        {
                              $correct_answer_class = 'correct-answer';
                        }
                        
                        $submitted_value = '';
                        if($user_answers) 
                        {
                           if($uAnswer == $index+1) 
                           {
                                $submitted_value = 'checked';
                                
                            }
                        }
                      
                        ?>
                        <li class="col-md-6  answer_radio" >
                            <input type="radio" name="option" id="1radio1"   disabled="">
                           
                        </li>
                        <?php $index++; } ?>
                    </ul>
                </div>
            </li>
            <hr>
            <?php } ?>

        </ul>
    </div>
</div>

Here we got an issue (Cannot use object of type stdClass as array). Please help me to solve this problem. In this we want to show result of students paragraph questions... This project build on laravel 5.2 please check the following errors solve this... I get this error while we take a paragraph exam.



via Chebli Mohamed

mardi 27 décembre 2022

How do I pass a method with my own constraints in a controller that uses request pattern to display data

Merry Christmass team! I have a problem trying to figure out how to pass a method with my own constraints in a controller that is bound to request patter paradigm:

Sample Controller Code:

class SampleController
{
    protected $model = SampleModel::class;
    protected $indexRequest = IndexRequest::class;
 
}

Request Class

class IndexRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */

    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [];
    }

Assume I have a method that I want to do something different.Say I want to fetch some data based on some column constraints. Whats the approach?



via Chebli Mohamed

dimanche 25 décembre 2022

Openwisk getting bad request error(400) while trying to create from Laravel App

Trying to create a openwisk action from laravel, with python zip file, but getting following error

PUT https://192.168.1.13:31001/api/v1/namespaces/_/actions/test_new_03?blocking=true&result=true&overwrite=false` resulted in a `400 Bad Request` response:
{"code":"H6PLPnMvnyTnzhNt6X8IQiAt8IDRAmLK","error":"The request content was malformed:\nUnexpected end-of-input at input (truncated...)

here is my header

'headers' => [
                'Authorization' => 'Basic <token>',
                'stream' => true,
                "Connection" => "keep-alive",
                "content-type" => "application/json"
            ]

using guzzle http.



via Chebli Mohamed

samedi 24 décembre 2022

Error 500 in laravel 5.2 when user was loged in

I was run composer update and composer selfupdate in laravel project now I get error 500 and blank white page after user login and see project pages this picture is my log

laravel log

I run this command

php artisan key:generate
php artisan cache:clear 
composer install
composer dump-autoload

anybody can help me?



via Chebli Mohamed

vendredi 23 décembre 2022

Data is not coming in laravel 5.4 after using timestamp in query

Data is not coming when comparing current time between 2 times to fetch data in Laravel. Both times are saved in the database as timestamp and in query also I am using timestamp. Below is the code i wrote:-

$current_date = strtotime(date('d-m-Y H:i:s'));
        
$bookings = MachineBooking::with('userDetail')->where('machine_id', $machine_id)->where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)->get();

"time_from" and "time_to" both timestamps are saved in bigint format in database. I entered timestamp using search option in direct database also still data did not come. Can someone please tell me where i am making mistake.



via Chebli Mohamed

jeudi 22 décembre 2022

Laravel Eloqunet query on first relation of one to many

I have Two Tables A and B A can have more than B the relation between them is that B has A_id columns in B have A_id and date I have a filter with status (status alpha = first B of A date is less than 30 days,beta = first B of A date is less than 60) when trying to get the status I want to query on the first row in B which has A_id

public function alpha(){
    return $this->hasOne("App/B")->where('date','<',now()->subMonth(1)->toDateString())->where('date','>',now()->subMonth(2)->toDateString());
}
public function beta(){
    return $this->hasOne("App/B")->where('date','<',now()->subMonth(2)->toDateString());
}

This seems to get the job done but failed in specific situation imagine table B has two rows

  1. id = 1 A_id=1 and date is 45 days old
  2. id =2 A_id=1 and date is 70 days old

This should be an alpha since I'm only interested in the First date but the query I've written returns on both alpha and beta how can I fix my query to only check the first occurrence only mind that I can't loop over A's after getting them since I'm using pagination



via Chebli Mohamed

mardi 20 décembre 2022

is there any way to detect which extension is impacting my site? [closed]

My website is about education and has some online tests, but another party has made an extension to autofill answers according to the available question data, Is there any solution to prevent it?

Thanks all

I tried creating another extension to turn it off and force users to download my extension before accessing the site, but the other cheater faked another extension with the same name. and my pagkeid to still access the page



via Chebli Mohamed

Trying to get property of non-object

im getting "Trying to get property 'selleruserid' of non-object" this error. How can i resolve this error?

$selleruserid= 0;


$featured['items'] = Items::with('Ratings')->select('items.item_id', 'items.user_id AS selleruserid', 'items.item_liked','items.item_slug','items.item_preview','items.item_name','items.item_type','users.user_photo','users.username','users.user_document_verified','items.updated_item','items.item_sold','items.free_download','items.item_flash','items.item_type_cat_id','items.regular_price','items.item_token', 'items.mainpage_boost_last')->leftjoin('users', 'users.id', '=', 'items.user_id')->where('items.item_status','=',1)->where('items.mainpage_boost_last','>', $today_date)->where('items.drop_status','=','no')->orderBy(DB::raw('RAND()'))->take($setting['setting']->home_featured_items)->get();


$selleruserid = $featured->selleruserid; // ERROR LINE


$checkuser = Items::checkuser($selleruserid);

I will be glad if you help me thank you



via Chebli Mohamed

lundi 19 décembre 2022

The problem is that when selecting from select it has ware:model, the slider crashes, and when you click on search, it shows 404

When I use livewire The problem is that when selecting from select it has ware:model, the slider crashes, and when you click on search, it shows 404

As shown in the picturesenter image description here

I tried many times but I don't know why

//my view

div class="ne-sidebar sidebar-break-lg col-xl-4 col-lg-12 px-0">

            <div class="sidebar-box item-box-light-md">
              <div class="topic-border color-cinnabar mb-30">
                <div class="topic-box-lg color-cinnabar"> </div>
              </div>
              <div class="bodyimg">
                <form action="" method="post" name="dmarticlesFilter" id="dmarticlesFilter">
                    @csrf
            <div id="dmarticlesfilter_filters">
                <div class="dmarticlesfilter_filters_row">
                <select id="filterCategory634bd4c1cb9b5_0" wire:model="fcategory_id">
                            <option></option>
                            @foreach($firstcategories as $fcat)
                              <option value=""></option>
                            @endforeach
                    </select>



                    <select id="filterCategory634bd4c1cb9b5_1" wire:model="scategory_id">
                            <option></option>
                            @foreach($secondcategories as $scat)
                              <option value=""></option>
                            @endforeach
                    </select>


                        </div>

                        <div class="dmarticlesfilter_filters_values_l">
                            <input placeholder="Title" type="text" name="filterTitle" value="">

                    <span><input type="submit" class="button" id="button" value=""> </span>&nbsp;&nbsp;
                    <a > </a>
                  </div>
                    </div>

                </form>
                </a>
              </div>
            </div>


//my controller

<?php

class HomeComponent extends Component
{
    public $fcategory_id;
    public $scategory_id;
    public $tcategory_id;


    public function render()
    {


        /***************************** */
        $firstcategories = firstcategory::all();
        $secondcategories = secondcategory::where('fcategory_id',$this->fcategory_id)->get();
        $thirdcategories = thirdcategory::where('scategory_id',$this->scategory_id)->get();
        $fourthcategories = fourthcategory::where('tcategory_id',$this->tcategory_id)->get();


        return view('livewire.home-component',['fourthcategories'=>$fourthcategories,'thirdcategories'=>$thirdcategories,'secondcategories'=>$secondcategories,'firstcategories'=>$firstcategories])->layout('layouts.base');
    }
}

I think the problem is with livewire with wire:model



via Chebli Mohamed

dimanche 18 décembre 2022

Returned data from a Script shows select option behind Boostrap Modal on Laravel

I have a simple JavaScript that retrieves set of data from my database and returns the result on my blade page Bootstrap Modal, however, as I enter the keyword value to retrieve, the select option result appears behind the modal form. How can I show it in front or within the modal? I adjusted the height of the modal but still the same. enter image description here



via Chebli Mohamed

vendredi 16 décembre 2022

React + Laravel 5.6 api CORS issue [closed]

I tried all solutions that I could lay my hands and finally, this solution helped progressing 1 step. Laravel 5.6 CORS issue.

However, It is adding duplicate urls in Acess-Control-Allow-Origin' and throwing this error Access to XMLHttpRequest at 'https://test.domain.com/api/login' from origin 'https://test.domain.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'https://test.domain.com, https://test.domain.com', but only one is allowed. Any suggestion how to prevent it?



via Chebli Mohamed

jeudi 15 décembre 2022

Laravel web application is not connecting to mysql localhost but connecting to mysql command line client

I am working on a Laravel web application and trying to run the website on Mysql localhost but I can't able to do that and when I try to connect, it connects to the database present in Mysql command line client. Are they both mysql commad line client and mysql localhost are different or same.

and why the laravel application is connecting directly to mysql command line client

I have share laravel configuration file such as : 1).env 2)app.php 3)database.php

enter image description here enter image description here enter image description here

I try to connect the laravel application with xampp mysql localhost but it didn't connected.



via Chebli Mohamed

Laravel 5.8 Undefined index: app_name [closed]

Undefined index: app_name (View: C:\Users\Hp\Documents\Coding\project_konekthing\erp_rental\framework\resources\views\auth\login.blade.php)

I've only tried to clone from the git when I run it this error occur

What happened? and how to solve it?



via Chebli Mohamed

mardi 13 décembre 2022

syntax error, unexpected 'readonly' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

enter image description here I'm trying to decode qr code form local storage but get following error syntax error, unexpected 'readonly' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)


namespace Crm\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Libern\QRCodeReader\QRCodeReader;

class ScanQrCodeController extends Controller
{

    // public function __construct(string $imagePath)
    // {
    //     $imagePath = $this->imgPath;
    // }
  
        public  function scanQrCode()
        {
            $qrCodeScan = new QRCodeReader();
            
            $data = Storage::exists('public/uploads/companies/1/1/AVL0CQ/testQR.png');
            $url  = Storage::url('public/uploads/companies/1/1/AVL0CQ/testQR.png');
            $imgPath = (string) 'storage/uploads/companies/1/1/AVL0CQ/testQR.png';
            $qrCodeData = $qrCodeScan->decode($imgPath);
             
            return [
                "qr file exists " => $data,
                "url " => $url,
                //  "qr code output"  => $qrCodeData
            ];

        }

}


via Chebli Mohamed

lundi 12 décembre 2022

Single Signin For All Subdomain Or Projects?

Hy All Hope All Are Fine. First Of All Sorry For My English And I Am Totally New And didn't Know About Php My Sql Etc, So Lets Start My Questions With Detail I Purchased too many Projects subdomain1.maindomain subdomain2.maindomain subdomain3.maindomain subdomain4.maindomain May Be In Future I Will Add More Now Simply I Want Single Login For All Subdomains, Mean That User Can Signup In One Of Any Domain But Can Login For All Subdomain As Same Signup For any One Of Above Domain. My Sql Database User Is Same But Mysql Database Is Different One From Other Every Subdomain or Domain Has It's Own Database. Please Tell Me Is It Possible To Login As A One???? Please If It Is Possible Share With Detail Because I Am New. I Did't Try Any Method



via Chebli Mohamed

dimanche 11 décembre 2022

What would be the proper steps to upgrade laravel version 5 to latest version 9

I have an old project which I developed in Laravel 5.3 and I want to upgrade the project to Laravel v9. What are the steps to upgrade?

What I have seen so far on the internet and from my knowledge:

Upgrade to each higher version step by step e.g 5.3 to 5.4 ... 6 to 7 to 8 to 9

I am running php 8 on my macos. And currently, my code is not running because of deprecated methods in php 5.6 that my Laravel 5.3 is using.

How to upgrade properly?

My composer.json file is

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.3.*",
        "appzcoder/crud-generator": "^2.0",
        "laravelcollective/html": "5.3.*",
        "doctrine/dbal": "^2.5",
        "maatwebsite/excel": "~2.1.0",
        "predis/predis": "~1.0",
        "guzzlehttp/guzzle": "~4.0",
        "laravel/scout" : "^2.0",
        "algolia/algoliasearch-client-php": "^1.17",
        "fx3costa/laravelchartjs": "^2.2",
        "gloudemans/notify": "^1.0",
        "pda/pheanstalk": "~3.1"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.0",
        "symfony/css-selector": "3.1.*",
        "symfony/dom-crawler": "3.1.*"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "allow-plugins": {
            "kylekatarnls/update-helper": true
        }
    }
}



via Chebli Mohamed

vendredi 9 décembre 2022

Replacing Google OAuth API in Laravel

I have an app that I was tasked with to renew. However, the app runs a Google OAuth API to authenticate the users. However, this instance of the API no longer works as the company has changed name and thus the old mail domain no longer exists.

E.g: name@companyname.com

Is there a way for me to change the instance of the api so it will allow any gmail to get in.

here's my current controller for the oauth

public function checkUserByToken($social_token)
    {
        $client  = new \Google_Client(['client_id' => env('GOOGLE_CLIENT_ID', '')]);
        $payload = $client->verifyIdToken($social_token);
        if ($payload) {
            $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)oldcompany.com$/i',
            ]);
            if ($validator->fails()) {
                return false;
            }
            $user = User::where('email', $payload['email'])->first();
            if (!$user) {
                $data = [
                    'name'      => $payload['family_name'],
                    'full_name' => $payload['name'],
                    'email'     => $payload['email'],
                    'password'  => bcrypt(str_random(8)),
                ];
                $user = $this->createUser($data);
            }
            $user->forceFill([
                'email' => $payload['email'],
                'email_verified_at' => Carbon::now(),
            ])->save();
            $tokenResult = $user->createToken('Personal Access Client');
            $token = $tokenResult->token;
            $token->expires_at = Carbon::now()->addMonth();
            $token->save();
            $data = [
                    'access_token' => $tokenResult->accessToken,
                    'token_type'   => 'Bearer',
                    'expires_at'   => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString(),
                    'full_name'    => $payload['name'],
                    'avatar'       => $payload['picture'],
                    'role'         => $user->role,
                    'section'      => isset($user->section)?$user->section->name:"",
                    'id'           => $user->id
            ];
            return $data;
        } else {
            return false;
        }
    }

I have tried replacing the google OAuth API in .env and change

 $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)oldcompany.com$/i',
            ]);

to

 $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)newcompany.com$/i',
            ]);

no avail as I think the google API outside of sending back auth token also send back something else but I'm not sure what it is.



via Chebli Mohamed

Controller does not exist in laravel 5.6

I have this error where it said that the controller does not exist

My routes

use App\Http\Controllers\PasienController;  
Route::resource('/pasien', PasienController::class)->only(['index']);

The controller

<?php

namespace App\Http\Controllers;

use App\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use RealRashid\SweetAlert\Facades\Alert;

class PasienController extends Controller
{
    public function index(Request $request)
    {
        $patient = null;
        if (isset($request->nik)) {
            $response = $this->patient_by_nik($request->nik);
            $data = $response->getData();
            if ($response->status() == 200) {
                if ($data->total) {
                    $patient = $data->entry[0]->resource;
                    Alert::success($response->statusText(), 'Pasien Ditemukan');
                } else {
                    Alert::error('Not Found', 'Pasien Tidak Ditemukan');
                }
            } else {
                Alert::error($response->statusText() . ' ' . $response->status());
            }
        }
        
}

I was trying to get data from an API and return the data



via Chebli Mohamed

mercredi 7 décembre 2022

The "--path" option does not exist

The "--path" option does not exist.

Artisan::call("migrate --path=database/migrations/tenant")

i updated Laravel from 5.8 to laravel 8

i don't know that wrong

Artisan::call("migrate") work fine



via Chebli Mohamed

page not opening when click the post

I am newbie in development please help,Do not judge me. Remember everyone starts from 0.

When I click my ticket it is not opening specific page while click link of my ticket it shows in link correct ticket id but page not opening "404 not found"

Ticket.blade.php

`

                        
                                <tr>
                                                                     
                                                                     
                                    @foreach ($ticketsinfos as $ticketinfo)
                                    <td>IR-173049</td>
                                    <td>Dito Katsarava</td> 
                                    <td></td>
                                    
                                    <td><a href="/tickets/show/"></a></td>
                                    
                                    <td><button class="btn btn-danger btn-sm" type="button">Action Needed<br></button><br></td>
                                    <td>Tako Kiknadze</td>
                                    <td></td>
                                    <td></td>
                                </tr>

                                @endforeach  
                              
                                </tr>

`

web.php

`

<?php

use App\Http\Controllers\AdminsUserController;
//use App\Http\Controllers\UserController;
//use App\Http\Controllers\CompaniesController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\TicketsController;
//use App\Models\AdminsUser;
//use App\Models\Companies;
use Illuminate\Support\Facades\Route;

/*
|----------------------------------------------z----------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::resource('/dashboard', DashboardController::class);

Route::resource('/tickets', TicketsController::class);

Route::resource('/admin/users', AdminsUserController::class);
// Route::resource('/companies', CompaniesController::class);




Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');


`

Controller

`

  public function show(Tickets $tickets)
    {
        //
        $tickets = Companies::with('tickets')->get();

        $severities = Severities::with('severity')->get();
        
        $ticketsinfos = Tickets::with('companies')->findOrFail(2);
    
        

  
     return view('customer.index', compact($tickets))->with(['tickets' => $tickets])->with(['severities' => $severities])->with(['ticketsinfos' => $ticketsinfos]);

    //dd($ticketsinfos->toArray());
        
    }

`

When I 'dd' works

Thanks you.



via Chebli Mohamed

laravel Unique Validation on row where is_active is 1

I want to implement unique validation on one column but it should only check active rows of the table. so is there any way I can implement this logic using laravel validation?

Below is the logic I am using to check unique records but its not working.

unique:users,email,is_active,1


via Chebli Mohamed

mardi 6 décembre 2022

Laravel "Trying to access array offset on value of type null" error when trying to render markdown

I'm trying to show some changelog content on my Laravel page with this markdown plugin, but it always throws this error: Trying to access array offset on value of type null

@markdown($changelog->content)

The content is not null, all the content is there and it gets created and stored properly.

I found out about @isset but no matter how I use it, it still shows that error.

@isset($changelog->content)
  @markdown($changelog->content)
@endisset

Note: I'm using Laravel 5.8, this is an older project.



via Chebli Mohamed

lundi 5 décembre 2022

FatalThrowableError in Call to a member function get_one() on null

i have some laravel code like this

public function update_password(Request $request)
    {
        $data = array(
            'password_current' => $request->input('password_current'), 
            'password_new' => $request->input('password_new'),
            'password_new_confirmation' => $request->input('password_new_confirmation'), 
            );

        $rules = [
            'password_current' => 'required',
            'password_new' => 'required|confirmed',
            'password_new_confirmation' => 'required',
        ];

        $validator = Validator::make($data, $rules);
        if ($validator->fails()) {   
            return redirect()->action('Editor\ProfileController@edit_password')->withInput()->withErrors(['New password confirmation failed!']);
        } else {
            
            $user = $this->UserRepository->get_one(Auth::user()->id);
            
            if(Hash::check($request->input('password_current'), $user->password))
            {
                $this->UserRepository->change_password(Auth::user()->id, $request->input('password_new'));

                return redirect()->action('Editor\ProfileController@show');
            } else {
                return redirect()->action('Editor\ProfileController@edit_password')->withInput()->withErrors(['Current password mismatch!']);
            }
        }
    }

but when i run the program, the program notification is FatalThrowableError, Call to a member function get_one() on null. i change with other script in google but no one is work.

$user = $this->UserRepository->get_one(Auth::user()->id);

anyone ever had this problem?

I try to change script like

use Auth;
$user_id = Auth::user()->id;

and still not work.



via Chebli Mohamed

dimanche 4 décembre 2022

Need to replace a static value in all controllers even in whole project. Is there any way that i can change this value from only a single function?

I have a pre-build project and there is some static value passed in the whole project. Instead of looking in every controller and blade file, I want to change these static values replace to the values from the env file.

**What I tried: ** In the bootstrap folder in the app.php file, I created a function for replacing static values by using str_replace() and call this function in the same file. This is not working.

I don't want to change the static value in the controller, But on the run time.

<?php

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/

$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/

$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/


function replaceHello()
{
    str_replace("world","all.","Hello world");
}
replaceHello();

return $app;

This function is for replace world from the hello world to hello all in whole project. Is there any way to do this?



via Chebli Mohamed

samedi 3 décembre 2022

Lumen queue throwing MySQL server has gone away error

I'm calling a common function from Lumen queue and cron job. During user interaction this function is called from queue ( async purpose ), if something goes wrong with queue execution for example lock wait timeout etc. I have a cron job which is scheduled for every 15 mins to process older transactions. There is no issue when cron is executed but whenever queue is executed MySQL server has gone away error is occurring. Error is occurring at the line DB::connection()->getpdo()->exec('BEGIN');

I did some research on internet, those articles are saying this kind of error will raise when we try to insert large data and we can avoid this error my increasing max_allowed_packet. But error is occurring at beginning line itself, I'm not trying to insert large data ( mostly it should be in KBs ) and moreover same function is working when cron executes for every 15 mins. Following are my code snippets,

public function processTransaction($data)
{
    try {
        $this->validate($data);
        DB::connection()->getpdo()->exec('BEGIN');
    // Save & Update DB 
        DB::connection()->getpdo()->exec('COMMIT');
    } catch (Exception $ex) {
        DB::connection()->getpdo()->exec('ROLLBACK');
        Log::error($ex->getMessage() . '-' . $ex->getTraceAsString());
        throw new AppException($ex->getMessage(), $ex->getCode());
    }
}

Above is the initial version I tried, in this case error was at ROLLBACK statement. Later I had updated to following

public function processTransaction($data)
{
    try {
        $this->validate($data);
        DB::connection()->getpdo()->exec('BEGIN');
    // Save & Update DB 
        DB::connection()->getpdo()->exec('COMMIT');
    } catch (Exception $ex) {
        Log::error($ex->getMessage() . '-' . $ex->getTraceAsString());
        try {
            DB::connection()->getpdo()->exec('ROLLBACK');
        } catch (Exception $ex) {
            Log::error($ex->getMessage() . '-' . $ex->getTraceAsString());
        }
        throw new AppException($ex->getMessage(), $ex->getCode());
    }
}

Here the error is at BEGIN statement and PDO exception error code is in string, which is also creating the issue for argument 2 AppException (extends Exception class), which excepts argument 2 as integer. I think PDO exception issue can be handled by separately catching PDO exception but I want to know why MySQL server has gone error is getting.



via Chebli Mohamed

vendredi 2 décembre 2022

How can i use redirect()->route('test', $id) after create a data in Laravel? [closed]

The store function

The Route

I try to store a data to database and than i want to redirect the page with the created data ID. I use return redirect()->route('test', $id) but its not working.



via Chebli Mohamed

how can I handle errors in laravel mail

Laravel app sending mails with mandrillapp and Mailchimp. it's working.

How do you handling errors? How can I know is the mail sent or not?

Mail is send with Mail::sent() in try/catch block.

count(Mail::failures) is always 0. I can't find what type or error is needed to show in failures[]?

I can catch

Swift_RfcComplianceException

and

Swift_TransportException

I read the mailchimp documentation but can't find some return of API which says about mail status.

Any idea or suggestion about error handling?



via Chebli Mohamed

jeudi 1 décembre 2022

How to get the result with these time intervals in php

I'm using a time clock system which, by default, records only the employee's entry and exit times. I'm customizing it so that it's possible to also record break times but I'm having trouble getting the break time to be subtracted from the total time. This snippet of code is used to register the time between the check-in and check-out:

$time1 = Carbon::createFromFormat("Y-m-d H:i:s", $timeIN); 
$time2 = Carbon::createFromFormat("Y-m-d H:i:s", $timeOUT); 
$th = $time1->diffInHours($time2);
$tm = floor(($time1->diffInMinutes($time2) - (60 * $th)));
$totalhour = ($th.".".$tm);

The variable ($totalhour) receives the total value between the input register and the output register. It sends to the database in H.i format (hour.minutes), then another page searches for this information in the database and replaces the point (.) with (hr). Based on this code, I did the same to get the interval start and end timestamps. I was able to get the time between the start time and end time interval with the code below:

$breakstart = table::attendance()->where([['idno', $idno]])->value('breakstart');
$breakend = table::attendance()->where([['idno', $idno]])->value('breakend');
$one = Carbon::createFromFormat("H:i:s", $breakstart); 
$two = Carbon::createFromFormat("H:i:s", $breakend);
$breakone = $one->diffInHours($two);
$breaktwo = floor(($one->diffInMinutes($two) - (60 * $breakone)));
$totalbreak = $breakone.".".$breaktwo;

The $totalbreak variable stores the time taken between the start and end of the break. I was also successful in getting the time between this interval. Now, I need the total time to be done by subtracting the time obtained from the record at the beginning of the interval to the record at the end of the interval. I did with this code and got good result up to a point. Could you give me tips on how to get an assertive result in this case?

$totalhour = ($th.".".$tm) - ($totalbreak);

I tried to get the total time by subtracting the break time, but without success.



via Chebli Mohamed