jeudi 31 décembre 2020

Laravel scheduler to charge users recurring payments via peach payment

I have a project that uses Ionic and Laravel as a backend. The user uses our app based on monthly or annual subscriptions. So far I have been successful in implementing the initial charge of the subscriptions via peach payment.

So now I want every month end to charge the recurring monthly or annual subscriptions.

The idea I have is as follow:

  1. Run Scheduler to check subscriptions table for all monthly active users where the expiry date is month-end (31/12/2020) or is the current month.
  2. Generate transactions for all those users and save them to the billing table ( this is to get transaction_id to send to a payment gateway).
  3. Run the scheduler using the billing info where created_at is today, send each transaction to payment gateway api for processing.
  4. On Api response get status of each payment request and save/update the db billing table using transaction_id as primaryKey.
  5. Update the subscriptions table (status, new expiry date) after the billing table is update

Any help or direction with this will be appreciated. The code below is the code to use for sending a single charge request.

/**
     * Monthly Subscriptions
     * @param Request $request
     */
    public function chargeMonthlySubscription(Request $request)
    {
        $curl = curl_init();
        $url = "$this->url/registrations/$request->registrationId/payments";
        $data = "entityId=$this->entityId" .
            "&amount=$request->subscription_amount" .
            "&currency=ZAR" .
            "&customer.merchantCustomerId=$request->subscription_no" .
            "&customer.givenName=$request->first_name" .
            "&customer.surname=$request->last_name" .
            "&recurringType=$request->recurring_type" .
            "&paymentType=DB";

        curl_setopt_array($curl, array(
            CURLOPT_URL => "$url",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => array(
                $this->token,
                "Content-Type: application/x-www-form-urlencoded"
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;

    }



via Chebli Mohamed

why is my for loop not getting updated value on 2nd iteration?

consider i have an array like this $customersids = [10 , 20 , 30 , 40] out side the loop which i am updating later according to some conditions example if updated array is $customersids = [10 , 30] on second iteration my loop should use this updated $customersids but it is not taking updated and my result is null here is my small piece of code example

        $customersids = Customer::whereIn('created_by', $adminot)->pluck('id')->toArray(); // this id should be updated for looping
                for ($a = 0; $a < 2 ; $a++){
                $customerscords = Customer::whereIn('id', $customersids)->pluck('location_url')->toArray(); **//on first iteration it should use upper $customersids and on 2nd iteration it should use updated $customersids = [10 , 30] but it is not taking updated value**
                foreach ($customerscords as $short){
                 $shortest[] = $this->getsortedDistance($cords , $cords1 ,$short);
                } 
    // example here i updated $customersids = [10 , 30]
}

here is my full code

$adminot = array_merge($ids, User::where('ot_of', Auth::id())->pluck('id')->toArray());
$new_ids = "empty";
$cords = 31.5815886;
$cords1 = 74.3779746;
$customersids = Customer::whereIn('created_by', $adminot)->pluck('id')->toArray(); // this id should be updated for looping
for ($a = 0; $a < 2 ; $a++){
$customerscords = Customer::whereIn('id', $customersids)->pluck('location_url')->toArray();  
foreach ($customerscords as $short){
 $shortest[] = $this->getsortedDistance($cords , $cords1 ,$short);
}
for($i = 0; $i < sizeof($customersids); $i++){
    $maping[$customersids[$i]] =  $shortest[$i];
}
$key_val = array_keys($maping, min($maping));// this gets keys and shortest value
if( $new_ids == "empty"){ // this stores srtoed ids
    $new_ids = $key_val;
}
else{
 array_push($new_ids , $key_val);    
}
$get_last_id = end($new_ids); 
$getcordslastid = Customer::where('id' , $get_last_id)->pluck('location_url')->first();
$getcordslastid = explode(',', $short);
$cords = @$getcordslastid[0];
$cords1 = @$getcordslastid[1];
$customersids = array_diff($customersids , $new_ids); // this sets customer ids for looping
}

why my loop resulting null on second iteration what mistake i am making in it it should use all the updated value on 2nd iteration but it is not taking updated values



via Chebli Mohamed

Bad Method Call Exception Laravel

Following is my route code

Route::get( 'generate_pdf', 'Admin\UserController@generateproviderlist' )->name('provider.pdf') ;

and Controller

<?php

 namespace App\Http\Controllers\Admin;

 use Illuminate\Http\Request;
 use Intervention\Image\ImageManagerStatic as Image;
 use App\Http\Controllers\Controller;

 // For Uploading image, we need to include these libraries
 use Illuminate\Support\Facades\Input;
 use Illuminate\Support\Facades\File;
 use Illuminate\Support\Facades\URL;

 use Illuminate\Support\Facades\Hash;

 use App\User;
 use App\Profile;
 use App\ProfileAddress;
 use App\Service;
 use App\Category;
 use App\ProviderService;
 use App\ProviderCategory;

 class UserController extends Controller
 {
      public function generateproviderlist( Request $request )
     {
         $user_list = User::join('profiles', 'profiles.user_id', '=', 'users.id')
                            ->where('users.is_deleted', 0)
                            ->where( 'users.user_type', 2 )
                            ->select('users.id', 'users.is_enable', 'users.email', 'users.phone',      'profiles.company_name', 'profiles.reg_number')
                            ->get() ;

         $mpdf = new \Mpdf\Mpdf();
         $html = view('admin.provider.provider_pdf', ['provider_list' => $user_list])->render();
         $mpdf->WriteHTML($html);
         $mpdf->Output('done_list.pdf', 'D');

        return false;
     }
 }

When I visit the url I get an exception

Method App\Http\Controllers\Admin\UserController::generateproviderlist does not exist.

Following is the telescope url for the exception. https://do-net.com/telescope/requests/925fbd80-c2a8-4ed5-981d-cc0a21bb9c29

I have tried Clearing the cache and changed the function name but it isn't working. the other routes are working perfectly fine. The route is working fine on my localhost but it is giving 500 error on the live server



via Chebli Mohamed

mercredi 30 décembre 2020

Invalid characters and post-update-cmd error on composer update Laravel

Want to update any dependencies show below error

1 - [ErrorException]
Invalid characters passed for attempted conversion, these have been ignored

2 - Script php artisan optimize handling the post-update-cmd event returned with error code 1

composer file:

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": [
    "framework",
    "laravel"
],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=7.4.3",
    "laravel/framework": "5.2.*",
    "league/flysystem-aws-s3-v3": "~1.0",
    "yajra/laravel-datatables-oracle": "~6.0",
    "laravel/socialite": "^2.0",
    "skovmand/mailchimp-laravel": "1.*",
    "barryvdh/laravel-dompdf": "0.6.*",
    "google/cloud": "^0.135.0",
    "superbalist/flysystem-google-storage": "^7.2",
    "php-ffmpeg/php-ffmpeg": "^0.16.0"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~4.0",
    "symfony/css-selector": "2.8.*|3.0.*",
    "symfony/dom-crawler": "2.8.*|3.0.*"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},
"scripts": {
    "post-root-package-install": [
        "php -r \"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"
}

}



via Chebli Mohamed

php artisan schedule:run not returning response as expectation?

We have scheduled jobs in our system. It was working fine on laravel 5.8 . But now we have updated it to laravel 8. Before that when we run command php artisan schedule:run it triggers those jobs . But now it is returning this response Running scheduled command: Callback I don't know what does this means.

Here is our jobs

     $schedule->call(function () {
            \App\Jobs\Invoice\CreateInvoiceAutomatically::withChain([
                (new \App\Jobs\Invoice\FillUpInvoices)->delay(Carbon::now()->addMinutes(2))->onQueue('invoice'),


            ])->dispatch()->onQueue('invoice');

        })->everyMinute('16:47');

         $schedule->job(new \App\Jobs\Invoice\AutoSumChargesForInvoice,'invoice')->dailyAt('17:16');

    }
    ```


via Chebli Mohamed

how to remove array keys and double quotes from array in php?

In an array i have key and its value in double quotes like this

$a = [

0 => "19 => 0"
  
1 => "20 => 0"
 
2 => "21 => 0"
  
3 => "24 => 18.831126689097"
  
4 => "25 => 0"
  
5 => "26 => 0.85071506409078"]

i want output delete all keys and double quotes how i can do that in php?

19 => 0
  
20 => 0
 
21 => 0
  
24 => 18.831126689097
  
25 => 0
  
26 => 0.85071506409078


via Chebli Mohamed

FleetCart keep redirect me to pre-installation

I am trying to use fleetcart, so after I first visit the domain it takes me to pre-installation, and after I fill the input fields and click complete everything goes without any single error, but, when I click go to your store it redirects me to pre-intsallation, also tried to access /admin directly from address bar nothing works.



via Chebli Mohamed

Can't Retrieve One to Many Relationship Data In Laravel

I have a bit strange of problem about retrieving one to many relationship data in Laravel.

Model

// JobTypes model
public function jobs()
{
    // one type of job has many jobs
    return $this->hasMany('App\Jobs', 'id'); // id refer to jobs.id
}

// Jobs model
public function job_types()
{
    // one job only belongs to one type of job
    return $this->belongsTo('App\jobTypes');
}

Pivot table

 Schema::create('jobs_job_types', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('jobs_id')->unsigned()->nullable();
        $table->integer('job_types_id')->unsigned()->nullable();
        $table->timestamps();

        $table->foreign('jobs_id')->references('id')->on('jobs');
        $table->foreign('job_types_id')->references('id')->on('job_types');
    });

Controller

$data = \App\JobTypes::paginate($items);

    return view('jobs.index', compact('data'))->with(array('showData' => $showData, 'count' => $count))->withItems($items);

View

@foreach($data as $jobType)
        <td>
          @foreach($jobType->jobs as $category)
            
          @endforeach
        </td>
    @endforeach 

Am I missing something?



via Chebli Mohamed

how to check if array contains multi strings Laravel

i have collection

Illuminate\Support\Collection {#1453
  #items: array:4 [
    0 => "three"
    1 => "nine"
    2 => "one"
    3 => "two"
  ]
}

and this string

'one', 'two', 'three'

i am trying to validate if these all strings available in array

$array->contains('one', 'two', 'three')

it should return true

but everytime i am getting false

what i am doing wrong please explain thank you



via Chebli Mohamed

mardi 29 décembre 2020

Why is my $items doesn't hold a group of $item? Laravel 8 Ecommerce

I'm from the same post here but I've found the root problem why is my quantity won't increment but I don't know how to solve this. The problem is at my isset function (in Cart.php), because I tried to echo something there and just realized the function isn't running. This is the error pops up when I removed isset function at the if($this->items). I tried to dd($items) too, and it said null. Why is my $items isn't holding a group of $item? Do you guys know why and how to solve this?

p/s: from the previous post, I've removed my $oldCart and replace it with $cart, and I'm expecting $cart to overwrite itself. These are all the codes related to my shopping cart.

In Cart.php

<?php

namespace App\Models;

class Cart
{
    private $items = array();
    public $totalQty = 0;
    public $totalPrice = 0;


    public function __construct($cart)
    {
        if ($cart) {
            //dd($this);
            $this->items = $cart->items;
            $this->totalQty = $cart->totalQty;
            $this->totalPrice = $cart->totalPrice;
        }
    }


    public function add($item, $id)
    {
        global $cart;
        global $items;

        //default values if item not in cart


        $storedItem = [
            'qty' => 0,
            'price' => $item->price,
            'item' => $item
        ];


        //if item is already in shopping cart
        if (isset($this->$items) ? $items : false) {
            if (array_key_exists($id, $this->items)) {
                $storedItem = $this->items[$id];
            }
        }

        //dd($items);
        $storedItem['qty']++;
        $storedItem['price'] = $item->price * $storedItem['qty'];
        $this->items[$id] = $storedItem;
        $this->totalQty++;
        $this->totalPrice += $item->price;
    }
}

in FoodController.php

<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Food;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;


class FoodController extends Controller
{
public function addtoCart(Request $request, $id, Food $foods)
    {

        $foods = Food::find($id);

        //check in session if cart already contains product
        $cart = Session::has('cart') ? Session::get('cart') : null;

        //dd($cart);
        //if it did contain products, pass them to constructor
        if (!$cart) {
            $cart = new Cart($cart);
        }

        $food = $foods->id;
        $cart->add($foods, $food);

        Session::put('cart', $cart);
        //dd($request->session()->get('cart'));


        return view('cart', ['food' => $cart->items, 'totalPrice' => $cart->totalPrice]);
    }

    public function getCart()
    {
        if (!Session::has('cart')) {
            return view('cart');
        }

        $cart = Session::get('cart');
        $cart = new Cart($cart);
        return view('cart', ['food' => $cart->items, 'totalPrice' => $cart->totalPrice]);
    }
}

in cart.blade.php

    @foreach ($food as $foods)
                        
                        
       <p align="left"><a href="#">  </a> <span class="price">MYR  </span></p>
       <p align="left">Quantity</p>
       <p><input class="w3-input w3-p-adding-16 w3-border" type="number" placeholder="Quantity" value="" required name="quantity"></p>
                        
@endforeach
                        
                        
<hr class="new1">
                        
<p align="left">Total <span class="price"><b>MYR </b></span></p>


via Chebli Mohamed

send to repository class variable laravel from controller

i´m traying to do query into my repository to get galleries that to have a restaurant and i need seach for id. One restaurant´s gallery only can to have 10 images, but we can to have more than one restaurant. I need that when one restaurant will have a 10 images, it can´t upload any more and disable this restaurant.

sorry for my english, i hope that i can explain me correctly.

my controller:

if (auth()->user()->hasRole('admin')){
            $restaurant = $this->restaurantRepository->pluck('name', 'id');
        }else{
            $restaurant = $this->restaurantRepository->galleries()->myActiveRestaurants()->pluck('name', 'id');
        }
        // get all media gallery of restaurant
        //$media = $this->galleryRepository->getCountMedia();
        foreach($restaurant as $res){
            $res->cg = (count($res->galleries()->get()) == 10);
        }

        $hasCustomField = in_array($this->galleryRepository->model(), setting('custom_field_models', []));
        if ($hasCustomField) {
            $customFields = $this->customFieldRepository->findByField('custom_field_model', $this->galleryRepository->model());
            $html = generateCustomField($customFields);
        }
        return view('galleries.create')->with("customFields", isset($html) ? $html : false)->with("restaurant", $restaurant)/*->with('imagesRestaurant', $media)*/;

here i´m calling to model function galleries() where i have a function to get, restaurant_id

but in my web, result is:

Call to a member function galleries() on string

i need to get restaurant_id for call here my repository:

public function getCountMedia(){
        return Gallery::join("user_restaurants", "user_restaurants.restaurant_id", "=", "galleries.restaurant_id")
                        ->where('user_restaurants.user_id', auth()->id())->count();
    }

i don´t want auth()->id() i need restaurant_id for in my controller extract that restaurant to have 10 image

i hope that any can help me, please



via Chebli Mohamed

In Laravel 5 Left Join Donot Update Row in Database

I have used Below Query to update column in database but it do not update column but when I remove join then it update database.

`$userrequestforcasecopy=DB::table('user')      
  -> leftJoin('token','user.id','=','token.request_id')     
  ->where('user.id',$rowId)   
  ->update(['approved_status'=> 2]);`       


via Chebli Mohamed

lundi 28 décembre 2020

Downgrade Laravel 7 to Laravel 5

I developed a laravel project with Laravel 7 and PHP 7 on my laptop.

I want to deploy to a server but the server use PHP 5.4. (I cannot upgrade the server PHP version).

I check that Laravel 5 compatible run on PHP 5.4 and i tried to downgrade the project as well as create raw Laravel 5 Project but it not successful.

Is there any way the server can run my Laravel 7 project? And is it actually possible to downgrade Laravel 7 to Laravel 5?



via Chebli Mohamed

Reactjs - Export to csv showing in encoded format

I am using maatwebsite to export the records to CSV file. Using php laravel for backend.

Here is my following code:

Controller code:

    public static function exportCsvReport($params){
    
    header('Content-Encoding: UTF-8');
    header('Content-type: text/csv; charset=UTF-8');
    
    return Excel::download(new UsersExport, 'invoices.xlsx');

}

UserExport model:

<?php

namespace App\Exports;
use App\Models\Api\v1\Tbcall;
use Maatwebsite\Excel\Concerns\FromCollection;

class UsersExport implements FromCollection
{

    public function collection()
    {
        return Tbcall::where('Row_Id',14407)->get();
    }
}

?>

React code:

  exportReporttoCsv(params){
    this.setState({ isDataFetched: true }, async () => {
  
  let productsData = await this.apiService.exportCsvReport(params);
  
  const url = window.URL.createObjectURL(new Blob([productsData.data]));
  const link = document.createElement('a');
  link.setAttribute('href', 'data:text/csv');
  link.href = url;

  link.setAttribute('download', 'aaa1.csv'); //or any other extension

  document.body.appendChild(link);
  link.click();

  });
  }

Output:

enter image description here

Tried in notepad as well. Still shows the encoded data.

enter image description here

File is getting downloaded but when opening the file shows like these.

Not getting what is going wrong. What changes are needed here ? Any answers will be appreciated. Thanks



via Chebli Mohamed

I have upload laravel project in github but when download it on local machine it show old file of controller

In my office I put laravel 5 project in github but when I download It on my local machine it show old controller and old php class file.I have checked controller file it is latest file but on browser it show old controller



via Chebli Mohamed

Matwebexcel getRowCount returns 0

I tried the following code following document: https://docs.laravel-excel.com/3.1/architecture/objects.html#getters

        class CategoryImport implements ToModel, WithHeadingRow, WithMultipleSheets
        {
            use SkipsFailures, Importable;
    
        private $rows = 0;
    ------

 

         public function model(array $row)
            {
            ++$this->rows;// get row count

            $this->application = (new Application());    
            $this->application->category_id = $cate_id;//
            $this->application->save();
}

public function getRowCount():int
{
    return $this->rows;
}

Call:

$import = (new CategoryImport($request, $org_file_name));
            $data = Excel::import($import, storage_path('file') . '/' . $fileName);
            $total = $import->getRowCount();

$total always returns 0;



via Chebli Mohamed

In Laravel my controller file is saved in cache .how to remove it

I update laravel controller but it donot show changes.How can I remove cache contaning controller and php class in laravel 5.5 and my php version is 7.0



via Chebli Mohamed

dimanche 27 décembre 2020

export data in excel from multiple tables

i wanted to export data from multiple table with multiple drop down

Here Is my table names

1-products------------id

2-proattrs--product_id

3-prostocks---product_id

I wwated to get data using reference id from all tables and making to dropdown in excel file for my attribute and stock table colomns

Here Is My rotes

    Route::get('export_excel', 'ImportExportController@importExportView')->name('export_excel');
    Route::post('export', 'ImportExportController@export')->name('export');
    Route::post('import', 'ImportExportController@import')->name('import');

here is my controller

                <?php
                namespace App\Http\Controllers;
                use Validator,Redirect,Response;
                use Illuminate\Http\Request;
                use App\ProductsExport;
                use App\ProductsImport;
                use Excel;
                use DB;

            class ImportExportController extends Controller
            {
                public function importExportView()
                {
                   return view('dashboard.excel.export_excel');
                }
                public function export(Request $request)
                {
                    $request->validate([
                        'primaryCategory'=>'required'          
                    ],[
                            'primaryCategory.required' => 'Please select category'
                    ]);
                    return Excel::download(new ProductsExport($request->primaryCategory), 'products.xlsx');
                }
                public function import(Request $request)
                {
                    $request->validate([
                        'bulk_file'=>'required|max:50000|mimes:xlsx,doc,docx,ppt,pptx,ods,odt,odp'          
                    ],[
                            'bulk_file.required' => 'Please upload .xlsx file'
                    ]);
                  if($request->hasFile('bulk_file')){
                        Excel::import(new ProductsImport, request()->file('bulk_file'));
                    }
                    return redirect()->route('export_excel')->with('message','Products exported successfully!');
                }
            }

And Here Is my Model

            <?php
        namespace App;
        use Illuminate\Support\Collection;
        use Maatwebsite\Excel\Concerns\ToCollection;
        use Maatwebsite\Excel\Concerns\FromCollection;
        use Maatwebsite\Excel\Concerns\WithHeadings;
        use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
        use Maatwebsite\Excel\Concerns\WithEvents;
        use Maatwebsite\Excel\Events\AfterSheet;
        use Maatwebsite\Excel\Concerns\ShouldAutoSize;
        use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
        use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
        use DB;

        class ProductsExport implements ToCollection, FromCollection, ShouldAutoSize, WithHeadings, WithEvents, WithStrictNullComparison
        {
            protected $results;
            public $catId;
            public function __construct($catId)
            {
                $this->catId = $catId;
            }
            public function collection()
            {
                // store the results for later use
                $this->results = $this->getActionItems();
                return $this->results;
            }
            public function headings(): array
            {
                $columns = [
                    'Title',
                    'Brand',
                    'Description',
                    'Gst Rate',
                    'Handling Time',
                    'Legal Disclaimer',
                    'Special Features',
                    'Return Policy',
                    'Packet Weight',
                    'Packet Width',
                    'Packet Height',
                    'Packet Length',
                    'MetaTitle',
                    'Meta Description',
                    'Search Keywords',
                    'Slug'
                ];
                return $columns;
            }
            private function getActionItems()
            {
                $select = 'title, brand ,description, gstRate, handlingTime, legalDisclaimer, specialFeatures,returnPolicy, packetWeight, packetWidth, packetHeight, packetLength, metaTitle, metaDescription, searchKeywords, slug';
                $query = \DB::table('product_adds')->select(\DB::raw($select));
                return $query->whereRaw("FIND_IN_SET(?, primaryCategory) > 0", explode(',', $this->catId))->get();
            }
            public function registerEvents(): array
            {
                return [
                    // handle by a closure.
                    AfterSheet::class => function(AfterSheet $event) {
                        // get layout counts (add 1 to rows for heading row)
                        $row_count = $this->results->count() + 1;
                        $column_count = count($this->results);
                        
                        foreach ($this->results as $brandId) {
                          $brandName = DB::table('brands')->where('id', $brandId->brand)->get();
                                        
                        // set dropdown column
                        $drop_column = 'B';
                        // set dropdown options
                        $options = [
                            $brandName[0]->brandname
                        ];
                    } 
                        // set dropdown list for first data row
                        $validation = $event->sheet->getCell("{$drop_column}2")->getDataValidation();
                        $validation->setType(DataValidation::TYPE_LIST );
                        $validation->setErrorStyle(DataValidation::STYLE_INFORMATION );
                        $validation->setAllowBlank(false);
                        $validation->setShowInputMessage(true);
                        $validation->setShowErrorMessage(true);
                        $validation->setShowDropDown(true);
                        $validation->setErrorTitle('Input error');
                        $validation->setError('Value is not in list.');
                        $validation->setPromptTitle('Pick from list');
                        $validation->setPrompt('Please pick a value from the drop-down list.');
                        $validation->setFormula1(sprintf('"%s"',implode(',',$options)));

                        // clone validation to remaining rows
                        for ($i = 3; $i <= $row_count; $i++) {
                            $event->sheet->getCell("{$drop_column}{$i}")->setDataValidation(clone $validation);
                        }
                        // set columns to autosize
                        for ($i = 1; $i <= $column_count; $i++) {
                            $column = Coordinate::stringFromColumnIndex($i);
                            $event->sheet->getColumnDimension($column)->setAutoSize(true);
                        }
                    },
                ];
            }
        }

i wanted to know ho can i get data from multiple tables And Make DropDown For Multiple Cells using reference Id Please Help Me



via Chebli Mohamed

Laravel 8 Shopping Cart item quantity wont increment

I'm a beginner in laravel and I've been trying to create a simple ecommerce web but i got stuck in this logic error for days. I've been following in a youtube tutorial about creating shopping cart but the item quantity won't increment if i add the same item in the cart. The totalPrice and totalQty seems counting fine though...
this is what i get when i tried to dd($this) into cart.php.

I think it's because i declared the array in the add function(in Cart.php) and it keeps overwriting the current quantity. but i cant declare it outside of the function or it'll throws an error saying undefined index. I've tried checking some of relevant posts here but it still didn't work. I don't know what to do anymore.
Do you guys know what's the solution? Thank you!

p/s: this is the video tutorial link that i watched. all creds to Academind for an amazing tutorial.

https://www.youtube.com/watch?v=4J939dDUH4M&list=PL55RiY5tL51qUXDyBqx0mKVOhLNFwwxvH&index=9

these are my related codes to the error.

In Cart.php

<?php

namespace App\Models;

class Cart
{
    public $items = array();
    public $totalQty = 0;
    public $totalPrice = 0;


    public function __construct($oldCart)
    {
        if ($oldCart) {
            //dd($this);
            $this->items = $oldCart->items;
            $this->totalQty = $oldCart->totalQty;
            $this->totalPrice = $oldCart->totalPrice;
        }
    }


    public function add($item, $id)
    {
        //force get $items
        global $items;

        //default values if item not in cart
        $storedItem = [
            'qty' => 0,
            'price' => $item->price,
            'item' => $item
        ];
        
        //if item is already in shopping cart
        if (isset($this->$items) ?? $items::false) {
            if (array_key_exists($id, $this->items)) {
                $storedItem = $this->items[$id];
            }
        }


        $storedItem['qty']++;
        $storedItem['price'] = $item->price * $storedItem['qty'];
        $this->items[$id] = $storedItem;
        $this->totalQty++;
        $this->totalPrice += $item->price;
        dd($this);
    }
}

In FoodController.php

 <?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Food;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

public function addtoCart(Request $request, $id, Food $foods)
        {
    
            $foods = Food::find($id);
            //check in session if cart already contains product
            $oldCart = Session::has('cart') ? Session::get('cart') : null;

            //if it did contain products, pass them to constructor
            $cart = new Cart($oldCart);
    
            $cart->add($foods, $foods->id);
    
            $request->session()->put('cart', $cart);
    
    
            return view('cart', ['food' => $cart->items, 'totalPrice' => $cart->totalPrice]);
        }
    
    public function getCart()
    {
        if (!Session::has('cart')) {
            return view('cart', ['food' => null]);
        }
    
        $oldCart = Session::get('cart');
        $cart = new Cart($oldCart);
        return view('cart', ['food' => $cart->items,'totalPrice' =>$cart->totalPrice]);
        }

in cart.blade.php

@foreach ($food as $foods)
                    
                    
    <p align="left"><a href="#">  </a> <span class = "price"> $ </span></p>
    <p align="left">Quantity</p>
    <p><input class="w3-input w3-p-adding-16 w3-border" type="number" placeholder="Quantity" value="" required name="quantity"></p>
                   
@endforeach
                    
                    
<hr class="new1">
<p align="left">Total <span class="price"><b> $ </b></span></p>


via Chebli Mohamed

why laraval routing return the object instead of echoing it or printing it directlly?

in laravel routing we can pass a closure and it returns the result. so my question is why it cannot echo or print the result than returning it?. is it the closurity property of php or laraveles routing rule.

Route::get('/',function(){
    return 'hello world';
 });


via Chebli Mohamed

Twilio Received an error from MediaStream

I am trying to integrate Twilio in my Laravel application so far I was doing great generated the access token, created the device but when I run device.connect(param) it give me this error in the console.

twilio.min.js:99 Received an error from MediaStream: Error code: 31000

I have searched the twilio documentation for this error but couldn't resolve it can anyone please help me out with this. Here's my code.

JS

function callCustomer(phoneNumber) {
    alert(phoneNumber);
    $.get("/token", {forPage: window.location.pathname}, function (data) {
        const device = new Twilio.Device();
        var params = {"phoneNumber": phoneNumber};
        device.setup(data);
        device.connect(params);
    });
}

Here is the picture of complete console error.

enter image description here

According to the error it says something about stable connection and I do have stable connection which works perfectly fine when I was working on other projects. Any hint or code will be appreciated thank you.



via Chebli Mohamed

samedi 26 décembre 2020

Call to undefined method App\Http\Controllers\ProfilesController::authorize()

I am getting error Call to undefined method App\Http\Controllers\ProfilesController::authorize() in Laravel 5.8xx but I think I am doing everything right.

Controller:

public function edit(User $user)
    {
        $this->authorize('update', $user->profile);
        return view('profiles.edit', compact('user'));
 
    }

Profile Policy

public function update(User $user, Profile $profile)
    {
        return $user->id == $profile->user_id;
    }


via Chebli Mohamed

erreur du lancement du serveur de developpement laravel?

bonsoir, je débute avec laravel et j'ai rencontrer ce soucie lorsque j'avais essayer de lancer le serveur php <> dans l'invite de commande voici ce qui est afficher

fclose(): Argument #1 ($stream) must be of type resource, bool given

help me !!!



via Chebli Mohamed

Is it possible to apply condition inside the map function of Laravel?

I wanted to apply some condition in foodOrders. Is it possible to apply condition inside map function that acts as where $foodOrder->foodOrders->where('invoice_id',null)->get();

 public function getTableList(Request $request){
    $skip =$request->skip;
    $limit=$request->limit;
    $totaltable = Table::get()->count();

    $table = Table::skip($skip)->take($limit)->orderBy('id', 'DESC')->get();
    $table->map(function($foodOrder){
        $foodOrder->foodOrders;
    });
}

Below is the output that this query returns. But I only want the data with null invoice_id

{
  "success": true,
  "message": "Lists of Table.",
  "data": [
    {
      "id": 2,
      "table_number": "TN02",
            "food_orders": [
        {
          "id": 16,
          "food_items_id": 1,
          "table_id": 2,
          "invoice_id": null,
          "quantity": 2,
          "price": "2000.00"
         },
        {
          "id": 17,
          "food_items_id": 2,
          "table_id": 2,
          "invoice_id": null,
          "quantity": 3,
          "price": "150.00"
        }
      ]
    },
    {
      "id": 1,
      "table_number": "TN01",
      "created_at": "2020-10-25 10:44:31",
      "updated_at": "2020-10-25 10:44:31",
      "food_orders": [
        {
          "id": 14,
          "food_items_id": 1,
          "table_id": 1,
          "invoice_id": 39,
          "quantity": 1,
          "price": "2000.00"
        }
      ]
    }
  ]
}


via Chebli Mohamed

How to make all column fillable by default of every newly create table in laravel

For now i need to declare in laravel model like that

    protected $fillable = 
    [
        'object_name','attributes','item','cost','status','category','object_id','status','customer_id','provider_id'
       
];

after that, I can insert value in the database. Is there any way that can make all columns of every newly created table fillable so I will need to change it every time.



via Chebli Mohamed

Doctrine/DBAL/Schema/SchemaException - There is no column with name

Laravel version 5.5

Database mysql

use Illuminate\Support\Facades\DB;

class InvoiceController extends Controller
{
    public function GenerateInvoice()
    {
        $data_type = DB::getSchemaBuilder()->getColumnType('order', 'invoice_no');
        dump($data_type);
    }
}

I use Schema Builder to get the column data type of invoice_no from table order but end up with this error.

SchemaException {#472 ▼
  #message: "There is no column with name 'invoice_no' on table 'order'."
  #code: 30
  #file: "/home/server/public_html/order/vendor/doctrine/dbal/lib/Doctrine/DBAL/Schema/SchemaException.php"
  #line: 82
  trace: {▶}
}

I am new to Laravel. Please tell me what should I do!



via Chebli Mohamed

Laravel Multiple @foreach in View

@foreach($data as $var)
    <tr>
        <td style="text-align:center;">
          <input type="checkbox" id="select" class="sub_chk" data-id="" value="" name="selected_values[]"/>
        </td>
        <td></td>
        <td></td>
        <td></td>
        <td> 
          <?php $elements = array(); ?>
          @foreach($var->student_registrars as $category)
            <?php $elements[] = '<a href=" '.route('student-registrars.show', $category->id).' "> '.$category->name.' </a>'; ?>
          @endforeach
          <?php echo implode(',<br>', $elements); ?>
        </td> 
        <td>
          // Second foreach should be here
        </td>
        <td>
          <a href="" class="btn btn-primary btn-sm">Detail</a>
        </td>
    @endforeach 

    // Second foreach
    @foreach($dataGM as $var2)
    <tr>
       <td>
         <?php $elements = array(); ?>
         @foreach($var2->student_registrars as $category)
            <?php $elements[] = '<a href=" '.route('student-registrars.show', $category->id).' "> '.$category->name.' </a>'; ?>
         @endforeach
         <?php echo implode(',<br>', $elements); ?>
       </td>
    </tr>
    @endforeach 

      </tr>

And the result for code above is: enter image description here

I have a little problem related multiple foreach in one view. It's actually just a simple problem but I am stuck here. Any body can solve it? Should I use partial view to do this?



via Chebli Mohamed

vendredi 25 décembre 2020

require(vendor/function.php): Failed to open stream in laravel

I have installed laravel recently via composer but in browser it shows these errors

Warning: require(D:\xampp\htdocs\laravel-8.x\vendor\composer/../symfony/deprecation-contracts/function.php): failed to open stream: No such file or directory in D:\xampp\htdocs\laravel-8.x\vendor\composer\autoload_real.php on line 69

Fatal error: require(): Failed opening required 'D:\xampp\htdocs\laravel-8.x\vendor\composer/../symfony/deprecation-contracts/function.php' (include_path='D:\xampp\php\PEAR') in D:\xampp\htdocs\laravel-8.x\vendor\composer\autoload_real.php on line 69



via Chebli Mohamed

jeudi 24 décembre 2020

Class Barryvdh\DomPDF\Facade not found on Laravel 5.7

Class Barryvdh\DomPDF\Facade not found on Laravel 5.7 on server but there is no issue on this locally. I have try to check if the package folder exist, and it does.

WHat is the solution Dev



via Chebli Mohamed

I want laravel app stop working after a specific date [closed]

I want laravel app stop working after a specific date. Will you please tell me what code is to be inserted and where to be inserted? I am new to laravel.



via Chebli Mohamed

Bitbucket CI Pipelines for deploying Laravel Project on CPanel

First time working on pipelines and CI in general so I may stuff that are wrong. I was trying to build a pipeline to automate deployment for our project on CPanel (Don't ask me, client already had that setup when I joined). Here's what our bitbucket-pipelines.yml file looks like atm:

image: php:7.3-fpm

pipelines:
  branches:
    staging:
      - step:
          caches:
            - composer
          artifacts:
            - storage/**
            - vendor/**
            - public/**
            - .env
          script:
            - apt-get update && apt-get install -qy git curl libmcrypt-dev -y libzip-dev zip
            - yes | pecl install mcrypt-1.0.2
            - docker-php-ext-install zip
            - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer --version=1.10.19
            - composer install
            - sleep 5
            - pipe: atlassian/ftp-deploy:0.3.0 
              variables:
              USER: $FTP_USER
              PASSWORD: $FTP_PASSWORD
              SERVER: $FTP_SERVER
              REMOTE_PATH: $FTP_REMOTE_PATH
          services:
            - docker

It's important to note that the project is built on Laravel 5.5 and I have been urging him to upgrade the version to atleast Laravel 6 since it is the LTS.



via Chebli Mohamed

mercredi 23 décembre 2020

500 Error when setting up swagger in php laravel 5. I provide the correct module reference but it still provides me a 500 Response code

 *
 *    @SWG\Get(
 *      path="/billing/invoice",
 *      tags={"Invoices"},
 *      operationId="getinvoices",
 *      summary="Get all invoices.",
 *      @SWG\Response(
 *          response=200,
 *          description="success",
 *          @SWG\Schema(ref="common/Billing/invoices/Invoice"),
 *      ),
 *      @SWG\Response(
 *          response="default",
 *          description="error",
 *          @SWG\Schema(ref="app/Error"),
 *      ),
 *  )

I'm giving the correct module reference but get 500, 403 and 405 response code.



via Chebli Mohamed

How to display all time slots between two times

I have a Laravel application in which I need to display all time slots between 9AM to 3AM on the basis of 15 minutes interval. the time slots does not contain no date, only times format like (AM and PM)



via Chebli Mohamed

mardi 22 décembre 2020

get value 1 - 2 - 1 - 2 - 1 in for loop php

i am trying to get value like 1-2-1-2-1-2 from for loop

i tried code like this

$k = 1;
        for ($i=$k; $i <= $currentPage ; $i++) {
            $b = $i > $c ? $k : $i;
            $urls = $response['video'][$b - 1];
            echo "$b";
        }

where $currentPage = 5; $c =2; remember when $c = 3; the the value should be 1-2-3-1-2-3 please help me to solve this.



via Chebli Mohamed

I want to get dynamic dependent dropdown using jQuery Ajax in Laravel 5.8 from other microservices?

geeks here is my issue that when i am changing project name it should show some similar URL of that project but it's not showing. but the response is coming when i inspect the value and checking the log it's working but in the view file it's not showing anything. can you please check below files to answer the question.

test.blade.php

@extends('layouts.backend.mainlayout')
@section('title','Seo Keyword View')

@section('content')
<input type="hidden" id="a_u_a_b_t" value="{!! $a_user_api_bearer_token !!}">
<script type="text/javascript">
localStorage.setItem('a_u_a_b_t', $('#a_u_a_b_t').val());
</script>
<!-- hidden Auth email and id for calling in json index -->
<input type="hidden" value="" name="admin_id" id="auth_id" />
<input type="hidden" value="" name="admin_email" id="auth_email" />

<div class="row page-titles">
<div class="col-md-5 align-self-center">
    <h3 class="text-themecolor">Account Admin</h3>
</div>
<div class="col-md-7 align-self-center">
    <!-- <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="javascript:void(0)">System Setting</a></li>
        <li class="breadcrumb-item active">Task</li>
    </ol> -->
</div>
</div>

<div class="container-fluid">

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="table-responsive m-t-40">

                    
                    <div class="row">
                        <div class="col-md-8">
                            <button type="button" name="create_record" id="create_record"
                                class="btn btn-primary ">Add New Keyword</button>
                        </div>
                    </div>

                    <table id="keywordTable" class="table">
                        <thead>

                        </thead>
                        <tbody>

                        </tbody>

                    </table>

                    <div id="formModal" class="modal fade" role="dialog">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header bg-primary">
                                    <h5 class="modal-title text-white" id="exampleModalLabel">Add New Keyword</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <!-- Success Message after submit -->
                                    <span id="form_result" aria-hidden="true"></span>
                                    <!-- Error Message after form not submit -->
                                   
                                    <form method="post" id="sample_form" class="form-horizontal"
                                        enctype="multipart/form-data">
                                        @csrf

                                        <div class="form-group" id="name_form">
                                            <label class="control-label col-md-4">Project Name</label>
                                            <div class="col-md-8">
                                                <select name="project_name" id="project_name" class="w-100 p-2">
                                                    <option value="default" class="form-control text-dark">Select Project </option>
                                                    @foreach(App\Http\Controllers\Api\ProjectApiController::getvalueall() as $project)

                                                    <option name="" value=""></option>
                                                    @endforeach
                                                </select>

                                            </div>
                                        </div>

                                        <div class="form-group" id="name_form">
                                            <label class="control-label col-md-4">URL</label>
                                            <div class="col-md-8">
                                                <select name="url" id="url" class="w-100 p-2">
                                                <option value="" class="form-controll text-dark">Select URL </option>
                                                </select>

                                            </div>
                                        </div>

                                        <div class="form-group" id="name_form">
                                            <label class="control-label col-md-4">Keyword</label>
                                            <div class="col-md-8">
                                                <input type="text" name="keyword" id="keyword" class="form-control" />
                                                <!-- <span id="username" class="text-danger"></span> -->
                                            </div>
                                        </div>

                                        
                                        <!-- Sending admin_id and admin_email in hidden input box -->
                                        <input type="hidden" value="" name="admin_id"
                                            id="admin_id" />
                                        <input type="hidden" value="" id="admin_email" name="admin_email" />
                                        <input type="hidden" value="" id="url_id" name="url_id" />
                                        <input type="hidden" value="" id="project_id" name="project_id">
                                </div>

                                <!-- <br /> -->
                                <div class="form-group text-center">
                                    <input type="hidden" name="action" id="action" />
                                    <input type="hidden" name="hidden_id" id="hidden_id" />
                                    <input type="submit" name="action_button" id="action_button"
                                        class="btn btn-warning float-center" value="Add" />
                                </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="confirmModal" class="modal fade" role="dialog">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header bg-light">
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                <br>
                                <span class="modal-title_delete">Confirmation</span>
                            </div>
                            <div class="modal-body">
                                <h4 class="text-center" style="margin:0; color:red;">Are you sure you want to remove this URL?</h4>
                            </div>
                            <div class="modal-footer">
                                <button type="button" name="ok_button" id="ok_button"
                                    class="btn btn-danger">OK</button>
                                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            </div>
                        </div>
                    </div>
                </div>

                

            </div>
        </div>
    </div>
</div>
</div>
</div>
@endsection
@push('js')

<script>
$(document).ready(function() {
// onchange function for url get via project name
$('#project_name').on('change',function(){
    console.log('project name change');
    if(this.value !='default'){
        ajaxCall();
    } else{
        $('#url').empty();
        $('#url').append('<option> Select URL</option>');
    }
    function ajaxCall() {
    console.log('in ajaxCall');
    var project_id = $("#project_name option:selected").attr("name");
    console.log(project_id);
    $.ajax({
            type: "GET",
            url: '/'+project_id,
            data: {},
            headers: {
                "Authorization": "Bearer " + localStorage.getItem('a_u_a_b_t')
            },
            success: function(response) {
            $('#url').empty();
            $('#url').append('<option> Select Url </option>');
            console.log(response);
            console.log(response.data);
            console.log(response.success);
            if(response.success){

                $.each(response.data, function(i, link) { 
                    $('#url').append('<option name="'+link.id+'" value="' + link.url + '">' + link.url + '</option>');
                });
            }
            },
            error: function(errorResponse) {
            console.log(errorResponse);
            }
        });
    }
});
// onchange function for url get via project name  
</script>
@endpush

TestApiController.php ( controller that i am getting link)

        <?php

    namespace App\Http\Controllers\Api;

    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use GuzzleHttp\Client as Client;
    use Illuminate\Support\Facades\Log;
    use Config;
    use Validator;
    use Auth;

    class LinkApiController extends Controller
    {
        //generating access token as static for getvalueall function
        private static function getAddUrlAccessToken()
        {
            Log::info('In LinkApiController->getAddUrlAccessToken()');
            try{
                $http = new Client(); //GuzzleHttp\Client
                $response = $http->post(
                    Config::get('app.SD_ADD_URLS_MS_BASE_URL') . Config::get('app.SD_ADD_URLS_MS_OAUTH_TOKEN_URL'),
                    [
                        'form_params' => [
                            'grant_type' => Config::get('app.SD_ADD_URLS_MS_GRAND_TYPE'),
                            'client_id' => Config::get('app.SD_ADD_URLS_MS_CLIENT_ID'),
                            'client_secret' => Config::get('app.SD_ADD_URLS_MS_SECRET'),
                            'redirect_uri' => '',
                        ],
                    ]
                );
                $array = $response->getBody()->getContents();
                $json = json_decode($array, true);
                $collection = collect($json);
                $access_token = $collection->get('access_token');
                Log::info('Got the token!');
                return $access_token;
            } catch(RequestException $e){
                Log::info('There is some exception in LinkApiController->getAddUrlAccessToken()');
                return $e->getResponse()->getStatusCode() . ': ' . $e->getMessage();
            }
        }

        //get project function
        public function getUrl($id)
        {
            try{
                Log::info('SD_ADD_URLS_MS_ALL_URL: ' . Config::get('app.SD_ADD_URLS_MS_ALL_URL'));
                $access_token = $this->getAddUrlAccessToken();
                $url = ''
                .Config::get('app.SD_ADD_URLS_MS_BASE_URL')
                .Config::get('app.SD_ADD_URLS_MS_ALL_URL')
                .'/'
                .$id;
                Log::info('Got the access token from LinkApiController::getAddUrlAccessToken(). Now fetching URLs!');
                Log::info('ALL Addurls URL: ' . $url);
                $guzzleClient = new Client(); //GuzzleHttp\Client
                $params = [
                    'headers' =>[
                        'Accept' => 'application/json',
                        'Authorization' => 'Bearer ' .$access_token
                    ]
                ];
                $response = $guzzleClient->request('GET', $url, $params);
                Log::info('Got the Response from SD ADDurls MS');
                Log::info('Store hone ke baad index page par value aa raha hai !');
                $json = json_decode($response->getBody()->getContents(), true);
                Log::info('Number of objects in response: ' . count($json['data']));
                return $json;
            } catch(\Exception $e){
                Log::info('There was some exception in LinkApiController->getProject()');
                return $e->getResponse()->getStatusCode(). ':' . $e->getMessage();
            }
        }

        // onchange function via project_id
    public static function getProjectid($project_id)
        {
            Log::info('in LinkApicontroller->getProjectid(sadfasdfasdfasdfasdf)'.$project_id);
            try{
                $access_token = LinkApiController::getAddUrlAccessToken();
                Log::info('Got the access token from LinkApiController->getAddUrlAccessToken(). Now fetching urls!');
                $http = new Client(); //GuzzleHttp\Client
                $response = $http->get(
                    Config::get('app.SD_ADD_URLS_MS_BASE_URL') . Config::get('app.SD_ADD_URLS_MS_GETPROJECT_URL')
                    .'/'
                    .$project_id,
                    [
                        'headers' => [
                            'Accept'     => 'application/json',
                            'Authorization' => 'Bearer ' . $access_token
                        ]
                    ]
                );
                Log::info('Got the response from URL!');
                $json = json_decode($response->getBody()->getContents(), true);
                Log::info('Number of objects in response: ' . count($json['data']));
                return $json['data'];
            } catch(\Exception $e){
                Log::info('ye aa gye ham error part me');
                return $e->getResponse()->getStatusCode() . ': ' . $e->getMessage();
            }
        }
    }

api.php (routes)

<?php

    use Illuminate\Http\Request;


    Route::group(['prefix'=>'v1/j', 'middleware' => 'auth', 'middleware' => 'client_credentials'], function(){
            
            // web url api route
            Route::get('addurl/index/{id}','Api\LinkApiController@getUrl')->name('addurl.index');
            Route::post('addurl/store/{project_name}','Api\LinkApiController@storeUrl')->name('addurl.store');
            Route::get('addurl/edit/{id}','Api\LinkApiController@editUrl')->name('addurl.edit');
            Route::post('addurl/update','Api\LinkApiController@updateUrl')->name('addurl.update');
            Route::get('addurl/destroy/{id}','Api\LinkApiController@destroyUrl')->name('addurl.delete');
            Route::get('addurl/getProject/{project_id}','Api\LinkApiController@getProjectid')->name('addurl.getProject');

    });

google chrome inspect result enter image description here



via Chebli Mohamed

vue devserver proxy not working, no CORS error but getting xhr response as a doc file

I have configured devserver proxy with my staging server url of my site, and made axios request using client server url. But the ajax request is returning just a html file, no response getting from server.

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS
Access-Control-Allow-Headers: token, Content-Type


axios

Axios({
            method: 'get',
            url: 'http://10.1.3.159/v3/se/oauth/getAccessToken.php',
            data: {}
          }).then(function (response) {
            console.log(response);
          });

vue.config.js

module.exports = {
    devServer: {
      proxy: 'server url'
    }
  }

These also added in php file headerxhr response



via Chebli Mohamed

Laravel response time very slow

My Laravel app is really very slow, it takes more than 3 seconds to get a response, sometimes less. even if I tried to call a route with an empty controller the time to get the response is 3 seconds. My controller:

function index(Request $request){
    echo "hi";
    exit;
}

response time



via Chebli Mohamed

Google Login using Socialite in laravel and Vue.js

I'm using vue-social auth package for google login

Link: https://www.npmjs.com/package/vue-social-auth

when i login i'm getting following screen:

enter image description here

Here is the way i'm using it:

app.js

import VueSocialauth from 'vue-social-auth'
Vue.use(VueSocialauth, {
 
  providers: {
    google: {
      clientId: 'XXXXXXXXXX.apps.googleusercontent.com',
      redirectUri: 'callback/google' // Your client app URL
    }
  }
})

View.vue.js

 <button @click="AuthProvider('google')">auth Google</button>

method:

 AuthProvider(provider) {
 
              var self = this
 
              this.$auth.authenticate(provider).then(response =>{
 
                self.SocialLogin(provider,response)
 
                }).catch(err => {
                    console.log({err:err})
                })
 
            },
 
            SocialLogin(provider,response){
 
                axios.post('/sociallogin/'+provider,response).then(response => {
 
                    console.log(response.data)
 
                }).catch(err => {
                    console.log({err:err})
                })
            },

Web-routes.js

{
  path: '/auth/:provider/callback',
  component: {
    template: '<div class="auth-component"></div>'
  }
},

api.php

Route::post('sociallogin/{provider}', 'Auth\AuthController@SocialSignup');
Route::get('auth/{provider}/callback', 'OutController@index')->where('provider', '.*');

env:

GOOGLE_ID=XXXX
GOOGLE_SECRET=XXXXX
GOOGLE_URL=https://localhost:8000/callback/google

Auth Controller :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Socialite;

class AuthController extends Controller
{
 

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function SocialSignup($provider)
    {
        // Socialite will pick response data automatic 
        $user = Socialite::driver($provider)->stateless()->user();
 
        return response()->json($user);
    }
}


via Chebli Mohamed

Validate Date time through laravel Validation

I'm trying to validate date time through Laravel Validation like this:

$this->validate($request,[
        'DateTime'=> 'required|after_or_equal:' . date('Y-m-d H:i:s'),
]);

I want to restrict the user if they enter date time greater than current date time but in my case date is being validated but i have to validate time also. Format of date time is 2020-12-23 17:40:00



via Chebli Mohamed

how to show a graph in each row in usgin googlechart(or chart.js etc)

I've been trying to display a graph in each row inside one page using Google chart but I have no idea how to do that.

I get data from database when making a graph. putting aside if this code below is right, here's my image.

@foreach ($titles as $title)


<?php $getData = App\Graph::getNumber($title->id)?>

<div id="graph_bar" ></div>     ←graph


@endforeach

<script type="text/javascript">

    var barA= @json($getData->numberA);
    var barB = @json($getData->numberB);
    var barC= @json($getData->numberC);


    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawchart);

    function drawchart() {
        var data = google.visualization.arrayToDataTable([
            ['', '', '', ''],
            ['', barA, barB , barC],
        ]);
        var options = {
            isStacked: true,
            isStacked:'percent',
            legend: {position: 'none'},
            series: {
                0:{color:'red'},
                1:{color:'blue'},
                2:{color:'grey'},
            }
        };
        var chart = new google.visualization.BarChart(document.getElementById('graph_bar'));
        chart.draw(data, options);
    }
    $(window).resize(function(){
        drawchart();

    });

</script>

1.Is it possible to do that(display a graph in each row) in the first place? 2.I'd like to get ID from HTML at javascript.

if anyone knows anything about this, I'd appreciate if if you would help me out. thank you.

enter image description here



via Chebli Mohamed

Expected response code 250 but got code "550", with message "550 Bad HELO - Host impersonating domain name [mydomain.com]

I can send mail from local without any errors but dont send email from VPS.

Expected response code 250 but got code "550", with message "550 Bad HELO - Host impersonating domain name [golrizpaper.com] "

.env file:

MAIL_DRIVER=smtp
MAIL_HOST=mailservice4.irandns.com
MAIL_PORT=25
MAIL_USERNAME=info@golrizpaper.com
MAIL_PASSWORD='******'
MAIL_ENCRYPTION=null

Any idea how to solve this?



via Chebli Mohamed

Initialization model inside custom request

There is a model event. I wanna update it. The custom request is used for validation, but have several problems. Every event has two user's relations - client and executor. As an example, I wanna change the event time. That time should be after now and should be free in the executor. The first validation rule is simple, but for the second I have to initialize the event model in custom request, retrieve the executor and his free time. Of course, I can do something like that

$event = Event::find($id);
$executor = $event->executor;

But is it good way to process validation? Do not think so. What the better way to validate that data?



via Chebli Mohamed

Laravel 5.4 - How to count the absences of the employee from the table

How can I count the number of absences of the employee? can someone help me with this, please? thank you very much!

For example, i want to count the total absences of the bio_emp = 9.

This is the snippet of the table



via Chebli Mohamed

Laravel is not reading environmental variables on AWS Lambda

Laravel deployment on AWS Lambda using bref/serverless.

Error message:

production.ERROR: SQLSTATE[HY000] [2002] Connection refused (SQL:...

This is a database connection error but I think this is because Laravel is not reading environmental variables.

This:

Route::get('/', function () {
    return env('APP_NAME');
});

returns nothing although APP_NAME is set and works properly on a local computer.

I'm not sure where the .env file is located on AWS Lambda and how to check it (other than the test above) if it is properly transferred to AWS Lambda.



via Chebli Mohamed

lundi 21 décembre 2020

add another array data in array php

hello i am trying to add another array data to an array, i have array like this,

    array:4 [▼
  "data" => array:19 [▼
    0 => array:2 [▼
      0 => array:1 [▼
        "filename" => "a"
      ]
      1 => array:1 [▼
        "filename" => "b"
      ]
    ]
    1 => array:2 [▼
      0 => array:1 [▼
        "filename" => "c"
      ]
      1 => array:1 [▼
        "filename" => "d"
      ]
    ]
    2 => array:2 [▼
      0 => array:1 [▼
        "filename" => "e"
      ]
      1 => array:1 [▼
        "filename" => "f"
      ]
    ]
    
  ]
  "video" => array:2 [▼
    0 => array:1 [▼
      "url" => "x"
    ]
    1 => array:1 [▼
      "url" => "y"
    ]
  ]
  
]

i want array like this

array:4 [▼
  "data" => array:19 [▼
    0 => array:2 [▼
      0 => array:1 [▼
        "filename" => "a",
      ]
      1 => array:1 [▼
        "filename" => "b"
      ],
      2 => array:1 [▼
        "url" => "x"
      ]
    ]
    1 => array:2 [▼
      0 => array:1 [▼
        "filename" => "c"
      ]
      1 => array:1 [▼
        "filename" => "d"
      ],
      2 => array:1 [▼
        "url" => "y"
      ]
    ]
    2 => array:2 [▼
      0 => array:1 [▼
        "filename" => "e"
      ]
      1 => array:1 [▼
        "filename" => "f"
      ],
      2 => array:1 [▼
        "url" => "x"
      ]
    ] 
  ]
]

i am trying to add array but still no result, is any way to solve this issue in php. please suggest me.

"video" data have only 2 , it will repeated , 1-2-3-1-2-3 on that array.

please suggest me how can i solve this



via Chebli Mohamed

[Vue warn]: Error in v-on handler: "Error: Request handler instance not found" Vue.js

I'm using vue-social auth package for google login

Link: https://www.npmjs.com/package/vue-social-auth

As i press the login button i'm getting:

[Vue warn]: Error in v-on handler: "Error: Request handler instance not found"

Here is the way i'm using it:

app.js

import VueSocialauth from 'vue-social-auth'
Vue.use(VueSocialauth, {
 
  providers: {
    google: {
      clientId: 'XXXXXXXXXX.apps.googleusercontent.com',
      redirectUri: 'auth/google/callback' // Your client app URL
    }
  }
})

View.vue.js

 <button @click="AuthProvider('google')">auth Google</button>

method:

 AuthProvider(provider) {
 
              var self = this
 
              this.$auth.authenticate(provider).then(response =>{
 
                self.SocialLogin(provider,response)
 
                }).catch(err => {
                    console.log({err:err})
                })
 
            },
 
            SocialLogin(provider,response){
 
                axios.post('/sociallogin/'+provider,response).then(response => {
 
                    console.log(response.data)
 
                }).catch(err => {
                    console.log({err:err})
                })
            },

Web-routes.js

{
  path: '/auth/:provider/callback',
  component: {
    template: '<div class="auth-component"></div>'
  }
},

api.php

Route::post('sociallogin/{provider}', 'Auth\AuthController@SocialSignup');
Route::get('auth/{provider}/callback', 'OutController@index')->where('provider', '.*');

env:

GOOGLE_ID=XXXX
GOOGLE_SECRET=XXXXX
GOOGLE_URL=https://localhost:8000/auth/google/callback

Auth Controller :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Socialite;

class AuthController extends Controller
{
 

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function SocialSignup($provider)
    {
        // Socialite will pick response data automatic 
        $user = Socialite::driver($provider)->stateless()->user();
 
        return response()->json($user);
    }
}


via Chebli Mohamed

laravel 5.3 ...Como puedo solucionar este error ErrorException in HomeController.php line 45: compact(): Undefined variable: my_denuncias [closed]

mi homecontroller donde se hace mencion a lo que se va ver en la vista de cada nivel de cliente soporte y administrador solo que no estoy pudiendo pasar por el problema que se ve de ErrorException in HomeController.php line 45:compact(): Undefined variable: my_denuncias tengo en mi repositorio el trabajo para ver mas de cerca y si alguno puede darme una salida se lo agradeceria


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;
use App\Denuncia;
use App\ProjectUser;

class HomeController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $user = auth()->user();
        $selected_project_id = $user->selected_project_id;

        if ($selected_project_id) {

            if ($user->is_support) {
                $my_denuncias = Denuncia::where('project_id', $selected_project_id)->where('support_id', $user->id)->get();

                $projectUser = ProjectUser::where('project_id', $selected_project_id)->where('user_id', $user->id)->first();

                if ($projectUser) {
                    $pending_denuncias = Denuncia::where('support_id', null)->where('level_id', $projectUser->level_id)->get();
                } else {
                    $pending_denuncias = collect(); // empty when no project associated
                }
            }

            $denuncias_by_me = Denuncia::where('client_id', $user->id)
                                        ->where('project_id', $selected_project_id)->get();
        } else {
            $my_denuncias = [];
            $pending_denuncias = [];
            $denuncias_by_me = [];
        }

        return view('home')->with(compact('my_denuncias', 'pending_denuncias', 'denuncias_by_me'));
    }
         
    public function selectProject($id)
    {
        // Validar que el usuario esté asociado con el proyecto
        $user = auth()->user();
        $user->selected_project_id = $id;
        $user->save();

        return back();
    }

}

mi home.blade donde tengo las vistas


@section('content')
<div class="panel panel-primary">
    <div class="panel-heading">Dashboard</div>

    <div class="panel-body">
        
        @if (auth()->user()->is_support)
        <div class="panel panel-success">
            <div class="panel-heading">
                <h3 class="panel-title">Denuncias asignadas a mí</h3>
            </div>
            <div class="panel-body">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Código</th>
                            <th>Categoría</th>
                            <th>Severidad</th>
                            <th>Estado</th>
                            <th>Fecha creación</th>
                            <th>Título</th>
                        </tr>
                    </thead>
                    <tbody id="dashboard_my_denuncias">
                        @foreach ($my_denuncias as $denuncia)
                            <tr>
                                <td>
                                    <a href="/ver/">
                                        
                                    </a>
                                </td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>

        <div class="panel panel-success">
            <div class="panel-heading">
                <h3 class="panel-title">Denuncias sin asignar</h3>
            </div>
            <div class="panel-body">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Código</th>
                            <th>Categoría</th>
                            <th>Severidad</th>
                            <th>Estado</th>
                            <th>Fecha creación</th>
                            <th>Título</th>
                            <th>Opción</th>
                        </tr>
                    </thead>
                    <tbody id="dashboard_pending_denuncias">
                        @foreach ($pending_denuncias as $denuncia)
                            <tr>
                                <td>
                                    <a href="/ver/">
                                        
                                    </a>
                                </td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td>
                                    <a href="" class="btn btn-primary btn-sm">
                                        Atender
                                    </a>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
        @endif

        <div class="panel panel-success">
            <div class="panel-heading">
                <h3 class="panel-title">Denuncias reportadas por mí</h3>
            </div>
            <div class="panel-body">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Código</th>
                            <th>Categoría</th>
                            <th>Severidad</th>
                            <th>Estado</th>
                            <th>Fecha creación</th>
                            <th>Título</th>
                            <th>Responsable</th>
                        </tr>
                    </thead>
                    <tbody id="dashboard_by_me">
                        @foreach ($denuncias_by_me as $denuncia)
                            <tr>
                                <td>
                                    <a href="/ver/">
                                        
                                    </a>
                                </td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td>
                                    
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>
@endsection


via Chebli Mohamed

Laravel loop undefined variable in loop [closed]

I am trying to redirect users to a page where they can choose facilities they belong to. Super admins can view all facilities, this works perfectly. Organization admins should only view facilities they belong to. Unfortunately, this part fails, and i get an error Undefined variable: facilities despite the fact that facilities is defined, and if i run the quary, the correct result is obtained. The third part of the loop gets executed by default. Any tips/advice on what i am doing wrong in my loop will be appreciated.

group = $user->groups;            

        if($group[0]->name === 'Super Administrator') {

            $facilities = Facility::all();

        } else if($group[0]->name === 'Organization Administrator') {
        
            $org_id = $group[0]->organization_id;
            
            $facilities = Facility::where('organization_id', '=', $org_id)->get();

        } else if( (!empty($group[0]->facility)) && $group[0]->facility->count() == 1) {

            $url = $scheme . $facility->first()['subdomain'] . '.' . env('APP_DOMAIN', 'localhost.loc');

            return redirect()->away($url);

        } 

        $facilities = $facilities->unique();

The value of $group is :

  {
    "uuid": "924bd268-f97e-4570-9122-b30a6b23cf8a",
    "name": "Test Organization Admin",
    "alias": "test-organization-admin",
    "description": "Organization Administrator",
    "facility_id": 2,
    "status": 1,
    "facility": {
      "uuid": "924bcf28-63a8-4541-b54f-e480e3a7aae0",
      "name": "Test Facility",
      "organization_id": 4,
      "subdomain": "testfacility",
      "schema_name": "testfacility_2020_12_21_122917",
      "status": 1,
      "logoWeb": null,
      "logoWebMenu": null
    }
  }
]                                                                                                    ```


via Chebli Mohamed

dimanche 20 décembre 2020

How to check each row with foreach loop using Laravel

Lets start from a scenario. In my project there are products coming from product table and users as requester are able to request for the product but requester can request a product only one time If requester already requested for the product it will redirect back with error message otherwise the product will add to his request list.

For that i make request table having requester id and product id as foreign key. Here is request controller.The condition only check the first row of the table and not working properly.

Guide me what i am doing wrong??

 public function show($id)
{
    $request_item = new request_item; 
    $loginuser=Auth::user()->id;
    $checkif=DB::select('SELECT * FROM `request`');
    $requester_ID = DB::table('requester')->where('user_id', $loginuser)->value('id');

       foreach ($checkif as $db) 
        {

           if ($requester_ID==$db->requester_id && $id==$db->product_id) {
               
                return redirect()->back()->with('error_code', 5);
            }
            else
            {
                  $requester_ID = DB::table('requester')->where('user_id', $loginuser)->value('id');
                  $request_item->requester_id = $requester_ID;
                  $request_item->product_id = $id;
                  $request_item->save();
                return redirect('myRequest');
                
            }
        }     
        return "Something went wrong! Please try gain later";

      
     
     //return view('myRequest');
}


via Chebli Mohamed

Laravel returning IP address for assets instead of domain

I'm trying to set up a local Laravel Homestead (5.3) environment for my API. I want to be able to hit the API locally through my Android app.

I've set everything up, including getting the Android app to trust the server's certificate, but now I'm getting the following issue:

The app trusts my server's domain (in my case, homestead.test). The problem is, my server is returning all assets with the IP address of the server, which is 192.168.10.10, so all assets return in the form of:

https://192.168.10.10/storage/img/posts/6/thumbnails/1.jpeg

For whatever reason, the Android app doesn't trust this IP as I guess I don't have the certificate for it set up. Instead, I need it to return with the domain, homestead.test, so it looks like:

https://homestead.test/storage/img/posts/6/thumbnails/1.jpeg

In my hosts file (Windows), I have this already:

192.168.10.10  homestead.test

How can I make this change? I've tried changing APP_URL to https://homestead.test in the .env file, but that doesn't seem to have changed anything.

What am I missing?



via Chebli Mohamed

How to add offset after sortBy in laravel

How can I add offset after using sortBy in laravel? Please see my code below.

Controller

$order_type = ($dir == 'asc') ? 'sortBy' : 'sortByDesc';

$inventories = $inventories->get()->$order_type(function($inventory) {
   $item_status = [
     '0'  => 'I',
     '1'  => 'D',
     '2' => 'HI',
     '3' => 'HR',
     '4' => 'A',
     '5' => 'DS'
   ];

   return $item_status[$inventory->receive_item->inspection_status];
});

$inventories = $inventories->offset($start)->limit($limit);

Error I get

BadMethodCallException in Macroable.php line 74: Method offset does not exist.



via Chebli Mohamed

Cannot install laravel/socialite package

I'm trying to install Socialite Package getting this error :

Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 4096 bytes) in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSetGenerator.php on line 126

I have change changed memory_limit in my php.ini file but facing same issue, any help will be highly appreciated.



via Chebli Mohamed

How to add Laravel scheduled tasks as cronjob on AWS Elastic Beanstalk?

I tried many different solutions that I found but none of them worked! Here are the links that I already tried without any luck:

  1. First
  2. Second
  3. Third
  4. Forth
  5. ..

I need to regularly truncate a table in DB which is used for caching purposes (PHP artisan truncate:cached_stores).

According to the documentation, I created mycron.config in .ebextensions folder in the root directory of my Elastic Beanstalk laravel app with many different contents based on the solutions I found such as the followings:

    files:
    "/etc/cron.d/schedule_run":
        mode: "000644"
        owner: root
        group: root
        content: |
            * * * * * root php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
commands:
    remove_old_cron:
        command: "rm -f /etc/cron.d/*.bak"

Also this:

    files:
    "/etc/cron.d/mycron":
        mode: "000644"
        owner: root
        group: root
        content: |
            * * * * * root /usr/local/bin/myscript.sh

    "/usr/local/bin/myscript.sh":
        mode: "000755"
        owner: root
        group: root
        content: |
           * * * * * root . /opt/elasticbeanstalk/support/envvars && /usr/bin/php /var/www/html/artisan schedule:run 1>> /dev/null 2>&1

commands:
    remove_old_cron:
        command: "rm -f /etc/cron.d/*.bak"

I appreciate it if you could help me what am I missing?



via Chebli Mohamed

how insert data and show data by location Laravel using the Laravel and jQuery

how insert data and show data by location Laravel using the Laravel and jQuery

how insert data and show data by location Laravel using the Laravel and jQuery



via Chebli Mohamed

samedi 19 décembre 2020

Undefined Variable Request in Laravel 5

I am having issues it says Request is undefined same goes for DB.

public function edit(Request $request,$id) {
        $name = $request->input('stud_name');
        DB::update('update student set name = ? where id = ?',[$name,$id]);
        echo "Record updated successfully.<br/>";
        echo '<a href = "/edit-records">Click Here</a> to go back.';
     }


via Chebli Mohamed

Loop through Categories and its Products in PHP Laravel

I have to create an array with the categories array and its related products i'm fetching category with all related products using this query

  $categoryData= Category::with('product')->get();

Data is beign fetched properly, using this loop to get data in the format given below:

 foreach($categoryData as $row){
            $categoriesData[] = [
                'id' => $row->id,
                'title' =>  $row->title,
            ];
          foreach($row->product as $rowproduct){
            $categoriesData['product_details'][] = [
             'product_name' => $rowproduct->name,
             'product_price' => $rowproduct->price
      ];
}
}

Format (It should be something like this) :

{
    "categoriesData": {
        "0": {
            "id": 1,
            "category_name" : "Name 1",
        "product_details": [
            {
                "id": 1,
                "product_name": Product Name,
            },
        ],
        "1": {
            "id": 2,
            ""category_name" ": "Name 2",
            "product_details": [
            {
                "id": 1,
                "product_name": product name,
            },
        },
      
   

but through present loop all product is getting saved in one array. It is not saving inside category.

Any help is highly appreciated



via Chebli Mohamed

vendredi 18 décembre 2020

Laravel pagination showing duplicate records

I am using laravel pagination in the query i am using order by with a column and the multiple rows has the same value for this column so when i change the page via pagination some records repeats. Is there any solution to fix this problem.



via Chebli Mohamed

not working in laravel

I am displaying images in laravel blade with this method

<img class="docu-image" src="" alt="Second slide">

on localhost it is working fine but on live server it isn't working

When add public in url by inspect element then it shows image .

What could be the reason



via Chebli Mohamed

"Interface 'Illuminate\Contracts\Auth\Access\Gate' not found" I can't figure out what is wrong here

So basically I'm building an application using Laravel 5.6, under php 7.1.2, and I got this error:

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN) Interface 'Illuminate\Contracts\Auth\Access\Gate' not found

So obviously I checked the incriminated file and stumbled on this piece of code which I don't understand in Illuminate\Contracts\Auth\Access\Gate.php

use Illuminate\Contracts\Auth\Access\Gate as GateContract;

class Gate implements GateContract {

I don't understand why the file is using itself, and why the Gate class is trying to implement itself despite the fact that it's defined as a class and not an interface. Thus I don't understand how I am supposed to solve this mess.

If anyone could shed some light on this I would be grateful.



via Chebli Mohamed

Aws db name is displaying (-) .what should i give in my laravel project?

I have created db on aws rds all the other infor mation is available but db_name is displaying ``(-)``` I dont know how i should give it in my laravel env file

env

DB_DATABASE=-

enter image description here



via Chebli Mohamed

Laravel many to many relationship need to execute a query to get users list where role_id = 5

I have the below tables

  1. users : id | name
  2. projects : id | name
  3. user_project : id | user_id | project_id

My Models contains

  1. User.php

    public function projects() { return $this->belongsToMany(Project::class); }

  2. Project.php

    public function users() { return $this->belongsToMany(User::class); }

In my controller file, I want to get a list of users using the User model whose role_id is 5.

Something like below

User::query()->roles(5);

*Help will be appreciated



via Chebli Mohamed

Running commands from Controller async

There is a migration task. User uploads file to the server, then it should be saved and migration command should be run async. The first path works well, there is an issue with the second part. I've tried to put all code to console command and run it with

Artisan::call('user:migrate', ['user_id' => $userId]);

or

Artisan::queue('user:migrate', ['user_id' => $userId]);

the script works, but not async, controller's function waits for the end. Also I've tried to create a Job and call it via:

$this->dispatch(new UserMigration($user));

and had the same result, script works but not async. Please help to realize how queues work and that approach is better for my task. I've not created any queue migrations and configuration, because need this step just async calling.



via Chebli Mohamed