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;

    }



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

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



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

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



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

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

}



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

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');

    }
    ```


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

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.



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

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?



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

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



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

mardi 29 décembre 2020

Laravel: {closure}() must be an instance of Illuminate\Mail\Message

I'm trying to make a custom forgot password but when I'm trying to send the email it gives this error

Argument 1 passed to App\Http\Controllers\Auth\PasswordController::App\Http\Controllers\Auth\{closure}() must be an instance of Illuminate\Mail\Message, instance of App\Models\User given, called in D:\laragon\www\laravel8\vendor\laravel\framework\src\Illuminate\Auth\Passwords\PasswordBroker.php

I've tried with these two methods

        $response = Password::sendResetLink($request->only('email'), function (Message $message) {
        
            $message->from('support@test.com', Config::get('APP_NAME'));
            $message->subject($this->getEmailSubject());
            });

Or

public function postEmail(Request $request){
          $response = $this->broker()->sendResetLink(
            $request->only('email'),
            function (Message $message) {
                $message->from('support@test.com', Config::get('APP_NAME'));
                $message->subject($this->getEmailSubject());
            }
        );
}
public function broker()
    {
            return \Illuminate\Support\Facades\Password::broker();
     }

Idk how to make the anonimous function become an instance of message

More info

Trying to update from laravel 5.1 to 8



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

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>


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

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



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

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


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

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?

Thank you for any suggestion and comments.



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

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

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



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

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



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

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;



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

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



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

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



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

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>


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

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


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

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.



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

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


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

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



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

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


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

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.



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

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!



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

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?



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

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



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

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



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

I want laravel app stop working after a specific date

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.



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

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.



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

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.



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

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)



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

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

$c = count($response['video']); // 2
$currentPage  = 2;
$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;

when $c = 3; the value should be 1-2-3-1-2-3 when i echo $b or dd($b) out of loop i will got 12111 but i need answer 121212 please help me to solve this.



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

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



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

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



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

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



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

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


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

Laravel display object from foreach

i want to echo ouptut from controller When i dump this object i get all data like i want, but how to echo that I want to display this data like this

Here is my controller

$pkm = DB::table('magacin_pkms')->select(
    'magacin_pkms.status',
    'magacin_pkms.izdao_to',
    'users.name as izdaoFirstName',
    'users.lastname as izdaoLastName',
    'magacin_pkms.vrednost',
    'magacin_pkms.izdao_by',
    'magacin_pkms.izdao_at'
)
    ->join('users', 'id_user', 'izdao_to')
    ->where('magacin_pkms.status', 2)
    ->orderBy('izdao_to')
    ->get();

$driverIDs = array_unique($pkm->pluck('izdao_to')->toArray());

foreach ($driverIDs as $id) {
    $obj  = new StdClass;
    $name = $pkm->where('izdao_to', $id)->first()->izdaoFirstName;
    $lastname = $pkm->where('izdao_to', $id)->first()->izdaoLastName;
    $cnt = $pkm->where('izdao_to', $id)->count();
    $total = $pkm->where('izdao_to', $id)->sum('vrednost');
    $admin = $pkm->where('izdao_to', $id)->first()->izdao_by;
    $izdato = $pkm->where('izdao_to', $id)->first()->izdao_at;
  
    $obj->name = $name;
    $obj->lastname = $lastname;
    $obj->cnt = $cnt;
    $obj->total = $total;
    $obj->admin = $admin;
    $obj->izdato = $izdato;
    dump($obj);
}

this is my view

@foreach ($obj as $items)
    <tr>
        <td></td>
        <td> </td>
        <td></td>
        <td></td>
        <td> $</td>
        <td></td>
        <td></td>
@endforeach


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

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



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

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



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

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?



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

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?



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

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? This is the snippet of the table



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

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.



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

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



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

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


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

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


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

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


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

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


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

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?



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

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.



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

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.



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

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?



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