mercredi 28 décembre 2022

Insert has error when data column is double

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/An9i5Jc
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/LJCkE7p
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/xOyZ7B8
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/VvXoti7
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/eArKfRy
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/JguVHQU
via IFTTT

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());
}
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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/n0OxYrv
via IFTTT

mercredi 21 décembre 2022

Passport Login not working after git clone to a local device. I am using a sql server. While I try to login, the process keeps on running no resposne

This is the env file This is the .env

I am trying to login using the passport. I just cloned the project to my local device which was running in a development serve.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/4vwxVZt
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/hcrwI5F
via IFTTT

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;


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

I will be glad if you help me thank you



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/zHN1njm
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/iMuIFad
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/9DOv0L5
via IFTTT

samedi 17 décembre 2022

While accessing the website I am getting this error. Can anyone help me to resolve this issue?

Error Image

error image

I have done the max user upto 1000 but error is coming simultaneously. I am using laravel.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/rZYBxlP
via IFTTT

vendredi 16 décembre 2022

React + Laravel 5.6 api CORS issue

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/OHdJyGs
via IFTTT

jeudi 15 décembre 2022

Server error: `POST https://my-api-url` resulted in a `500 Internal Server Error

So i have this error where it says that

"Server error: POST https://my-api-url resulted in a 500 Internal Server Error resulted in a 500 Internal Server Error` response: {"fault":{"faultstring":"Execution of JS-SetCreator failed with error: Javascript runtime error: "SyntaxError: Unexpect (truncated...)

the error

The function:

 public function store()
  {
    $client = new Client();
    $url = "https://my-api-url";
    $token = Token::latest()->first()->access_token;
    $json = '{
      "resourceType": "Medication",
      "meta": {
        "profile": [
          "https://some-url"
        ]
      },  "identifier": [
        {
          "system": "url",
          "use": "official",
          "value": "123456789"
        }
      ],
// ...
}';

$jsonArray = json_decode($json, true);
    $response = $client->post($url, [
      'headers' => [
        'Authorization' => 'Bearer ' . $token,
        'Accept' => 'application/json'
      ],
      'form_params' => $jsonArray,
    ]);
    $response = json_decode($response->getBody());
}

I'm trying to make a POST request to the given URL but ended up with those errors. I've tried in postman but it's working fine, so I guess there's something wrong with my code

Here's the not truncated error

{"fault":{"faultstring":"Execution of JS-SetCreator failed with error: Javascript runtime error: \"SyntaxError: Unexpected token: r. (SetCreator.js:5)\"","detail":{"errorcode":"steps.javascript.ScriptExecutionFailed"}}}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/uweZygc
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/jgxz9A7
via IFTTT

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
            ];

        }

}


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/bG3DyNU
via IFTTT

lundi 12 décembre 2022

Argument 1 passed to Symfony\Component\HttpFoundation\Request::__construct()

I have this error that says:

Argument 1 passed to Symfony\Component\HttpFoundation\Request::__construct() must be of the type array, string given, called in C:\xampp\htdocs\satusehat2\app\Http\Controllers\PasienController.php on line 68.

This is my function

public function curl_postman() {
        $client = new Client();
        $headers = [
          'Content-Type' => 'application/json',
          'Authorization' => 'My Bearer token'
        ];
        $body = '';
        $request = new Request('GET', 'my-api-address', $headers, $body);
        $res = $client->sendAsync($request)->wait();
        echo $res->getBody();
        
    }

and the line 68 is

$body = '';


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/REYspOd
via IFTTT

Trying to change the static data in vue.js file

<template>
  <v-card>
    <v-toolbar tabs flat>
      <v-toolbar-title>Branding</v-toolbar-title>
   
      <v-spacer></v-spacer>
      <template v-slot:extension>
        <v-flex>
          <v-tabs 
            v-model="selectedTab" 
            :slider-color="app.color_name"
            color="grey darken-3"
            show-arrows
            >
            <v-tab :href="'#general'">
              General
            </v-tab>
            <v-tab :href="'#email'">
              E-mail
            </v-tab>
            <v-tab :href="'#domain'">
              Domain
            </v-tab>
          </v-tabs>
        </v-flex>
      </template>

I am trying to replace "Branding"

   <v-toolbar-title>Branding</v-toolbar-title>

to "Branding Testing

   <v-toolbar-title>Branding Testing</v-toolbar-title>

but it is not showing any changes. Can anyone help me with that?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/jm5Cesa
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/lMovgq2
via IFTTT

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
        }
    }
}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/J2a3QS4
via IFTTT

vendredi 9 décembre 2022

How can I Link Cron jobs to users Laravel

I am trying to know which user has cron jobs on our server.

I tried to read from the jobs table the user's id. It worked but there should be a cleaner way than using LIKE on a big chunk.

My first thought is when creating a job I should add a row in a many-to-many relationship between the user's id and the job's id.

Is there a more efficient way of handling such a scenario? There is not much code I can add because I need to understand how to tackle this.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/ZdH24Rl
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/u3t8Ynq
via IFTTT

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 what is wrong.

Artisan::call("migrate") works fine



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/iwAEFlV
via IFTTT

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


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/wT1sLlI
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/frvbuhi
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/9KY8dRc
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/ZmQ4dLy
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/jpVysdR
via IFTTT

The modal inside the foreach also returns the last data [closed]

modal inside foreach return the last data

how do i fix this ,modal inside foreach return the last data



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/Ir0O8hL
via IFTTT

vendredi 2 décembre 2022

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

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/mRTC1UX
via IFTTT

autofocus in laravel cursor point automically in input user can type please answer in product_name textbox

 autofocus not work in  laravel page 
Just passed with array() or in javascript I also tried please help me 



{!! Form::open(['url' => action('ProductController@saveQuickProduct'), 'method' => 'post', 'id' => 'quick_add_product_form' ]) !!}
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="modalTitle">@lang( 'product.add_new_product' )</h4>
</div>
<div class="modal-body">
  <div class="row">
    <div class="col-md-4">
      <div class="form-group">
        
        {!! Form::label('name', __('product.product_name') . ':*') !!}
        
          {!! Form::text('c', null,array('autofocus'=>'autofocus'),['class' =>'form-control', 'required', 
          'placeholder' => __('product.product_name')]); !!} 
          {!! Form::select('type', ['single' => 'Single', 'variable' => 'Variable'], 'single', ['class' => 'hide', 'id' => 'type']); !!}
          
        </div>
    </div>


user can type without click on textbox


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/r58xyJK
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/f0BoOn4
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/T0QHpi9
via IFTTT

mercredi 30 novembre 2022

getting error on server(aws) SyntaxError: Unexpected token '<', "

I have deployed my laravel application on AWS server(ubuntu). Application works fine. But when I upload images using custom modal popup, then i got the syntax error from vendors.js.

Here is the error getting from modal popup while uploading images: Here is the error getting from modal popup while uploading images

Can anyone tell about that, how i can resolve that? I am just stuck from last two days.

I have tried run on server npm i body-parser And also re-add the file of vendors.js But same result.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/Nu2G06D
via IFTTT

mardi 29 novembre 2022

Fatal error: Uncaught ReflectionException: Class IlluminateContractsHttpKernel does not exist

Fatal error: Uncaught ReflectionException: Class IlluminateContractsHttpKernel does not exist in C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php:788 Stack trace: #0 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php(788): ReflectionClass->__construct('IlluminateContr...') #1 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php(667): Illuminate\Container\Container->build('IlluminateContr...') #2 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php(615): Illuminate\Container\Container->resolve('IlluminateContr...', Array) #3 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(767): Illuminate\Container\Container->make('IlluminateContr...', Array) #4 C:\xampp\htdocs\erc_new\public\index.php(52): Illuminate\Foundation\Application->make('IlluminateContr...') #5 C:\xampp\htdocs\erc_new\server.php(21): require_once('C:\xampp\htdocs...') #6 {mai in C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 788

auto it is showin the Kernel error. thought i have not made any changes. i have already tried checking the Kernel.php files. more over i have already deleated the vendor and composer.lock file and install the composer . But also getting the the above error.

Moreover I also have deleted the every things that recedes on bootstrap/cache/



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/LF1uUhm
via IFTTT

Laravel 8 - search paginate ( withQueryString ) not working on table when searching NUMBERS on row integer

i can't search when it comes to searching NUMBERS on row int (price), but when searching like String number on row string (name) it's working fine

like this in my table row here is my Product table

category_id
"56"
user_id
"1"
name
"555"
description
"fruit"
price
555

when i am searching the name row "555" it's working fine beacuse its a string. but when it comes to price i can't search it because it's int

here is my code for controller searching

public function index(Request $request){
    $user = Auth::user()->id;
    if($request->search){
        $search = $request->search;
        $products = Products::with('category')
        ->where('name','like',"%$search%")
        ->orWhere('price','like',"%$search%")
        ->where('user_id',$user)->paginate(10);
    }else{
        $products = Products::with('category')->where('user_id',$user)->paginate(10);
    }
      return view('client.product.index',['products'=>$products]);
}

here is my blade

    <form class="w-full" action="">
        <i class="fa fa-search"></i>
        <input placeholder="Search"  type="search" name="search">     
        <button type="submit">Search</button>
    </form>

@foreach ($products as $product)
    <p></p>
    <p></p>
@endforeach



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/xRA2tjM
via IFTTT

lundi 28 novembre 2022

How to sort parent data based on child column detial in laravel 5.4?

I have 3 way relationship firstl i have get code like this in a controller

Trial::with('subjects')->where('source_id', $sourceId)->get()->toArray()

Now I want to sort subject.reactions on desc order of subject.reactions.accounts.nb_followers column. I tried to use orderby on relationship but it does not work because it sorting account indsted on reactions. I want to sort reaction based on value of "nb_followes" column present inside account table.

Trail Model

class Trial extends Model
{
    use HasFactory;
    public $table = 'trials';

    public function subjects()
    {
        return $this->hasMany(Subject::class, 'trial_id')->with(['reactions', 'news'])->withCount('reactions');
    }
  } 

Subject Model

class Subject extends Model
{
    use HasFactory;
    public $table = 'subjects';

    public function reactions()
    {
        return $this->hasMany(Reaction::class, 'subject_id', 'id')->with(['accounts' => function ($q) {$q->orderBy('nb_followers', 'DESC');}])->where('twitter_error', 0)->where('active', 1)->orderby('key_reaction', 'DESC');
    }

    public function news()
    {
        return $this->hasone(News::class, 'id', 'news_item_id');
    }

Reaction Model

class Reaction extends Model
{
    use HasFactory;

    public $table = 'reactions';

    public function accounts()
    {
        return $this->belongsTo(Account::class, 'account_id', 'id')->where('name', '!=', '');
    }

Thank you in Advance.



I want to sort reactions based on account table's column yes i cant use simple eloquent query because it will not create a structure that i want so that's why i created these relationships.


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/jIaDs1P
via IFTTT

samedi 26 novembre 2022

laravel Target class [App\Http\Controllers\EmployeeController] does not exist

enter image description here enter image description here

enter image description here

Target class [App\Http\Controllers\EmployeeController] does not exist.

 protected $namespace ='App\\Http\\Controllers';
public function boot()
{
    $this->configureRateLimiting();

    $this->routes(function () {
        Route::middleware('api')
            ->prefix('api')
            ->namespace($this->namespace)
            ->namespace('App\Http\Controllers') 
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
        ->namespace($this->namespace)
        ->namespace('App\Http\Controllers')
        ->group(base_path('routes/web.php'));
    });

}

using but not solving the problem



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/DsvzprI
via IFTTT

vendredi 25 novembre 2022

Access numeric key in array php [duplicate]

I have a array with a key like "11_check". How to acess this using php/laravel?

            $check=$list[$i]->{11_check};

I'm trying to acess with {} but I'm getting the error

Parse error: syntax error, unexpected '_check' (T_STRING)

Solution:

            $check=$list[$i]->{'11_check'};


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/oXgRhl3
via IFTTT

How can I pass params at access point of GraphQL such as {url}/graphql?development=true by using lighthouse in laravel

How can I pass params at access point of GraphQL such as {url}/graphql?development=true by using lighthouse in laravel. if development is true i want to use different database in laravel.

http://127.0.0.1:8000/graphql?development=true

its working but graphql does not getting development params



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/7XunMGp
via IFTTT

jeudi 24 novembre 2022

Error Laravel\Socialite\Two\InvalidStateException In the return method from the Google side

I want use Socialite package but receive in Error !

controller codes :

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Laravel\Socialite\Facades\Socialite;

class GoogleAuthController extends Controller
{
    public function redirect()
    {
        return Socialite::driver('google')->redirect();
    }

    public function callback()
    {
        // when i dd() here i see in the answer in the browser.
        $googleUser = Socialite::with('google')->user();
        // but dd in here isn't working!
       
        $user = User::where('email', $googleUser->email)->first;

        if ($user) {
            auth()->loginUsingId($user->id);
        } else {
            $newUser = User::create([
                'name' => $googleUser->name,
                'email' => $googleUser->email,
                'password' => bcrypt(\Str::random(16)),
            ]);
            auth()->loginUsingId($newUser->id);
        }
        return $this->redirect('/');
    }
}

in web.php :

Route::get('auth/google', 'Auth\GoogleAuthController@redirect')->name('auth.google');
Route::get('auth/google/callback', 'Auth\GoogleAuthController@callback');

laravel version : 6.20.26

php version : 7.2.5

please help me. tnks

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

I try this (https://stackoverflow.com/a/37849202/20355717) :

Socialite::driver('google')->stateless()->user()

but in did't work for me and given an anothe error ! :

GuzzleHttp\Exception\RequestException

cURL error 77: error setting certificate verify locations: CAfile: /path/to
/downloaded/cacert.pem CApath: none (see https://curl.haxx.se/libcurl
/c/libcurl-errors.html) for https://www.googleapis.com/oauth2/v4/token


http://localhost:8000/auth/google/callback?authuser=0&code=4%2F0AfgeXvucuWTlboWqaMwf2bkBe0AHjbPEJd-
2e7cQdlSN345_3imguhVT_1PQ8fa3ISoHSA&prompt=consent&
scope=email%20profile%20openid%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&
state=axIlfjFkns6vWNJIX2uJMuMKNiYFfy7cKiE8Xr8W 



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/gruUtsS
via IFTTT

lundi 21 novembre 2022

Laravel 9 Validation: array is optional but its keys are required: required_array_keys and nullable don't work together

Summary

  1. Context

  2. Sources

    2.1. Unit test

    2.2. FormRequest's rules method

  3. Behaviors

    3.1. Actual behavior

    3.2. Expected behavior

  4. Question


Context

In a Unit test, I want to send data to a FormRequest in a REST call. I am testing the behavior of the validation rules I've written in the rules method of the FormRequest.

Sources

Unit test

    public function test_detach_user_job_status()
    {
        $response = $this->put(route('users.update', ['user' => $this->applier['id']], [
            'job' => [
            ]
        ]));
        $response->assertStatus(200);
    }

FormRequest's rules method

    public function rules()
    {
        return [
            'name' => 'nullable|string',

            'job' => 'nullable|array:id,attach_or_detach,message|required_array_keys:id,attach_or_detach',
            'job.id' => 'integer|gt:0',
            'job.attach_or_detach' => 'boolean',
            'job.message' => 'required_if:job.attach_or_detach,true|string',
        ];
    }

Behaviors

Actual behavior

The test succeeds.

Expected behavior

The test fails. Indeed, the array job is provided but no keys id or attach_or_detach or (eventually) message are provided, whereas the validation rules do specify: required_array_keys:id,attach_or_detach.

Also, if no job array is specified at all, then the validator must not reject the request because this array is not provided, nor its keys: it's perfectly normal since the array must be optional (it is nullable to provide this feature).

Question

Why doesn't Laravel make my test fail since my nullable (= optional) array is provided, and that its keys are required?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/LvI08qw
via IFTTT

dimanche 20 novembre 2022

Fetch product first based on values in column laravel

I have this query that fetches properties from table

$properties = Property::with('Category')
            ->orderBy('name','asc')
            ->where('status','Active')
            ->get();

In my table i have added new column featured it's value is either 0 or 1. I want to show property with 1 value in featured column first

Please suggest solution Thanks.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/ZkweNlx
via IFTTT

samedi 19 novembre 2022

How can I ad more fields for the enrollment and make it appear on the dashboard

So I downloaded this project of laravel from github a laravel course enrollment project and I want to add more fields to the register form and make it appear on the admin panel as well but in with the code, they used the quickadminpanel.com and also repeating this cruds.enrollment.fields.user which is literally not defined any where in the code that I can see. Since I am a beginner with this laravel thing, I could really use some help in building a project using that repository. Thank You

I have tried almost every thing I know and so far...nothing is happening



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/rdkERxG
via IFTTT

how to pass register data api to another out api

I am have register api for register user data in my users table I want also in the same register api set link for out api to register the same date also in another application how can i do this



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/iZnQJFg
via IFTTT

vendredi 18 novembre 2022

419 page expired error in laravel form submission even after adding csrf

 <form action="/checklogin" method="post" enctype="multipart/form-data" class="account-form" id="login_form_order_page">
                                     
              <div class="error-wrap"></div>
              <div class="form-group">
                 <input type="text" name="email" class="form-control" placeholder="Email*" required>
              </div>
              <div class="form-group">
                 <input type="password" name="password" class="form-control" placeholder="Password*" required>
              </div>
              <div class="form-group btn-wrapper">
                 <button type="submit" id="login_btn" class="submit-btn">Login</button>
              </div>
              <div class="row mb-4 rmber-area">
                 <div class="col-6">
                    <div class="custom-control custom-checkbox mr-sm-2">
                       <input type="checkbox" name="remember" class="custom-control-input" id="remember">
                       <label class="custom-control-label" for="remember">Remember Me</label>
                    </div>
                 </div>
                 <div class="col-6 text-right">
                    <a class="d-block" href="/register">Create New account?</a>
                    <a href="login/forget-password">Forgot Password?</a>
                 </div>
              </div>
              <div class="col-lg-12">
                 <div class="social-login-wrap">
                 </div>
              </div>
           </form>


Route::POST('/checklogin', 'HomeController@checklogin');

I am submitting the form with csrf still after submitting form 419|Page Expired Error. After adding session_start() method on page it shows headers already sent.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/ihuWRcO
via IFTTT

mercredi 16 novembre 2022

lluminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, string

I have a problem trying to send values in the form of an array from the input, what is the solution? And each array of data is in a separate line in the data base and has an id as if I entered the data more than once

I searched a lot, but I did not find a solution to this problem. Can someone help me? Thank you

//blade

<td>
    <input type="text" class="qty form-control" name="p_unit[]">
    @error('p_unit.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td>
    <input type="text" class="qty form-control" name="p_lastPrice[]">
    @error('p_lastPrice.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td>
    <input type="text" class="qty form-control" name="p_averagecost[]">
    @error('p_averagecost.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td><input type="text" class="form-control" name="p_priceA[]"></td>
<td>
    <input type="text" class="form-control weight" name="p_priceB[]">
    @error('p_priceB.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td>
    <input type="text" class="form-control unit_cost" name="p_priceC[]">
    @error('p_priceC.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>


I have an activated button that repeats the same fields to fill them in again, and after that I want to send the data in an array to the database

// controller

$products = $request->p_code;


for ($i=0; $i<count($products); $i++)
{
    $items = productUnitPrice::create([
        'p_code'               => $request->p_code,
        'p_packing'            => $request->p_packing[$i],
        'p_conversionfactor'   => $request->p_conversionfactor[$i],
        'p_unit'               => $request->p_unit[$i],
        'p_lastPrice'          => $request->p_lastPrice[$i],
        'p_averagecost'        => $request->p_averagecost[$i],
        'p_priceA'             => $request->p_priceA[$i],
        'p_priceB'             => $request->p_priceB[$i],
        'p_priceC'             => $request->p_priceC[$i],

    ]);


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/504s3mQ
via IFTTT

My Laravel Links keep breaking Each time I restart my server

My Laravel links keep breaking each time I restart my local server

So, I am using Laravel 9 and my links keep breaking each time I reload the page or when I restart the server For example

127.0.0.1:8000/cars/1/edit

will become 127.0.0.1:8000/cars/cars/1/edit next time I click it.

I have searched for a solution and stumbled upon this On every click link changes in blade view

But the problem is that the guy that asked the question is using named routes from web.php route

I, on the other hand, am using resource routes ( I do not know what to call them = Route::resource('/cars', CarsController::class);)Resouce route

For that reason, I'm finding it difficult to implement the route() solution proposed as his had a named route name

The href I want to make changes to looks like this. I am using resources routes in web.php

<a href="cars//edit">Edit &rarr;</a>

Href I want to edit



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/TWo0CMk
via IFTTT

Tom-Select options not loading while using JavaScript's native Fetch API in this example to retrieve remote data from a route

I am attempting to load tom-select options not loading while using JavaScript's native Fetch API in this example to retrieve remote data from a route. However, JS below fetches a json array of 15527 items but won't show on the options

The Select element...

<select id="select-repo" placeholder="Select a Diagnosis" multiple></select>

The JS...

var new_opd1 = "";

     new TomSelect('#select-repo',{
        valueField: 'url',
        labelField: 'icd_name',
        searchField: 'icd_name',
        // fetch remote data
        load: function(query, callback) {
            var url =new_opd1+'?q='+query ;
           // console.log(url)
            fetch(url)
                .then(response => response.json())
                .then(json => {
                    //console.log(json.name); ~undefined
                    callback(json);
                   // console.log(json);
                }).catch(()=>{
                callback();
            });

            
        },
       // custom rendering functions for options and items
         render: {
            option: function() {
                return `<div class="py-2 d-flex">
                            <div>
                                <div class="mb-1">
                                    <span class="h4">
                                        ${(icd_name) } 
                                    </span>
                                </div>
                                <span class="h4">
                                        ${(icd_code) }
                                    </span>
                            </div>
                        </div>`;
            },
            item: function() {
                return `div class="py-2 d-flex">
                            <div>
                                <div class="mb-1">
                                    <span class="h4">
                                        ${(icd_name) }
                                    </span>
                                </div>
                                <div class="description">${(icd_code) }</div>
                            </div>
                        </div>`;
            }
        },


     });

The route...

public function getData(Request $request){

   $users = ICD10Code::project(["_id" => 0])->get(['icd_code','icd_name']);
    
   return json_encode($users->toArray());
 
 }

I am attempting to recreate this https://tom-select.js.org/examples/remote/. However since my dataset is huge I was wondering if really this would work



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/XUx6bSI
via IFTTT

mardi 15 novembre 2022

Exclude from a select more than 2101 records with laravel sql query builder

I am using something like this:

$scanned = DB::table("Persons")
        ->whereNotIn("Person_Id", $exclude)
        ->get();

The problem is $exclude has more than 2101 records, and I get the following error:

SQLSTATE[IMSSP]: Tried to bind parameter number 2101.  SQL Server supports a maximum of 2100 parameters.

Is there a way around? how can I solve this?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/xwOMC81
via IFTTT

lundi 14 novembre 2022

Is there any way to use eloquent addSelect with different database on a different server in Laravel?

A table called api_call_data is being used in a seperate database (done by the original code author, not me) which is located in another server in our Laravel project (I can't move the table).

Due to that, the original query doesn't work anymore. The original query was like below:

$apicallData->addSelect(DB::raw("
    (SELECT MAX(`reg_time`) FROM `api_call_data` as A WHERE `A`.`app_id` = `apps_data`.`app_id` and reg_time between $request->from_date and $request->to_date) as api_reg_time
"))

(I have omitted the rest of the queries after this here)

Is there any way to make this original query work? I really wanted to make this work but I am totally lost here.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/R3sjBpw
via IFTTT

dimanche 13 novembre 2022

Wildcard routing with laravel not following recognizing prefix

In my application i have a laravel backend with two spas consuming api from it. Now i want to manage my routes by using wildcard routes where i give both routes prefixes before the wildcard route takes effect. Here is an example

Route::prefix('creditors')->group(function () {
    Route::any('/{all}', function () {
        return view('creditor');
    })->where(['all' => '.*']);
});

Now the issue us if i visit something like /creditors/login the spa returns a 404 not found. I want my spa to start handling routing after "creditors/". How do i go about this?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/Was2SHe
via IFTTT

samedi 12 novembre 2022

Sending an email using Laravel for contact form

1

I am making how to send an email using laravel through contact form.Why this @if @endif are display on the screen?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/gmz4rIu
via IFTTT

vendredi 11 novembre 2022

Can config/auth.php be made dynamic?

Can helper functions or through any other medium be used to make changes in config/auth.php? I mean can we get some data from the database through helper function or some other way and just append the data to config/auth.php.

I was trying to append the data to guards key. I made a guards table and formatted the data to the exact format of guards key of config/auth.php.

I called a helper function in config/auth.php and tried to get the data of guards but it showed a bunch of errors.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/hNMq58O
via IFTTT

jeudi 10 novembre 2022

CSRF token mismatched in laravel when i moved project to another server

enter image description here

Hii My website is not working on other server code is same into both server

1, Working server

http://programmingly.com/articles/

  • testuser@gmail.com
  • 12345678 (Working perfect)

https://www.vennocracy.com/

  • testuser@gmail.com
  • 12345678 (Not Working)

I tried ajax for that

$('#login-form').validate({
        rules: {
            email: {
                required: true,
            },
            password: {
                required: true,
            },
        },
        messages: {
            email: {
                required: 'Please enter email',
            },
            password: {
                required: 'Please enter password',
            },
        },
        submitHandler: function(form) {
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: "",
                type: "POST",
                data: new FormData(form),
                dataType: 'json',
                contentType: false,
                cache: false,
                processData: false,
                beforeSend: function() {
                    $("body").append(
                        "<div class='ajax-overlay'><i class='porto-loading-icon'></i></div>"
                        );
                },
                success: function(res) {
                    $(".ajax-overlay").remove();
                    if (res.status) {
                        $('.all-error').html('');
                        $('.all-success').html('');
                        $('.all-success').html(res.message);
                        setTimeout(function() {
                            $("#loginModal").modal('hide');
                            location.reload();
                        }, 4000);
                    } else {
                        $('.all-error').html('');
                        $('.all-error').html(res.message);
                    }
                },
                error: function(data) {
                    $(".ajax-overlay").remove();
                    var errorString = '';
                    $.each(data.responseJSON.errors, function(key, value) {
                        errorString += value + '<br>';
                    });
                    $('.all-error').html('');
                    $('.all-success').html('');
                    $('.all-error').html(errorString);
                },
            });
            return false;
        }
    });


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/IPj031d
via IFTTT

mercredi 9 novembre 2022

Laravel, download 2 files on one button click

I'm trying to make a feature where one button being clicked will access a single route and controller but the controller will sequentially download 2 files. The catch is they can't be zipped, they need to be downloaded sequentially as single files.

I've tried with this but I get an array to string conversion error.

public function fileDownload(){

    $first_file_name = 'test.xlsx';
    $first_file_path = storage_path("files/{$first_file_name}");

    $second_file_name = 'test2.xlsx';
    $second_file_path = storage_path("files/{$second_file_name}");  

    return \Response::download([$first_file_path, $second_file_path]);
}

Is there a way to do this in Laravel 5.3?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/16Hwon9
via IFTTT

how to show multiple filenames in one json format?

I'm not sure where and how I should use the for loop.

I am using Laravel v5.5. I am trying to upload multiple files on my project. I think if I can add all filenames in one json array I can show them in blade page. How can i do that?


        if(request()->hasFile('urun_resmi')) {
            $files = request()->file('urun_resmi');
            $filename = [];
            foreach ($files as $file) {
                if($file->extension() == 'pdf')
                {
                    $filename = $file->extension() . "-" . $entry->id . "-" . time() . "." . $file->extension();
                }else
                {
                    $filename = $entry->id . "-" . time() . "." . $file->extension();
                }
                $file->storeAs('urunler', $filename, 'public');
                $entry->detay()->update(['urun_resmi' => $filename]);
                
          
                if ($file->isValid()) {
                    $file->move('uploads/urunler', $filename);
                    UrunDetay::updateOrCreate(
                        ['urun_id' => $entry->id],
                        ['urun_resmi' => $filename]
                    );
                }
            }

        }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/onT7iOM
via IFTTT

mardi 8 novembre 2022

laravel log debug is not working.I checked A response is returned from the server side

laravel log debug is not working.

I create app with laravel5 and vue.js.

I send a request to the server side with vue and catch this with laravel Controller.php.

I code Log::debug to PostsController.php, but the log is not written in laravel.log.

I try use Illuminate\Support\Facades\Log; and use Log; , but both are not working.

Do you find anything wrong with my code?

Thank you for your help.

// web.php

Route::get('/posts/items', 'PostsController@items');
PostsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Model\Post;
use App\Model\Item;
// use Log;
use Illuminate\Support\Facades\Log;

use App\Http\Resources\Post as PostResource;
use App\Http\Resources\Item as ItemResource;

class PostsController extends Controller
{

    public function items(Request $request)
    {
        Log::info('kita');
        Log::debug('kurukao');
        logger()->debug('debug');

        $post_id = $request->input('post_id');
        return $post_id;
    }

//vue


    methods: {
      mouseenter(id) {
        this.itemId = id;
      },
      mouseleave(id) {
        this.itemId = null;
      },
      getItems() {
        axios.get("/posts/items", {
            post_id: this.$route.params.id
        })
        .then((res) => {
        //   console.log(res.data)
          console.log('ok')
          this.postDataList = res.data.data;
        //   console.log(this.postDataList)
          if(this.postDataList != null){
            this.itemDataList = this.postDataList[0]['items'];
          }
        });
      },


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/ivLf8et
via IFTTT

Column 'client_id' cannot be null

I am trying to run:

php artisan passport:install

And it is returning me this error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null (SQL: insert into oauth_personal_access_clients (client_id, updated_at, created_at) values (, 2022-11-0 8 07:58:48, 2022-11-08 07:58:48))

I am on laravel 5.5 with php 7.1. What am I doing wrong here? Passport version is 2.0.4.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/6XfoOiy
via IFTTT

lundi 7 novembre 2022

Laravel 5.6: sending email to BCC without adding email in TO()

How to send email to only bcc() without to(). When I tried, I got error

Error Information.

URL: http://example.com Parameters: [] Request Name: Request Method: GET Line Number: 309 File: /var/www/html/project_name/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php Client IP: 127.0.0.1 HTTP Referer: Is Secure: Is Ajax: userAgent: Symfony content: Error Message: Whoops! There was an error. ErrorException (E_WARNING) Illegal string offset 'address' ErrorException thrown with message "Illegal string offset 'address'" Stacktrace: #38 ErrorException in /var/www/html/project_name/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php:309 #37 Illuminate\Foundation\Bootstrap\HandleExceptions:handleError in /var/www/html/project_name/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php:309

Sending email to all bcc without using to



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/fVZPhXe
via IFTTT

I want to get the list of users who were present in the club from 10 AM to 12 PM using an SQL query in Laravel eloquent

thank you for reading this issue. please help me with the below issue

I want to user list which users in the club at the time between

  • 022-11-07 11:32:48 - 2022-11-07 12:32:48

below is data store in DB

  • In Time--------------------Out Time----------------- be show in result

  • 2022-11-07 11:32:48 - 2022-11-07 12:32:48 => 1

  • 2022-11-07 10:32:48 - 2022-11-07 11:33:00 => 1

  • 2022-11-07 12:32:00 - 2022-11-07 13:32:00 => 1

  • 2022-11-07 11:45:00 - 2022-11-07 12:15:00 => 1

  • 2022-11-07 10:00:00 - 2022-11-07 13:00:00 => 1

  • 2022-11-07 09:30:00 - 2022-11-07 11:30:00 => 0

  • 2022-11-07 12:35:00 - 2022-11-07 13:32:48 => 0

$activity = Activity::findOrFail($activity_id);

$users = User::whereHas('activities', function ($q) use ($activity) {
   $q->where('activities.activity_id', $activity->activity_id);
})->whereHas('bookingActivities', function ($query) use ($booking) {
   $query->whereNull('cancelled_by')
   ->whereBetween('bookingActivities.entry_time', [$booking->entry_time, $booking->exit_time])
   ->orWhereBetween('bookingActivities.exit_time', [$booking->_entry_time, $booking->exit_time]);
})->paginate();

I have add the query and it will give me 4 result it Should be 5

please help me to how can i add the query so i can get expect result.

thanks in advance



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/jCpiNDZ
via IFTTT

samedi 5 novembre 2022

Laravel Fatal error: Uncaught ReflectionException: Class App\Http\Kernel does not exist

Tried to install ** maatwebsite/excel** using composer as,

composer require maatwebsite/excel

but it throws Kernel does not exist error.

There are kernel files in the following locations

app\Console\Kernel.php app\Http\Kernel.php

Also tried composer update, composer dump-autoload. Tried deleting vendor folder and then composer install

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.12",
        "laravel/tinker": "^2.5",
        "laravel/ui": "^3.2",
        "maatwebsite/excel": "^3.1"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.2",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "platform-check": false
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

```
`

How do i resolve this issue.


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/URYgzbT
via IFTTT

vendredi 4 novembre 2022

WhatsApp API integration in Laravel not working

I have issue in my laravel project, the code below is working fine in core php, but it's not workng in laravel

i'm using old laravel version 5.5

even not showing any error

please help me ASAP, i hava a deadline

please help me ASAP, i hava a deadline please help me ASAP, i hava a deadline

`if($request->has('whatsapp') && $request->whatsapp!=0){
                $url = "https://graph.facebook.com/v15.0/{key}/messages";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('{auth key}', 'Content-Type: application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data3 = [
  
    "type"=>"body",
    "parameters" => [
      "type"=>"text",
      "text" => "Mr Jibran"
    ]
];

$data2 = [
  "name"=>"sample_issue_resolution",
"language"=> ["code"=> "en_US" ],
"components" => $data3
];

/*
components:{
  type:body,
  parameters {
    type:text,
    text:Mr Jibran
  }}"

*/

$data = array(
  "messaging_product"=>"whatsapp",
  "to"=>"my number",
  "type"=>"template",
  "template"=> array(
    "name"=>"sample_issue_resolution",
    "language"=> array ("code"=> "en_US" ),
    "components" => array(
      ["type"=>"body",
    "parameters" => array(
      ["type"=>"text",
      "text" => "Mr Jibran"]
    )]
    )
  )
)
;



$fields_string = json_encode($data);

curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);

$resp = curl_exec($curl);
curl_close($curl);

echo $resp;
                
            }

        }

    }`


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/hUlAGRZ
via IFTTT

jeudi 3 novembre 2022

Laravel v5.6 $this- validate()

I want to print error in session in controller using validation methos $this- validate() only and not

$validator = Validator::make()

I want to print error in session in controller using validation methos $this- validate() only and not

$validator = Validator::make()


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/oMuj6lJ
via IFTTT

Remove/unset specific row from collection in Laravel

I have this eloquent query

 $result= Result::query()
            ->where('city_id', '=', $search_city)
            ->get();
        } 

then inside loop

 foreach($result as $row)
                {
                    if(isset($row->user_id) && $row->user_id!=0)
                    {
                        $UserDetails = User::where('id',$row->user_id)->first();
                        if($UserDetails) 
                        {
                            if($UserDetails->type=='normal user')
                            {
                              // remove this specific row from result 
                            }
                
                        }
                    } 
                }

inside if condition if specific condition met i want to remove only that particular row from the result.

 return view('index', compact('result'));

Any solution Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/NCcx9Rb
via IFTTT

Instance class by some rule

I have some function converting some tag to class name.

function($tag): string {
    return '\App\Services\MyUglyServices\' . ucfirst(Str::camel($tag));
}

I want to instance some class by corresponding tag name. For example:

$obj = app('tag:my_ugly_service');
echo get_class($obj); // I want it to be \App\Services\MyUglyServices\MyUglyService

Is there any way to do it using service providers?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/jUc85pD
via IFTTT

mardi 1 novembre 2022

Laravel 5 User::where() My where call isn't working with laravel 5

I have narrowed my error down to this line of code

$user= User::where(['email'=>$req->email])->first();

it it not working with Laravel 5 I think this is from a Laravel 4 project. How do I update it to 5?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/Riys3u7
via IFTTT

Why my excel import date format is not working in laravel

I try to import the excel data file but my date format is not working. other than that data import is working file only issue is in the date format Please help to solve this issue.

enter image description here

this is my import code.

<?php

namespace App\Imports;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

use App\student_import;

use App\centres;
use App\Course;

class ImportStudent implements ToModel,WithHeadingRow
{
    /**
    * @param Collection $collection
    */

    public function model(array $row)
    {
        $rowNumber = array_values($row);

        $insert_data[] = array(
            'stud_dob' => Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($rowNumber[8])),
            'stud_gender' => $rowNumber[9],
            'stud_add1' => $rowNumber[10],
            'stud_nationality' => $rowNumber[13],
            'stud_registration_date' => Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($rowNumber[14])),
            'stud_completion_date' => Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($rowNumber[15])),
            'stud_course_status' => $rowNumber[16]
        );

    }
}

This is the error I'm getting when import the data file

enter image description here

enter image description here



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/b3fD78Y
via IFTTT

lundi 31 octobre 2022

Laravel taking 100% MySQL DB CPU and no jobs visible in php artisan queue:listen, Laravel 5.7

The MySQL DB CPU is running at 95%+ basically at all times, even when there's seemingly no activity in the app. It doesn't happen right away. Only once the app has been running for a while, but then it keeps at 95% CPU even once there's seemingly no activity.

The number of active sessions / connections gradually climbs from dozens to even hundreds. Looking at the MySQL processes on RDS reveals a dozen processes trying to use 8% of the DB CPU each for some reason.

I've checked for Laravel jobs via php artisan queue:listen but nothing appears.

Checked the database and query logs, and there are many DB logs which suggest a job or something occurring in a loop, but no indication as to what the source of those jobs are as the queries being ran are generic queries and could be called from many different places in the application.

We do not believe this is due to user activity, but if it is, it's some kind of user action whicih results in some kind of a server loop.

Checked application and error logs and nothing in particular stands out.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/nlCND8W
via IFTTT

when i upload laravel website form local to live sever this error that i face can any one help me

SQLSTATE[HY000] [2002] Connection refused (SQL: select * from sessions where id = E70KsnO9rKtK9ATW71zmd9AfGW1ek7nAhnD2wQjS limit 1) error that i face

any one help me to solve this



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/XfwyF4N
via IFTTT

dimanche 30 octobre 2022

Dynamic Scopes not working properly when dealing with tags->products() (many to many relationship) Laravel Livewire

its throwing me this error:

Call to a member function products() on null

i want the filter to be changed in real time and it works too just not working properly with many to many relationship:

this doesnt work

$tag1 =  request()->query('tag');  
$tag = Tag::where('name', $tag1)->first();
$products = $tag->products()->SortFilterBy($this->sortBy)->InStock()->paginate($this->perPage);

but when i manually type this

$products = $tag->products()->SortFilterBy('featured')->InStock()->paginate($this->perPage); //
Works But not in real time
$products = Product::SortFilterBy($this->sortBy)->InStock()->paginate($this->perPage); //WORKS IN REAL TIME

i am using livewire for this.

The Scope:


public function scopeSortFilterBy($query,$sortBy = "")
{
switch ($sortBy) {
case 'featured':

                return $query->where('featured','=', -1);
    
                break;
    
            case 'low':
           
                return $query->orderBy('sale_price', 'asc');
               
                break;
            case 'heigh':
                return $query->orderBy('sale_price', 'desc');
                break;
            default:
    
            return $query;
            
            break;
        }
      
    }

it do shows me the value of dd($this->sortBy) whenever i change the dropdown.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/LB0a6N7
via IFTTT

samedi 29 octobre 2022

Laravel clearing config causing wierd X to show up

I'm currently using laravel 5.8 in a project and stumbled on a weird problem, after lanching the commande optimize:clear a Wierd Caracheter will show up when executing any other commande and also causing ajax requests to fail here is an example of the problem enter image description here

this happening in all the team machines, not just mine. the second problem reloading a page, every time We load a page we see this screen before it redirected to the actual view
enter image description here

the only found solution is to run the commande Artisan config:cache



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/sykYgXf
via IFTTT

vendredi 28 octobre 2022

how to improve my performance for this complex query | Laravel , Datatabels

Hi everyone i have a very complex query to get Finance data, its like 4 Join and when the data is more than 1000 it getting slow when it loads in datatables how i can make it faster

this is the controller code for ajax :

  $financial_entries = FinanceEntryMod::select([
        DB::raw("ROUND(( 
            select SUM(finance_transaction.equivalent) from finance_transaction  where 
            finance_transaction.entry_id = financial_entries.id and
            finance_transaction.type = 'credit' 
        ), 2) as eqivalent_sum"),
        'financial_entries.id',
        'financial_entries.created_by',
        'financial_entries.branch_id',
        'financial_entries.order_id',
        'financial_entries.number',
        DB::raw('IFNULL(branches.name, IFNULL(v2_branches.name, "main_branch")) AS branch_name'),
        'financial_entries.v2_order_id as v2_order_id',
        'financial_entries.v2_document_id as v2_document_id',
        'financial_entries.date',
        'financial_entries.is_generated',
        'financial_entries.note',
        'financial_entries.created_at',
        'financial_entries.updated_at',
        DB::raw('
            DATE_FORMAT(financial_entries.date, "%Y-%m-%d") AS new_date,
            DATE_FORMAT(financial_entries.created_at, "%Y-%m-%d") AS new_created_at
        ')
    ])
    ->leftJoin('branches', function ($join) {
        $join->on("branches.id", "=", "financial_entries.branch_id");
    })
    ->leftJoin('finance_transaction', function ($join) {
        $join->on("financial_entries.id", "=", "finance_transaction.entry_id");
    })
    ->leftJoin('finance_accounts', function ($join) {
        $join->on("finance_accounts.id", "=", "finance_transaction.account_id");
    })
    ->leftJoin('v2_branches', function ($join) { 
        $join->on("v2_branches.id", "=", "finance_accounts.v2_branch_id"); 
    })
    ->where('financial_entries.is_deleted', '=', '0')
    ->groupBy('financial_entries.id');

and in the script : im using this

   "pageLength": 30,
        "serverSide"   : true,
        "processing"   : true,
        "columns": 

please help me to improve it thanks all



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/i4YJzuX
via IFTTT

jeudi 27 octobre 2022

MethodNotAllowedHttpException at RouteCollection->methodNotAllowed(array('POST'))

I'm trying to use POST to let user log in with correct email/password. I keep getting this error

MethodNotAllowedHttpException at RouteCollection->methodNotAllowed(array('POST'))

web.php

<?php

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

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

Route::post("/login",[UserController::class,'login']);

UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    //
    function login(request $req)
    {
        return $req->input();
    }
}

login.blade.php

@extends('master')
@section('content')
<div class="container custom-login">
    <div class="row">
        <div class="col-sm-4 col-sm-offset-4">
            <form action="/login" method="POST">
            <div class="form-group">
                @csrf
                <labe for="exampleInputEmail">Email address</label>
                <input type="email" name="email" class="form-control" id="exampleInputEmail" placeholder="Email">
            </div>
            <div class="form-group">
                <labe for="exampleInputPassword">Password</label>
                <input type="password" name="password" class="form-control" id="exampleInputPassword" placeholder="Password">
            </div>
            <button type="submit" class="btn btn-default">Login</button>
            </form>
        </div>
    </div>
</div>

@endsection

I tried opening the login page but POST is having issues. I expected the login page to use POST to check credentials in my database.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/IaZGujx
via IFTTT

mercredi 26 octobre 2022

I want to pull mysql export text from laravel

I want to pull mysql export text from laravel

INSERT INTO 'example' ('id', 'name') VALUES (1, 'example'), 
(2, 'example2'),
(3, 'example3'),
(4, 'example4');

Like this

Thank you.

I searched for sql query but couldn't find it



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/gGaOoJT
via IFTTT

dimanche 23 octobre 2022

JWT Token not expiring in Laravel

I have set 'ttl' => env('JWT_TTL',1), to 1 minutes so the token should expire in 1 minute but in my case it is not expiring i have run php artisan serve and cleared the cache also. Because on production server i was getting this error : Token has expired and can no longer be refreshed i was trying to debug it on my system after the token is expired.

JWT config:

<?php

/*
 * This file is part of jwt-auth.
 *
 * (c) Sean Tymon <tymon148@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

return [

    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Secret
    |--------------------------------------------------------------------------
    |
    | Don't forget to set this in your .env file, as it will be used to sign
    | your tokens. A helper command is provided for this:
    | `php artisan jwt:secret`
    |
    | Note: This will be used for Symmetric algorithms only (HMAC),
    | since RSA and ECDSA use a private/public key combo (See below).
    |
    */

    'secret' => env('JWT_SECRET'),

    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Keys
    |--------------------------------------------------------------------------
    |
    | The algorithm you are using, will determine whether your tokens are
    | signed with a random string (defined in `JWT_SECRET`) or using the
    | following public & private keys.
    |
    | Symmetric Algorithms:
    | HS256, HS384 & HS512 will use `JWT_SECRET`.
    |
    | Asymmetric Algorithms:
    | RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
    |
    */

    'keys' => [

        /*
        |--------------------------------------------------------------------------
        | Public Key
        |--------------------------------------------------------------------------
        |
        | A path or resource to your public key.
        |
        | E.g. 'file://path/to/public/key'
        |
        */

        'public' => env('JWT_PUBLIC_KEY'),

        /*
        |--------------------------------------------------------------------------
        | Private Key
        |--------------------------------------------------------------------------
        |
        | A path or resource to your private key.
        |
        | E.g. 'file://path/to/private/key'
        |
        */

        'private' => env('JWT_PRIVATE_KEY'),

        /*
        |--------------------------------------------------------------------------
        | Passphrase
        |--------------------------------------------------------------------------
        |
        | The passphrase for your private key. Can be null if none set.
        |
        */

        'passphrase' => env('JWT_PASSPHRASE'),

    ],

    /*
    |--------------------------------------------------------------------------
    | JWT time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in minutes) that the token will be valid for.
    | Defaults to 1 hour.
    |
    | You can also set this to null, to yield a never expiring token.
    | Some people may want this behaviour for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    | Notice: If you set this to null you should remove 'exp' element from 'required_claims' list.
    |
    */

    //'ttl' => env('JWT_TTL',1440),
    'ttl' => env('JWT_TTL',1),
    //'ttl' => null,

    /*
    |--------------------------------------------------------------------------
    | Refresh time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in minutes) that the token can be refreshed
    | within. I.E. The user can refresh their token within a 2 week window of
    | the original token being created until they must re-authenticate.
    | Defaults to 2 weeks.
    |
    | You can also set this to null, to yield an infinite refresh time.
    | Some may want this instead of never expiring tokens for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    |
    */

    //'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),
    'refresh_ttl' => null,

    /*
    |--------------------------------------------------------------------------
    | JWT hashing algorithm
    |--------------------------------------------------------------------------
    |
    | Specify the hashing algorithm that will be used to sign the token.
    |
    | See here: https://github.com/namshi/jose/tree/master/src/Namshi/JOSE/Signer/OpenSSL
    | for possible values.
    |
    */

    'algo' => env('JWT_ALGO', 'HS256'),

    /*
    |--------------------------------------------------------------------------
    | Required Claims
    |--------------------------------------------------------------------------
    |
    | Specify the required claims that must exist in any token.
    | A TokenInvalidException will be thrown if any of these claims are not
    | present in the payload.
    |
    */

    'required_claims' => [
        'iss',
        'iat',
        'exp',
        'nbf',
        'sub',
        'jti',
    ],

    /*
    |--------------------------------------------------------------------------
    | Persistent Claims
    |--------------------------------------------------------------------------
    |
    | Specify the claim keys to be persisted when refreshing a token.
    | `sub` and `iat` will automatically be persisted, in
    | addition to the these claims.
    |
    | Note: If a claim does not exist then it will be ignored.
    |
    */

    'persistent_claims' => [
        // 'foo',
        // 'bar',
    ],

    /*
    |--------------------------------------------------------------------------
    | Lock Subject
    |--------------------------------------------------------------------------
    |
    | This will determine whether a `prv` claim is automatically added to
    | the token. The purpose of this is to ensure that if you have multiple
    | authentication models e.g. `App\User` & `App\OtherPerson`, then we
    | should prevent one authentication request from impersonating another,
    | if 2 tokens happen to have the same id across the 2 different models.
    |
    | Under specific circumstances, you may want to disable this behaviour
    | e.g. if you only have one authentication model, then you would save
    | a little on token size.
    |
    */

    'lock_subject' => true,

    /*
    |--------------------------------------------------------------------------
    | Leeway
    |--------------------------------------------------------------------------
    |
    | This property gives the jwt timestamp claims some "leeway".
    | Meaning that if you have any unavoidable slight clock skew on
    | any of your servers then this will afford you some level of cushioning.
    |
    | This applies to the claims `iat`, `nbf` and `exp`.
    |
    | Specify in seconds - only if you know you need it.
    |
    */

    'leeway' => env('JWT_LEEWAY', 0),

    /*
    |--------------------------------------------------------------------------
    | Blacklist Enabled
    |--------------------------------------------------------------------------
    |
    | In order to invalidate tokens, you must have the blacklist enabled.
    | If you do not want or need this functionality, then set this to false.
    |
    */

    'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', false),

    /*
    | -------------------------------------------------------------------------
    | Blacklist Grace Period
    | -------------------------------------------------------------------------
    |
    | When multiple concurrent requests are made with the same JWT,
    | it is possible that some of them fail, due to token regeneration
    | on every request.
    |
    | Set grace period in seconds to prevent parallel request failure.
    |
    */

    'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),

    /*
    |--------------------------------------------------------------------------
    | Cookies encryption
    |--------------------------------------------------------------------------
    |
    | By default Laravel encrypt cookies for security reason.
    | If you decide to not decrypt cookies, you will have to configure Laravel
    | to not encrypt your cookie token by adding its name into the $except
    | array available in the middleware "EncryptCookies" provided by Laravel.
    | see https://laravel.com/docs/master/responses#cookies-and-encryption
    | for details.
    |
    | Set it to true if you want to decrypt cookies.
    |
    */

    'decrypt_cookies' => false,

    /*
    |--------------------------------------------------------------------------
    | Providers
    |--------------------------------------------------------------------------
    |
    | Specify the various providers used throughout the package.
    |
    */

    'providers' => [

        /*
        |--------------------------------------------------------------------------
        | JWT Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to create and decode the tokens.
        |
        */

        'jwt' => Tymon\JWTAuth\Providers\JWT\Lcobucci::class,

        /*
        |--------------------------------------------------------------------------
        | Authentication Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to authenticate users.
        |
        */

        'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,

        /*
        |--------------------------------------------------------------------------
        | Storage Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to store tokens in the blacklist.
        |
        */

        'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,

    ],

];

and i have middleware also

<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JwtMiddleware extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
          /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    try {
        $user = JWTAuth::parseToken()->authenticate();
    } catch (Exception $e) {
        if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
            return response()->json(['error' => 'Token is Invalid'],401);
        }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
            try
            {
              $refreshed = JWTAuth::refresh(JWTAuth::getToken());
              $user = JWTAuth::setToken($refreshed)->toUser();
              $request->headers->set('Authorization','Bearer '.$refreshed);
            }catch (JWTException $e){
                return response()->json([
                    'code'   => 103,
                    'message' => 'Token cannot be refreshed, please Login again'
                ]);
            }
           // return response()->json(['error' => 'Token is Expired'],401);
        }else{
            return response()->json(['error' => 'Authorization Token not found'],401);
        }
    }
    return $next($request);
    }
    
}

Angular Auth Interceptors:

export class AuthInterceptor implements HttpInterceptor {
    constructor(private tokenService: TokenService,private _router: Router,private auth: AuthStateService, private toastr: ToastrService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const accessToken = this.tokenService.getToken();
        req = req.clone({
            setHeaders: {
                Authorization: "Bearer " + accessToken
            }
        });
        //return next.handle(req);

        return next.handle(req).pipe(
            catchError(
              (err, caught) => {
                if (err.status === 401){
                  this.handleAuthError();
                  return of(err);
                }
                throw err;
              }
            )
          );
    }
    private handleAuthError() { 
        this.toastr.error('Warning', 'Unauthorised Access');
        this.auth.setAuthState(false);
        this.tokenService.removeToken();
        this._router.navigate(['/login'])
      }
    
}

I'm not getting 401 error but 500 error i want if the token if invalid or expired it should redirect to login Page.

Please suggest some solution, Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/0n9LQwo
via IFTTT