lundi 31 décembre 2018

after i change composer.jason file Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

after i change composer.jason file bellow errors are displayed.how can i fix it? Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

"require": {
    "php": "^7.1.3",
    "consoletvs/charts": "5.*",
    "fideloper/proxy": "^4.0",
    "genealabs/laravel-caffeine": "^0.7.1",
    "laravel/framework": "5.7.*",
    "laravel/tinker": "^1.0",
    "laravelcollective/html": "5.7.*" //I changed this line
},

this errors came with changes



via Chebli Mohamed

Setting up Chrome Logger Using Laravel Isn't Working

I'm trying to set up Chrome Logger to use alongside Laravel as detailed in "Easy Laravel 5", however following the instructions throws errors, and I'm new to Laravel (and not very experienced in PHP), so I'm not sure how to resolve them. We are directed to add a piece of code to the bootstrap/app.php file to use the chrome logger in the book.

The following is a screenshot of the error screen: Error Screen

The following is the site without the code excerpt:
Default Screen

I tried requiring the chrome.php file using require_once() in the app.php file, but the error still persists. Removing the code excerpt produces the default screen.

This is the code excerpt:
ChromePHP include code

if ($app->environment('local')) 
{
    $app->configureMonologUsing(function($monolog)
    {
          $monolog->pushHandler(new  \Monolog\Handler\ChromePHPHandler());
    });
}

I expected to be able to use the chrome logger, but instead receive the aforementioned error screen.



via Chebli Mohamed

How to get Font Sub Family in English language with PhenX/php-font-lib?

I want to get some informations in english language of font file with "PhenX/php-font-lib", but when parse font file information it return another language other than english. How to get english name of these fields ?

Example: Font Lib: https://github.com/PhenX/php-font-lib
I haved tried with "Times New Roman Bold Italic.ttf"

$font = Font::load($filePath);
$font->parse();

$fontName = $font->getFontName(); // Times New Roman
$fontSubFamily = $font->getFontSubfamily(); // Gras Italique
$fontFullName = $font->getFontFullName(); // Times New Roman Gras Italique

Expected: Bold Italic
Actual: Gras Italique

Here is the meta info of Localization Tables of this font file:
localization tables



via Chebli Mohamed

Get subject of opened or clicked email in Mailgun

I've set up my Mailgun domain to track the opens and clicks of emails sent by my Laravel app.

Now I want to set up webhooks to be notified of those events.

In particular, I'd love to know the event type (e.g. open, click, failed, etc), subject, recipient email address, and ideally the body of the message (although not necessary). For 'click' events, I also want to see the URL of the link that was clicked.

I see which fields of Event data get sent by the webhook, and unlike Amazon SES, Mailgun's webhooks do not seem to include the email subject or body.

The webhook provides data like this:

"message": {
    "headers": {
        "message-id": "f9bxxxxx1e30e7278f5fe75f50741fb3@swift.generated"
    }
}

So it seems to me that I'd somehow need to go to every place within my app that sends an email and add extra functionality to save to my own database the details of the email along with the unique Mailgun message-id of every message right after it has been sent.

Then, when receiving webhooks, I'd search my own database for the message-id and could see the subject and body that I'd stored.

This seems like a terrible hassle and poor design, especially given that other services (such as SES) would provide the email subject for me in the webhook.

Is there some easier way for me to know which emails were opened or clicked (when I receive a Mailgun webhook about an open or click event)?

(Am I misunderstanding something, or would I really need to revamp my entire app to take advantage of open tracking in Mailgun?)



via Chebli Mohamed

Laravel 5.7: UrlGenerator TypeError running php artisan dusk or phpunit

I'm getting this error when I run either php artisan dusk or phpunit:

TypeError: Argument 2 passed to Illuminate\Routing\UrlGenerator::__construct(
must be an instance of Illuminate\Http\Request, null given,
called in RoutingServiceProvider.php

A lot of suggestions for fixing this say to remove any instances of asset( or url( from config files. I'm not using either of those in any config file.

php artisan and php artisan route:list run fine.



via Chebli Mohamed

Laravel testing function to see any changes in a database

I need a function that would give me a list of tables and records that was done by some php code. This function is going to be executed from a unit test.

My idea to set a time by a Carbon, execute some php code, and then run this function that would get a list of all the tables in the database and run a select for each table looking for the specific date at created-at and updated-at fields..

Than it returns a collection of records created in the batabase grouped by table name.

Alternatively, if I'd be happy to get a list of modifications made by database transaction.

I don't know if such function exists somewhere on MySQL level or maybe in Laravel, or PHPUnit.

If it doesn't exist, please help me write it. Thank you.



via Chebli Mohamed

Laravel Passport not authenticating with JWT cookie (self consuming API)

I've gone through the entire page of documentation and as far as I can tell I have everything set up exactly as the documentation states. However, when I attempt to make a GET request to /api/users it always returns a 401 Unauthorized.

If I inspect the request, I see that the laravel_token is indeed being passed along with the request, as well as CSRF.

At this point, I'm not really sure why it's always failing to authenticate, but it's pretty frustrating and I'm sure it's something minor that I'm overlooking somehow.

I'm using Laravel 5.7.5.

Configuration steps done:

  • Ran php artisan passport:install
  • Added trait to User model
  • Added Passport::routes() to AuthServiceProvider::boot()
  • Changed API driver to passport in config/auth.php
  • Added CreateFreshApiToken::class to web middleware


via Chebli Mohamed

Invalid argument supplied for foreach() (View:

I'm tryingo to render data on a table in laravel view as always did, but in this case i'm obtaining an classic php error

Invalid argument supplied for foreach()

I assumed that it's an error related with the type of the variable that i'm using in the foreach, but i'm using a collection as always did.

This is my code:

Controller

 public function getAfiliaciones()
    {


        $roleId = Auth::user()->roleId;
        $provinciaId = Auth::user()->provinciaId;


        if ($roleId == "3") {

            $regAfiliate = Afiliacion::where('provinciaId', $provinciaId)->limit(5)->get();


            foreach($regAfiliate as $afiliate){


            $afiliate->provinciaId = array_get(Provincia::where('id',$afiliate->provinciaId)->pluck('nombre'),0);

            }

            return view('afiliaciones',['regAfiliate' => $regAfiliate]);


         }elseif ($roleId == "1"){

            $regAfiliate = Afiliacion::all();

            foreach($regAfiliate as $afiliate){


                $afiliate->provinciaId = array_get(Provincia::where('id',$afiliate->provinciaId)->pluck('nombre'),0);

            }



            return view('afiliaciones',['regAfiliate' => $regAfiliate]);


        }else{

            return view('afiliaciones');
        }


    }

View

  <table id="afiliaciones" class="table table-striped table-bordered table-hover" >
                    <thead>
                        <tr>
                            <th nowrap>ID</th>
                            <th nowrap>Fecha de Registro</th>
                            <th nowrap>Nombre</th>
                            <th nowrap>Apellido</th>
                            <th nowrap>DNi</th>
                            <th nowrap>Sexo</th>
                            <th nowrap>Email</th>
                            <th nowrap>Nombre de la Madre</th>
                            <th nowrap>Nombre del Padre</th>
                            <th nowrap>Fecha de Nac</th>
                            <th nowrap>Domicilio</th>
                            <th nowrap>Provincia</th>
                            <th nowrap>Cod. Postal</th>
                            <th nowrap>Telefono</th>
                            <th nowrap>Ceular</th>
                        </tr>
                    </thead>
                    <tbody>

                            @if(isset($regAfiliate))

                                @foreach ($regAfiliate as $registro)
                            <tr>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                            </tr>


                            @endforeach
                       @endif


                    </tbody>

                </table>

If someone can help me i'll be very thankful!!



via Chebli Mohamed

instagram hashtag system with Unicode

I want to set up a hashtag system like Instagram to support perisn and arabic languages

this: #(\w+)
for hashtag and work well in english but not work in perisan or arabic

Thank you for helping me



via Chebli Mohamed

use eloquent relationship to retrieve data for child relationship

I am using Laravel 5.6 and MySQL. I have categories, sub-categories, category_info, and services.

A category can have 1 or more sub-categories. A category belongs to one menu category

A sub-category has only one category.

A category has 1 category info record. It doesn't matter if its a category or subcategory it will have one record in the category_info table.

My table structure is as follows

Menu_Categories

id
1,
2

Categories

id, parent_category_id, menu_category_id 
1, null, 1
2, null, 1
3, 1, null
4, 1, null

Category_Info

category_id, name 
1, Legal Services 
2, Misc 
3, US Legal Services 
4, Europe Legal Services 

Controller

$cats = MenuCategories
        ::with(['categories', 'categories.info', 'categories.sub_categories'])
        ->get();

Menu Categories Model

public function categories() {
    return $this->hasMany(Categories::class, 'menu_category_id', 'id');
}

Categories Model

public function menu_categories() {
    return $this->belongsTo(MenuCategories::class, 'menu_category_id');
}

   public function sub_categories() {
    return $this->hasOne(Categories::class, 'parent_category_id');
}

public function info() {
    return $this->hasOne(CategoryInfo::class, 'category_id');
}

SubCategory Info Model

    public function category() {
    return $this->belongsTo(CategoryInfo::class);
}

I need to return the categories and the category info as follows

{
    Categories: {
        {
            id: 1,
            parent_category_id, null,
            Sub_Categories: {
                {
                    id: 3
                    parent_category_id: 1
                    Category_Info: {
                        {
                            category_id: 3,
                            name: US Legal Services
                        }
                    }
                },
                {
                    id: 4
                    parent_category_id: 1,
                    Category_Info: {
                        {
                            category_id: 4,
                            name: Europe Legal Services
                        }
                    }
                },
            },
            Category_Info: {
                {
                    category_id: 3,
                    name: Legal Services
                }
            }
        },
        {
            id: 2,
            parent_category_id, null,
            Category_Info: {
                {
                    category_id: 3,
                    name: Misc
                }
            }
        },
    }
}

With the way I have relationships set up it is returning data incorrectly. It is not returning Category_Info for sub-categories.

{
    Categories: {
        {
            id: 1,
            parent_category_id, null,
            Sub_Categories: {
                {
                    id: 3
                    parent_category_id: 1
                },
                {
                    id: 4
                    parent_category_id: 1,
                },
            },
            Category_Info: {
                {
                    category_id: 3,
                    name: Legal Services
                }
            }
        },
        {
            id: 2,
            parent_category_id, null,
            Category_Info: {
                {
                    category_id: 3,
                    name: Misc
                }
            }
        },
    }
}

Is it possible to return Category_Info for the sub-categories as well? Thanks in advance



via Chebli Mohamed

QueryException: General error: 1 no such table: {table_name} (SQL: select * from "{table_name}")

  • Laravel Version: 5.7
  • PHP Version: 7.2
  • Database Driver: sqlite
  • Database: memory

All testing on PHPUnit was working completely fine. But when I added View::share in AppServiceProvider then all the PHPUnit tests failed.

AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        \View::share('categories', \App\Models\Category::all());
    }
}

Error

Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: categories (SQL: select * from "categories")

I have already used RefreshDatabase in my all test.

Please guide me, how can I fix this. Where should I call View::share in Laravel app so, all tests should pass.



via Chebli Mohamed

Cannot Assign Key => Value to Foreach Array

I have the following array of countries ($countryIso = array("US","BR","CL");) and my idea is to create a new array to display the following schema:

('US', 200)

I tried to create the following structure:

    $countryIso = array("US","BR","CL");

    foreach ($countryIso as $isocode) {
        $productcalc[] = "'" . strtoupper($isocode) . "'" . ',' . number_format($this->product->calculate($product = $product, $countryIso = $isocode), 0, '.', ',');
    }

Despite I can create a look alike format, I realized that the array is not well formed. When I checked the output displays the following:

Array ( [0] => 'US',200

being the key is [0] and not US.

Any idea of how can I create a key => value result with

Array ( [US] => 200

using the foreach structure in my code? I tried with variants like array_combine to combine countryIso array with productcalc array but with no success



via Chebli Mohamed

A non-numeric value encountered in laravel script

in my laravel script, In a page appear this error:

"A non-numeric value encountered (View: /home/grammer/public_html/test/core/resources/views/admin/apiServices.blade.php)"

for this line

<td></td>

my code page:

@extends('admin.layouts.master')
@section('page_icon', 'fa fa-suitcase')
@section('page_name', 'API Services')
@section('body')
    <div class="row">
        <div class="col-md-12">
            <div class="tile">
                <h3 class="tile-title">API Services List</h3>
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>Serial</th>
                        <th>Service ID</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Price</th>
                        <th>Min</th>
                        <th>Max</th>
                    </tr>
                    </thead>
                    <tbody>
                    @foreach($items as $key => $item)
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td> $</td>
                            <td></td>
                            <td></td>
                        </tr>
                    @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
@endsection



via Chebli Mohamed

Passport middlwares permissions routes

im using first time Passport laravel, but i still didnt understand quite is the difference between midlewareare auth:api and client:credentials (CheckClientCredentials ), doesnt these 2 types of middlware restrict routes? What is the difference between them?



via Chebli Mohamed

How to upload laravel project on namecheap hosting

can somebody please tell me how to upload laravel project on namecheap shared hosting. I am using php version 7.2 and laravel version 5.7.



via Chebli Mohamed

Getting empty value of a variable in laravel mail view

I've assigned public variables in the mailable. I'm getting some values of keys but I get empty values from the keys that I had assigned later. I'm implementing queues as well.

In my controller:

public function changeOrderStatus(Order $order){

    $order->type = $request->type; //getting these two keys empty i.e.type and amount
    $order->amount = $transaction->amount;
    $mail = new CancelRefundOrder($order);

}

In my /App/Mail/CancelRefundOrder.php

class CancelRefundOrder extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;
    public $order;
    public $order_type;

    public function __construct($order)
    {
        $this->order = $order;        
        $this->order_type = $order->type;        
    }

    public function build()
    {
        return $this->view('emails.ecommerce.cancel_refund_order_mail');
    }
}

If I dd($order_type) here I get the value. But in my blade cancel_refund_order_mail, I get empty value on or why?



via Chebli Mohamed

Auth::login() not working properly laravel 5.7

I'm trying to setup 'Login with facebook' using laravel socialite. When I try to login, it gets a successful callback from the facebook, I'm storing the data fetched into the database and try to redirect to home page. While doing so, I am redirected back to the login page and never reaching the homepage.

While debugging the error I found that my Auth::login($user) is not working properly.

Here is the code-

AuthController.php

use App\Http\Controllers\Controller;
use Laravel\Socialite\Two\InvalidStateException;
use Auth;
use Socialite;
use App\User;

public function redirectToProvider($provider)
{
    return Socialite::driver($provider)->redirect();
}

public function handleProviderCallback($provider)
{
    $user = Socialite::driver($provider)->user();
    // dd($user);
    $authUser = $this->findOrCreateUser($user, $provider);
    // dd($authUser);
    if(Auth::login($authUser, true)){            // here is the error
      return redirect($this->redirectTo);
    }
    else{
      return 'Login not done';                 //this prints out to the screen
    }
}

public function findOrCreateUser($user, $provider)
 {
     $authUser = User::where('id', $user->id)->first();
     if ($authUser) {
         return $authUser;
     }
     return User::create([
         'name'     => $user->name,
         'email'    => $user->email,
         'avatar'    => $user->avatar,
         'password'    => bcrypt('password'),
         'provider' => $provider,
         'id' => $user->id
     ]);
 }

Do let me know what am I doing wrong.



via Chebli Mohamed

Shown Success / Failure message after laravel admin action is executed

I want shown message in laravel admin panel after action is executed or when i will redirect to listing or other page.

I have configured the laravel-admin package so inbuilt laravel module message showing in toaster so i want to need similar to this.

So can you please let me know if anyone know about this.

Thanks.



via Chebli Mohamed

dimanche 30 décembre 2018

(2/2) ErrorException Invalid argument supplied for foreach() (View: Path..\resources\views\pages\knowledgebasecategory.blade.php)

(2/2) ErrorException Invalid argument supplied for foreach() (View: C:\laragon\www\LK\resources\views\pages\knowledgebasecategory.blade.php)

FrontController.php

public function knowledgebasecategory($id)
{
$knowledgebasecategory = KnowledgebaseCategory::find($id);
$knowledgebases = Knowledgebase::orderBy('created_at','desc')->paginate(3);
return view('pages.knowledgebasecategory')
->with('knowledgebasecategory', $knowledgebasecategory)
->with('title', $knowledgebasecategory->name)
->with('knowledgebasecategories', KnowledgebaseCategory::all())
->with('knowledgebases', $knowledgebases);
}

knowledgebasecategory.blade.phpp

enter image description here



via Chebli Mohamed

Core PHP vs Laravel Framework, Which is better for large scale applications and API?

Guys, I want to know about which is better or not in terms of large-scale projects. Core PHP vs Frameworks like Laravel.

I know that core PHP is able to:

handle more requests. Low memory consumption.

but I don't know about a framework like Laravel. Please guide me.



via Chebli Mohamed

How to reduce loading time of sql query?

I had created a query to get a list of staffs using this query:

  $itemregistrations = DB::table('itemregistrations')
                       ->join('sections', 'itemregistrations.sectionid', '=', 'sections.sectionid')
                       ->join('categories', 'itemregistrations.categoryid', '=', 'categories.categoryid')
                       ->join('operasi', 'itemregistrations.operasiid', '=', 'operasi.operasiid')
                       ->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan', 'sections.sectionname', 'categories.categoryname', 'operasi.operasiname')
                       ->get();

However, the query gets loading quite long, about a minute to finish loading. The list displayed about 1256.

How to reduce the loading time?

I read about eager loading to decrease the loading time. But my trial not success.

section is the department of staffs.

categories is the staff level

operasi is the grade of staff, related to categories, each category has its own operasiname.



via Chebli Mohamed

Cannot create array for keys and another for its values for Google GeoChart addRow() function

Lavacharts GeoChart displays the following structure:

    $popularity = Lava::DataTable();

    //creates lavachart GEOMAP chart providing values
    $popularity
            ->addStringColumn('Country')
            ->addNumberColumn('VALUE')
            ->addRow($value));
    Lava::GeoChart('Popularity', $popularity);

And ->addRow() request values in the following form:

->addRow(array('US', 200))
->addRow(array('BR', 300))

My current code generates $value using an array of countries:

    $countryIso[] = array('US', 'BR','CL');

and foreach country performs a calculation:

    foreach ($countryIso as $countrycode) {
        $value[] = $this->product->make_calculation();
    }

My problem:

Currently my code displays data in the following format:

Array ( [0] => 899.99 1 => 1214.9865 [2] => 1445.833935 )

And I cannot find the way to replace keys like [0] with values from $countryIso array

eg: [0] replaced by US , 1 replaced by BR ....

in order to create values in the way requested by Google GeoChart like:

->addRow(array('US', 200))

I tried with array_combine — "a function that creates an array by using one array for keys and another for its values" but with no success.



via Chebli Mohamed

bonecms laravel-captcha validator for hesto multi-auth login

I am using hesto/multi-auth for login.I want to add captcha for login and register.For that i am using bonecms/laravel-captcha.I Used validator for captcha on register.I need to add validator for the captcha on login Form.Where I want to add validator? How should I change my Login Controller?

For Register Form with Validator:

<div class="col-md-6">
   @captcha
   <input id="captcha" type="text" class="form-control" name="captcha">
</div>

On Register Controller
protected function validator(array $data) {
    return Validator::make($data, [
        'email' => 'required|email|max:255|unique:clients',
        'password' => 'required|min:6|confirmed',
        'captcha' => 'required|captcha',
    ]);
}

Login Form Code:

For Login Form view
<div class="col-md-6">
    @captcha
    <input id="captcha" type="text" class="form-control" name="captcha">
</div

I need to validate Captcha for login form.



via Chebli Mohamed

Using of raw methods in laravel app seems safe

I know that using of raw methods is not good practice in larabel, but in some cases I need to use them. So in my laravel 5.7 I have next scopes defined, as :

1)

public function scopeGetByCreatedAt($query, $filter_voted_at_from= null, string $sign= null)
{
    if (!empty($filter_voted_at_from)) {
        if (!empty($sign)) {
            $query->whereRaw(with(new VoteItemUsersResult)->getTableName().'.created_at ' . $sign . "'".$filter_voted_at_from."' ");
        } else {
            $query->where(with(new VoteItemUsersResult)->getTableName().'.created_at', $filter_voted_at_from);
        }
    }
    return $query;
}

This method is used in report form, where $sign is given as as string literal ' > ' and filter_voted_at_from is date selection input, like

$detailedVoteItemUsersResults = VoteItemUsersResult
::getByCreatedAt($filter_voted_at_from, ' > ')

I mean none of these fields can have dangeraous value like ‘drop table users;’ .

2) when I need to make selection by several fields

public function scopeGetByName($query, $name = null)
{
    if ( ! isset($name)) {
        return $query;
    }
    return    $query->whereRaw(' ( ' . ContactUs::myStrLower('author_email', false, false) . ' like ' . ContactUs::myStrLower($name, true,
            true) . ' OR ' . ContactUs::myStrLower('author_name', false, false) . ' like ' . ContactUs::myStrLower($name, true, true) . ' ) ');
}

...

public static function myStrLower($value, $with_single_quote, $with_percent) : string
{
    $percent= $with_percent ? '%' : '';
    if ( $with_single_quote ) {
        $ret = "LOWER('" . $percent . $value . $percent . "')";
    } else {
        $ret= "LOWER(" . $percent . $value . $percent . ")";
    }
    return $ret;

}

Using this scope $name field is text input, so if user filles text like ‘Prof;drop table users;’ I have next sql deguging:

   SELECT * 
    FROM `contact_us` 
    WHERE  ( LOWER(author_email) like LOWER('%Prof;drop table users;%')     OR LOWER(author_name) like LOWER('%Prof;drop table users;%') )  
    ORDER BY `created_at` asc 

So I suppose no problems would be triggered?

Anyway I would prefer to avoid using of raw methods. a) Is it possible in examples above to avoid using of raw methods?
b) If no, are they safe ?

Thanks!



via Chebli Mohamed

How to insert select and join method in query using when method?

I am using when method for search filtering with this code:

 $newitem = DB::table('itemregistrations')
                ->when(request('umur'), function($query){
                    $query->whereRaw('YEAR(CURDATE()) - lahir_yy >= ?', [request('umur')]);
                })
                ->when(request('negeri_lahir'), function($query){
                    $query->where('NegeriID', request('negeri_lahir'));
                })
                ->when(request('kategori'), function($query){
                    $query->where('CategoryID', request('kategori'));
                })
                ->when(request('pangkat'), function($query){
                    $query->where('OperasiID', request('pangkat'));
                })
                ->get();

But I need to insert join and select method to get the categoryname and operasiname. but when I insert it to the code, the query error appear.

How to use join and select method in the code?



via Chebli Mohamed

Laravel Search between two numbers

I currently have the following function in my search controller. I also want to retrieve the results where the space_price is between the user min and max input. I also want the query to work if the user doesn't enter a min or max value or if they enter a max value and no min value it will return the results between 0 and the max value.

$town = $_GET['town'];
$category = $_GET['category'];
$min = $_GET['min'];
$max = $_GET['max'];

$spaces = \App\Space::where([ 
    ['space_town', 'LIKE', '%' . $town . '%'],
    ['space_category', 'LIKE', '%' . $category . '%'],
])->get();

return view('search', compact('spaces'));

Thanks in advance, Jamie



via Chebli Mohamed

Call to undefined method BinaryFileResponse::header()

I have an issue that appeared after updating the Maatwebsite Laravel Package but they are certain it isn't an issue on their package.

I get the following error: Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header() in my ModifyHeadersMiddleware.php file.

This comes up through the following controller function:

public function summaryReport(){
    return Excel::download(new ClaimsExport, 'claims-report.xlsx');
}

Under which my export is as such:

<?php

namespace App\Exports;

use App\Claim;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\Exportable;
use Illuminate\Contracts\View\View;

class ClaimsExport implements FromView
{
    use Exportable;

    /**
    * @return \Illuminate\Support\Collection
    */
    public function view(): View
    {
        return view('exports.osd.claims', [
            'claims' => Claim::where('type',2)->where('status',1)->whereNotNull('shipmentID')->orderBy('claimDate','desc')->get()
        ]);
    }
}

And this is the section of code that is brought up in the ModifyHeadersMiddle.php file:

   public function handle($request, Closure $next)
{
    $headers = [
        'Access-Control-Allow-Origin'      => '*',
        'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS',
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => '86400',
        'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
    ];

    if ($request->isMethod('OPTIONS')) {
        return response()->json('{"method":"OPTIONS"}', 200, $headers);
    }

    $response = $next($request);
    foreach($headers as $key => $value) {
        $response->header($key, $value);
    }

    return $response;
}

I'd appreciate any help anyone can give. Thank you so much!



via Chebli Mohamed

How to get last inserted non incremental id using eloquent in Laravel?

I have two models Customer and Address. My Customer has non incremental primary key and is of type string which is "customer_id". The relationship between these two models is of one to many, that means for single customer many addresses for example invoice address, delivery address, current address, etc. My Customer model is as shown below

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    protected $keyType='string';
    protected $primaryKey='customer_id';
    public $incrementing=false;

    public function addresses()
    {
        return $this->hasMany('App\Address','customer_id');
    }
}

And my Address model is as shown below

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    //
    public $timestamps = false;
    // protected $table="addresses";
    public function customer()
    {
        return $this->belongsTo('App\Customer');
    }
}

The other thing to note is that my "customer_id" is incremental in sense that I have created separate table namely customer_sequence which is auto incremental and before inserting record I append it with two character code using trigger and then place it into my "customers" table. Now when I save the data of customer and try to get id from customer model it returns me null. My controller is as shown below

public function store(Request $request)
{
$customer=new Customer;
$invoiceAddress=new Address;
$deliveryAddress=new Address;

$customer->name=$request->name;
$customer->type=$request->type;
$customer->dob=$request->dob;
$customer->save();

$deliveryAddress->street_name_no=$request->street_name_no;
$deliveryAddress->city=$request->city;
$deliveryAddress->country=$request->country;

//This throws error customer_id cannot be null integrity constraint
$deliveryAddress->customer_id=$customer->customer_id;
$deliveryAddress->save();
}



via Chebli Mohamed

laravel 5.3 Missing argument 2 for Illuminate\Routing\Router::middleware()

Missing argument 2 for Illuminate\Routing\Router::middleware()

api.php

Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); });

RouteServiceProvider.php

protected function mapApiRoutes()
{
Route::group([
    'middleware' => ['api', 'auth:api'],
    'namespace' => $this->namespace,
    'prefix' => 'api',
], function ($router) {
    require base_path('routes/api.php');
});
}



via Chebli Mohamed

samedi 29 décembre 2018

How to call a text box on controller from view in Laravel

I simply want to call a text on my controller so that I can choose what id i want to input to fetch it form the database, but for now I have this code i dont have idea on how to fetch the text box name or itself on the controller any help thanks

My Controller

public function index()
 {
        $aircrafts = Aircraft::all();
        return view('admin.aircrafts.index', compact('aircrafts'));

        $data = DB::table('aircrafts')
        ->join('movies','movies.aircraft_id','=','aircrafts.aircraft_id')
        ->select('movies.*')
        ->where('aircrafts.aircraft_id','=','HERE IS WHERE I WANT TO CALL THE TEXTBOX COZ HERE IS WHERE I INPUT IDs')
        ->get();
    }

My View

{!! Form::open(['action' => 'Admin\AircraftsController@index', 'method' => 'POST']) !!}

    

    {!! Form::close() !!}



via Chebli Mohamed

Laravel Query, Group and counting

I have a table scheme of

|checkSumID | playerID | team | gameResult | pickOrder | pickupRecordLocatorID

I have hundreds of results and I am trying to identify the following groupbed by playerID.

I want to count how many times gameResult is a Win or a Loss only when pickOrder value is 0. I would like to display it in an array format such as

array(
  'PlayerID' => '2837192',
    'data' => array(
       'win' => '9',
       'Loss' => '3'
      )
   ),
   ...
)

Any help would be greatly appreciated. Please let me know if you have any questions.



via Chebli Mohamed

Laravel Session Cookie Expiry Changing

I am running into a problem when my Laravel session-cookie changes expiry time each time I refresh and often expires after 2x refreshes.

I think the expected functionality is for it to expire x minutes after you last interacted with the service, but mine seems to work very differently. Let me detail it:

In my Laravel .env file I have

APP_TIMEZONE="Pacific/Auckland"

Accessing PHP via the CLI I get this output with regards to my local time:

php -a
Interactive shell
php > echo date("Y-m-d H:i:s");
2018-12-30 04:08:09
php > echo date_default_timezone_get();
UTC
php > echo date('I');
0

The time given above is out by an hour. I think PHP is misconfigured for daylight savings. My cookie access times are also off by an hour as well, because of this I assume.

  1. Login (Success)

    • Expires on: Mon, 31 Dec 2018 03:53:21 GMT
    • Last accessed on: Sun, 30 Dec 2018 03:53:21 GMT
  2. Refresh #1 (Success)

    • Expires on: Sun, 30 Dec 2018 05:53:31 GMT
    • Last accessed on: Sun, 30 Dec 05:53:31 GMT
  3. Refresh #2 (Logged Out)

    • Expires on: Sun, 30 Dec 2018 05:53:39 GMT
    • Last accessed on: Sun, 30 Dec 2018 05:53:39 GMT

I would have expected that my Expires on value would have been bumped forward to 24 hours ahead of when I last accessed the application (that is what my session timeout is set to).

Any help would be appreciated!



via Chebli Mohamed

How to convert this raw query to eloquent?

I want to convert this raw query that I have do in order to select the available rooms.

    $checkInDate = date("d-m-Y", strtotime($request->start_date));
    $checkOutDate = date("d-m-Y", strtotime($request->end_date));

    $availableRooms = $this->_availablerooms->from('availableRoom as r')
        ->selectRaw('*,r.roomDoorNum, r.isAvailable, rt.title as roomType,res.roomReservedID')
        ->join('roomtype as rt','rt.roomTypeID','=','r.roomTypeID')
        ->leftjoin('roomReserved as rr','rr.roomID','=','r.roomID')
        ->leftjoin('reservation as res','res.roomReservedID','=', DB::raw('rr.roomReservedID AND (res.reservationDate BETWEEN '."$checkInDate".' AND ' ."$checkOutDate". ' OR res.expiryDate BETWEEN '."$checkInDate".' AND ' ."$checkOutDate".')' ))
        ->get();

    return $availableRooms;

I'm new to eloquent so I'm having a hard time doing this.



via Chebli Mohamed

Laravel migration: "table already exists", but it has data and I cannot drop it

I am trying to do a migration with Laravel, but I get a message:

Illuminate\Database\QueryException : SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists (SQL: create table 'users'...

I researched this, and all suggestions say that I need to drop the table and re-run the migration.

However, my table has some dummy data and I don't want to re-type everything. How to get around this?



via Chebli Mohamed

Laravel - SQL query Join Statement convert PHP syntax to Laravel syntax

I am trying to convert PHP syntax join statement into Laravel Syntax but whatever what ill do nothing is being shown in the page test. I am new and beginner in Laravel so please guide me thank you! so here is my code

so let's say that i have this controller

public function queryJoinTest()
{

$query = "SELECT c.*, s.* FROM tbl_customer c JOIN tbl_stock s ON s.customer_id = c.customer_id AND c.customer_id = 1";

}

and let's say i have this view

here I have an input text and submit button so when I change the c.customer_id = 1 I can choose what customer_id i will type in and it will not be default in 1

<input type=text name="customerID" placeholder="Input an ID">

<input type="submit" value="Submit" name="submit">

OUTPUT

so overall i would like to achieve this

please take a look at this image

enter image description here

i have a textbox and there I input customer id so the default 1 customer id in my query will be removed and changed it into textbox

P.S any suggestions or advice on making join statement in laravel and i will take thanks



via Chebli Mohamed

You must have 4 photo fields filled in. You can not send the desired number of photos

To view the code you can refer to the link below

https://gist.github.com/Amirhf1/b80a7a9cac2085470652b922a7ac0e0d



via Chebli Mohamed

Multiple websites on one laravel application

I've created a dashboard on laravel with user authentication. I want to create multiple websites on this single laravel application. Each website will belong to one user and each user when log in should see the pages of their own website on the dashboard. Please, help me to do that, any idea or tutorial



via Chebli Mohamed

Laravel, How to remove signed url for a user?

Remove or disable old signed URLs in Laravel. https://laravel.com/docs/5.6/urls#signed-urls

when i make signed URL like:

return URL::signedRoute('login', ['user' => 1]);

i send it as signed notifications to email and i want to disable all old signed URL.



via Chebli Mohamed

Why does the first time I land on Laravel URL it renders HTTP based on Elastic Beanstalk?

I am using laravel 5.5 The application is being served on Elastic beanstalk single instance. I am able to server the Laravel application on HTTPS. However, when I first land on the link it serves as HTTP. IF I refresh the link it will again run on HTTPS. To test I cleared all the cookies and put the link on the address bar, again the first time I land there it serves in HTTP and again if I refresh the page it serves on HTTPS.

To serve the laravel app on Elastic Beanstalk I have already updated the SSL certificate.

Using the .htaccess as below

# Force SSL
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1 

Additionally to serve all the pages on HTTPS I have included the code as below in the boot method of AppServiceProvider

\URL::forceScheme('https');

This is very annoying as I dont really get if it is the Laravel app problem or the server problem.



via Chebli Mohamed

Symfony\Component\HttpKernel\Exception\NotFoundHttpException

I'm using laravel 5..7 and having some trouble on multilingual website... I have global route prefix for adding seo purposes. (adding lang parameters like en,tr to url)

 Route::group([
            'middleware' => 'web',
            'namespace' => $this->namespace,
            'prefix' => in_array(Request::segment(1), $this->noLangPrefix) ? "" : Request::segment(1)
        ]...
i

t actually works pretty well with below Language middleware..

public function handle($request, Closure $next)
    {
        $langSegment = $request->segment(1);

        // go ahead if is admin panel or sitemap
        if ($langSegment == "admin")
            return $next($request);

        if ($langSegment == "sitemap.xml")
            return $next($request);

        // if is homepage 
        if (is_null($langSegment)) {
            app()->setLocale($request->getPreferredLanguage((config("app.locales"))));
            return $next($request);
        }

        if (strlen($langSegment) == 2)
            return $next($request);

        return redirect(url(config("app.locale") . "/" . implode($request->segments())));
    }

When i say, "app.test/blog" it redirects me to "app.test/tr/blog"

But if I say "app.test/blog/sample-blog-spot" it gives me Symfony\Component\HttpKernel\Exception\NotFoundHttpException

Why I'm getting this error ? Because it cant fine route or something and how can I fix it ?



via Chebli Mohamed

How to set Eloquent withDefault on some condition rather than null and set default value from modal

I am creating an API in laravel to get all posts with their creator.

I have following tables - posts id title desc creator_id -> belongsTo users id creator_name type - ENUM('system','user') "when 'system', creator_name will be given else creator_id is used get name from users table"

users id name . .

In laravel we have Post and User Model. System posts are created by admin and a creator_name is provided. For system posts we want to show creator name from the creator_name field in posts table and not the details of admin user.

What is the best way to achieve this in laravel?

Post Model -

class Post{
    function creator(){
        return $this->belongsTo('App\Models\User', 'creator_id');
    }
}

Post Controller -

public function index()
{
    $posts = Post::with('creator')->paginate();
    $data = $posts->toArray();

    foreach ($data['data'] as $key => &$value) {
        if($value['type'] === 'system' && isset($value['creator'])){
            $value['creator']['name'] = $value['creator_name'];
            unset($value['type']);
            unset($value['creator_name']);
        }
    }

    return $this->sendResponse($data);
}




expected:
Posts -

[
    {
        "id": 1,
        "title": "some title",
        "desc": "some description",
        "creator_name": NULL,
        "creator_id": 123,
        "creator": {
            "id": 123,
            "name": "John Doe",
        },
        "type": "user"
    },
    {
        "id": 2,
        "title": "some other title",
        "desc": "some other description",
        "creator_name": "Jane Doe",
        "creator_id": 12, // admin user
        "creator": {
            "name": "Jane Doe", // creator_name rather than details of admin user
        },
        "type": "system"
    }
]



via Chebli Mohamed

How In LeftJoin to add additive parameter?

In my laravel 5.7 / eloquent/ Mysql 5.5 app I need in chats listing to get values of messsages of any chat and 1 more column of messsages of any chat for given useronly ($user_id):

I tried as :

$chats          = Chat
     ::select( \DB::raw( ' chats.*, count(cm.id) as messages_count, count(cmu.id) as user_messages_count' ) )
    ->orderBy('name', 'asc')
    ->groupBy('chats.id')
    ->leftJoin( \DB::raw('chat_messages as cm'), \DB::raw('cm.chat_id'), '=', \DB::raw('chats.id') )
    ->leftJoin( \DB::raw('chat_messages as cmu'), \DB::raw(' cmu.chat_id = chats.id and cmu.chat_id = ' .$user_id ) )
    ->get();    

But error :

 Column not found: 1054 Unknown column '' in 'on clause'.

Looks like for leftJoin expression can not be used with empty value paramerter. Or in some other way?

$chats          = Chat
     ::select( \DB::raw( ' chats.*, count(cm.id) as messages_count, count(cmu.id) as user_messages_count' ) )
    ->orderBy('name', 'asc')
    ->groupBy('chats.id')
    ->leftJoin( \DB::raw('chat_messages as cm'), \DB::raw('cm.chat_id'), '=', \DB::raw('chats.id') )
    ->leftJoin(\DB::raw('chat_messages as cmu'), \DB::raw('cmu.chat_id'), '=', \DB::raw('chats.id'))
    ->where( 'cmu.user_id', $user_id)
    ->get();    // `chat_messages` ORDER BY `chat_id` A

That works , but not correctly as for condition

>where( 'cmu.user_id', $user_id)

left join is skipped and rows with user_messages_count = 0 are skipped, but I need them.

Which is the right way?

Thanks!



via Chebli Mohamed

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'seaurchin.availableroom' doesn't exist (42S02)

I'm trying to get the available room at specified date by the client. So far I tried using join and left join to get the available room.

Controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\RedirectResponse;
use App\client;
use App\reservation;
use App\booking;
use App\availableRoom;
use App\roomType;
use App\amenities;
use App\payment;
use App\roomReserved;
use App\Mail\ReservationDetail;
use Carbon\Carbon;
class ReservationController extends Controller
{

    private $_availablerooms;

    /**
     * ReservationController constructor.
     */
    public function __construct()
    {
        $this->_availablerooms = new availableRoom();
    }


    /**
     * @param Request $request
     * @return mixed
     */
    public function checkAvailable(Request $request){
        $checkInDate = date("d-m-Y", strtotime($request->start_date));
        $checkOutDate = date("d-m-Y", strtotime($request->end_date));

        $availableRooms = $this->_availablerooms->from('availableRoom as r')
            ->selectRaw('*,r.roomDoorNum, r.isAvailable, rt.title as roomType,res.roomReservedID')
            ->join('roomtype as rt','rt.roomTypeID','=','r.roomTypeID')
            ->leftjoin('roomReserved as rr','rr.roomID','=','r.roomID')
            ->leftjoin('reservation as res','res.roomReservedID','=', DB::raw('rr.roomReservedID AND (res.reservationDate BETWEEN '."$checkInDate".' AND ' ."$checkOutDate". ' OR res.expiryDate BETWEEN '."$checkInDate".' AND ' ."$checkOutDate".')' ))
            ->get();

        return $availableRooms;
        //return view('rooms');lorem
    }



}

The problem is I'm getting this error now.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'seaurchin.availableroom' doesn't exist (42S02)



via Chebli Mohamed

htmlspecialchars() expects parameter 1 to be string, array given (View: in notification Database

Blade Code::

Notifications :: code

'data' => $this->dataCase,

Data Base Value

{"data":[{"name":"gwegweg"}]}

Finaly My error when get Value from database to view in my blade so please advise me



via Chebli Mohamed

Laravel - Array to string conversion

I am trying to show the related applications to abstract, I have used the code below but I am getting this error

Array to string conversion

My controller

public function show($A_ID){

  $abstract = Project::find($A_ID);

  // I believe the issue is caused by the line below but I am not sure what is wrong about it 

  $applications = Application::find($A_ID);
  return view('Abstracts.show')->with('abstract', $abstract)
                             ->with($applications);
}

My model

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
use Traits\HasCompositePrimaryKey; 

class Application extends Model{


    //Table name
    protected $table = 'student_application';

    //composite key
    protected $primaryKey = array('A_ID', 'S_ID');
    protected $fillable = ['S_Justification' ];
    public $incrementing = false;}

I want to note that the composite key is declared using this answer number two with currently 59 votes

For more information here is my view

@if (count($applications)>0)
@foreach ($applications as $application)
<tr>
        <td><h5></h5></td>
</tr>
@endforeach
@else 
<p> This project has no applications </p>
@endif



via Chebli Mohamed

vendredi 28 décembre 2018

Installing docker with nginx-proxy I got docker-php-ext-install not found error

I need to install laravel 5 app on Digital Ocean Server (under kubuntu 18) using Docker with VIRTUAL_HOST pointing to my my.freenom.com host using proxy server (https://github.com/jwilder/nginx-proxy) and for this in my app I use configuraion

docker-compose.yml:

version: '3.1'

services:

    web:
        image: jwilder/nginx-proxy
        build:
            context: ./web
            dockerfile: Dockerfile.yml

        environment:
            - APACHE_RUN_USER =#1000
            - VIRTUAL_HOST    =my.freenom.com
        volumes:
            - ./mysite.template:/etc/nginx/conf.d/mysite.template

        ports:
            - 8085:80
        working_dir: ${APP_PTH_CONTAINER}


    db:
        image: mysql:5.5.62
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: 1
        volumes:
            - ${DB_PATH_HOST}:/var/lib/mysql


    adminer:
        image: adminer
        restart: always
        ports:
            - 8086:80
        links:
            - db


    composer:
        image: composer:1.6
        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        working_dir: ${APP_PTH_CONTAINER}
        command: composer install --ignore-platform-reqs

and in web/Dockerfile.yml :

FROM nginx:1.10

 RUN apt-get update -y && apt-get install -y libpng-dev  \
     nano  libmcrypt-dev 

 RUN docker-php-ext-install \
     pdo_mysql \
     mcrypt \
     && a2enmod \
     rewrite

but running command :

docker-compose up -d --build

I got error :

 docker-php-ext-install: not found

Why error and which is correct way?

Thanks!



via Chebli Mohamed

How url of laravel app under docker without "public"?

Installing laravel 5.7 app under docker(based on php:7.2-apache ) I need to use "/public" in my url to run my app, so root url of my app is

http://127.0.0.1:8081/public

I modified .env of my laravel app as

APP_URL=http://127.0.0.1:8081/public/

But it did not help, as I browser I got image url :

http://127.0.0.1:8081/storage/mysites/-mysite-16/Babe_ver1.jpg?dt=1546059015

which way is invalid, as valid way must be :

http://127.0.0.1:8081/public/storage/mysites/-mysite-16/Babe_ver1.jpg?dt=1546059015

The similar way with ajax requests, as I got invalid ways :

http://127.0.0.1:8081/admin/get_activity_log_rows/1

But valid must be

http://127.0.0.1:8081/public/admin/get_activity_log_rows/1

In my docker-compose.yml :

version: '3.1'

services:

web:

build:
context: ./web
dockerfile: Dockerfile.yml

environment:
- APACHE_RUN_USER=www-data
volumes:
- ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
ports:
- 8081:80
working_dir: ${APP_PTH_CONTAINER}


composer:
image: composer:1.8
volumes:
- ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
working_dir: ${APP_PTH_CONTAINER}
command: composer install

and in .env of docker project :

# PATHS
DB_PATH_HOST=./databases
APP_PATH_HOST=./Mysites
APP_PTH_CONTAINER=/var/www/html/

How to set root url of my site with “/public” ?

Thanks!



via Chebli Mohamed

How to produce charts from data in database using laravel package?

I want to create pie chart using data from database using chart package from laravel.

I queried the values using this sql statement:

 $gender = DB::table('results')
            ->SELECT (DB::raw("SUM(CASE WHEN results.gender_id = 1 THEN 1 ELSE 0 END) as Male_count,
   SUM(CASE WHEN results.gender_id = 2 THEN 1 ELSE 0 END) as Female_count"))
             ->get();

I had queried the values into an array:

 Collection {#233 ▼
 #items: array:1 [▼
 0 => {#234 ▼
  +"Male_count": "2"
  +"Female_count": "1"
   }
  ]
  }

The code to generate the pie chart is as below:

   $chart = Charts::database($gender, 'pie', 'highcharts')
            ->title('Respondents Distribution by Gender')
            ->elementLabel("Gender")
            ->dimensions(1000,500)
            ->responsive(false);
  return view('gender_chart',compact('chart'));

However, the chart blade displays with no error but the values is null. So, no pie chart appear..only labels showing 0% values appear.

How to retrieve the gender counts of male and female from database and can be read by the chart?



via Chebli Mohamed

Property [client] does not exist on this collection instance

I can't get the value of the foreign key that is inside the booking table.

Booking Table

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class booking extends Model
{
    protected $primaryKey = 'bookingID';
   protected $fillable = ['clientID', 'checkInDate', 'checkOutDate', 'roomsCount', 'roomTypeID', 'adultsCount', 'childrenCount', 'amenityID', 'paymentID'];

    public function client()
    {
        return $this->hasOne(Client::class,'clientID');
    }

}

Client Table

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class client extends Model
{
  protected $primaryKey = 'clientID';
   protected $fillable = ['fullNmae', 'firstName', 'lastName', 'phoneNumber', 'emailAddress'];
  public function booking()
  {
      return $this->hasMany(Booking::class);
  }
}

I tried adding the protected $primaryKey = 'bookingID'; and protected $primaryKey = 'clientID'; as suggested in my previous question but now I still can't get just the FirstName from the client table.

$bookingDetail = booking::with('client')->get();
    return  $bookingDetail->client->firstName;



via Chebli Mohamed

Get multiple foreign key values and output them on view

I'm making a reservation system, this is the table that I'm currently using.I can't get the foreign key value of client payment. I already put the relationship in the models.

Booking

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class booking extends Model
{
   protected $fillable = ['clientID', 'checkInDate', 'checkOutDate', 'roomsCount', 'roomTypeID', 'adultsCount', 'childrenCount', 'amenityID', 'paymentID'];
    //public $incrementing = false;

    public function client()
    {
        return $this->belongsTo('App\Client','clientID');
    }
    public function payment()
    {
        return $this->hasOne('App\Payment');
    }
    public function amenities()
    {
        return $this->hasOne('App\Amenities');
    }

Client

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class client extends Model
{
   protected $fillable = ['fullNmae', 'firstName', 'lastName', 'phoneNumber', 'emailAddress'];
  public function booking()
  {
      return $this->hasMany('App\Booking');
  }
}

Payment

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class payment extends Model
{
   protected $fillable = ['clientID', 'paymentMethod', 'invoiceNum', 'accountName', 'amountPaid', 'datePaid', 'payment_image', 'comments'];
  public function booking()
  {
      return $this->belongsTo('App\Booking');
  }
}

I'm currently using this to access the foreign key

$bookingDetail = booking::with('client', 'payment')->get();
        return view('detail')
        ->with('bookingDetail', $bookingDetail);

view



Error I'm Getting

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'clients.id' in 'where clause' (SQL: select * from clients where clients.id in (3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17))

Is this the right way to do it? or am I missing something. I'm new to laravel so I don't know if this is the right way to do it



via Chebli Mohamed

Database structure for categories, sub-categories, and services

I am using Laravel 5.5 and MySql. I cannot figure out how to relate Categories, and Sub Categories to Services without adding a subCategoryID column to the Services table.

Currently this is my table structure

Service_Categories

id, name
1, Legal Services
2, Personal Drivers

Service_Sub_Categories

id, ServiceCategoryID, name
1, 1, US Legal Services
2, 1, Europe Legal Services
3, 1, Canada Legal Services

Services

id, serviceCategoryID, name
1, 1, US Legal Services Comapny INC
2, 1, Canada Legal Services Company INC
3, 2, JSY Personal Drivers
4, 2, XYZ Personal Drivers

One service must have at least 1 Service Category but it can also have 0 or more Sub-Categories

As you can see, Personal Drivers has no sub-category, but Legal Services has many Sub-Categories. When a user selects "US Legal Services" I only want to pull those up. I could easily add a subCategoryID column to the Services table but in the future I may have sub-sub-categories. What is the best way to structure my tables?



via Chebli Mohamed

How can I update user password in Laravel 5 ?

I use Laravel 5.7.

I'm trying to update one my users password

I ran this php artisan tinker

Then

>>> bcrypt(12345);                                                                                                
=> "$2y$10$5woTm5/1w.euUliNCujmMu.oYiC.U8YnRpBHVQN/CxyKXAYB.pGiS"                                                 
>>> 

I copied the hash update that into my database

I tried to login with 12345. I can't log in.

What did I forget to do ?


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

Making datasize change to each images dimensions

I am using photo swipe and laravel and bringing in images to the photoswipe gallery by a foreach. With photoswipe you have to define data-size and i am unsure on how i set this to define the size automatically. At the moment i have it predefined and its stretching small images and shrinking bigger images. Has anyone had any experience with this and the photoswipe plugin and managed to define it automatically foreach loaded images dimensions?

Here is the code that includes the data-size definition:

   <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject" >

     <a href="" itemprop="contentUrl" data-size="1200x600">
     <img src="" itemprop="thumbnail" alt="Userimage"  />
     </a>

    <figcaption itemprop="caption description">Uploaded by: , </figcaption>


   </figure>



via Chebli Mohamed

How to generate a hash password for Laravel project?

I'm using Laravel.I want to update the password of one of my users.

enter image description here

I tried went to this site : https://bcrypt-generator.com/

entered: 12345 as click Hash, then I got

$2y$12$I4R0XT4iE742UWQzAzIUf.nLQA8oQhekEl16.p4oqhqBqg5nZQLb2

I then copied the resulting hash and paste it into my database column.

enter image description here

Then try to log-in, still can't seems to log in

enter image description here


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

Sort Collection By id set

I have an array of ids that i want to sort a given column by them in the collection.

For example,

$suppliersOrder = [8,7,5,1,3,4];

$items = Items::get()->sortBy(function($model) use ($suppliersOrder) {
   return array_search($model->supplier_id, $suppliersOrder);
})->values();

This acts like ordering items as [1,3,4,5,7,8] instead of the given order. And if I try sortByDesc, likewise [8,7,5,4,3,1] but I couldn't figure out the way to actually sort them as my given array's order.

My ultimate goal is then running $items->groupBy('supplier.name') so I can have my desired order.



via Chebli Mohamed

how to perform an advanced search with scopequery

It is desired to be able to search for a specific charge, where when performing the search as the Coro Commission, all the members that belong to that position appear.

The code of sight:

@foreach ($ members as $ member)

                
                
                
                
                @if (empty ($ member-> formations-> fType))

                @else
               
               @endif

                @foreach ($ member-> charges as $ charge)

                        

                  @endforeach

            @endforeach

There is a table of parish members and positions, with many to many among them. The intermediate table has the name: cargo_membership_parish

The following is in the controller.

public function filters (Request $ request) {

  $ sector = $ request-> input ('sector');
  $ form = $ request-> formacion_id;
  $ stages = Stage :: all ();
  $ formation = Training :: all ();
  $ stage = $ request-> stage_id;
  $ charge = Charge :: all ();
  $ m_cargo = $ request-> car;
    $ members = Member_Parroquial :: orderBy ('id', 'DESC') -> sector ($ sector) -> stage ($ stage) -> training ($ form) -> get ();

  return view ('member.member_index', compact ('stages', 'formation', 'members', 'position'));

}

The SCOPEQUERY have been made in the following way:

public function scopeEtapa ($ query, $ stage) {

    if ($ stage) {

        return $ query-> where ('stage_id', 'LIKE', "% $ stage%");
    }
}

public function scopeFormation ($ query, $ form) {

    if ($ form) {
        return $ query-> where ('training_id', 'LIKE', "% $ form%");

    }
}

public function scopeCharge ($ query, $ charge) {

}

If you have an idea of ​​how to perform the scope query for charges in relation to many to many, it would be very helpful. Thank you



via Chebli Mohamed

Chunked file uploads with Laravel & AJAX

I try to create a script to upload large files, I send data through Ajax (It's work), but this did not solve the problem of large files, in the best circumstances, I can upload only 100 MB, and this is not good for the user, can you help me to add Chunked file uploads, Thank you

This is my HTML:

<form id="upload_form" method="POST" enctype="multipart/form-data">
 @csrf
 <input type="file" name="file" id="file-7" class="inputfile inputfile-6" />
<center>
   <a href="#" id="star_up" value="hide/show">
      <input class="btn btn-info btn-lg wow tada" id="sell_house_submit" type="submit" name="upload_file" value="@lang('lang.UPLOAD')">
   </a>
</center>
<div id="prog" style="display:none;">
    <progress id="progressBar" class="wow tada" style="@if(isMobile())width:200px;@else width:750px;@endif height: 10px;" value="0" max="100">
    </progress>
    <h3 class="av" id="status" ></h3>
    <p id="loaded_n_total" ></p>

My javascript:

$(document).ready(function(){

 $('#upload_form').on('submit', function(event){
   $.ajax({
   url:"",
   method:"POST",
   data: new FormData(this),
   xhr: function() {
        var myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){
            myXhr.upload.addEventListener('progress',progressHandler, false);
            myXhr.addEventListener("load", completeHandler, false);
            myXhr.addEventListener("error", errorHandler, false);
            myXhr.addEventListener("abort", abortHandler, false);
        }
        return myXhr;
    },
   dataType:'JSON',
   contentType: false,
   cache: false,
   processData: false,
   // IF SUCCESS
   success:function(data)
   {
      if (data.type_is == 'swal') {
        swal({
            title: data.title,
            html: data.html,
            showCloseButton: true,
            focusConfirm: false,
            type: data.status
        });
        jQuery('#progress_up').toggle('hide');
        document.getElementById('file-7').value = '';
        document.getElementById('name_file').innerHTML = '';
      } 
   }
  })
    event.preventDefault();
 });

});

Controller:

protected function upload(Request $request) {
  ini_set('max_execution_time', 3000);
  ini_set('memory_limit','256M');

  // UPLOAD FILE
  if (getValue('storage_type', 'disk') == 's3') {
     $path = Storage::disk('s3')->putFile('files', $request->file('file'));
     $storage = 's3';
  } else {
  $path = Storage::putFile('files', $request->file('file'));
  $storage = 'disk';
  }
  // RANDOM
  $link_id = Random();
  $delete_token = Random(50);
  $preview = Random(10);
  $ip = getip();

  $this->createFile($name, $path, $link_id, $delete_token, $ip, $preview, $size, $mime, $type, $storage);

  // FILE UPLOADED

  return response()->json([
     'title' => trans('lang.GREAT'),
     'html' => getFileInfoHTML($link_id, $delete_token, $name, $type, $preview),
     'type_is' => 'swal',
     'status' => 'success'
  ]);
}

I put the most important things only, I did not put the details of the file review and size ...., I just want to know how I can add the property and upload files without a large RAM :)



via Chebli Mohamed

all value is not inserted in my database (laravel-5.7)

I trying to insert value into database by form in laravel but my all value's is not inserted .
..insert only email,password,created_date
Here is my code of migration :-

    Schema::defaultStringLength(191);
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('fname');
        $table->string('lname');
        $table->string('email')->unique();
        $table->string('phone');
        $table->string('gender');
        $table->string('dob');
        $table->string('religion');
        $table->string('mtn');
        $table->string('country');
        $table->string('city');
        $table->string('district');
        $table->string('upozila');
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });


here is code of controller :-

public function register(Request $request)
{
    $this->validation($request);
    User::create($request->all());
    return redirect('/');
}

public function validation($request)
{
    $validatedData = $request->validate([
    'fname' => 'required|max:255',
    'lname' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users,email',
    'phone' => 'required|max:255',
    'gender' => 'required|max:255',
    'dob' => 'required|max:255',
    'religion' => 'required|max:255',
    'mtn' => 'required|max:255',
    'country' => 'required|max:255',
    'city' => 'required|max:255',
    'district' => 'required|max:255',
    'upozila' => 'required|max:255',
    'password' => 'required|min:6',
    'confirm_password' =>'required|min:6|same:password',

]);

}


here is my array = $request->all(); :

_token "wDRoDeLkOFX5re5nba2Ufv5pr0iKzYVCr0tK9EFE"
fname "nirab"
lname "nirax"
email "is@gmail.com"
phone "988907"
gender "male"
dob "2018-12-03"
religion "male"
mtn "male"
country "male"
city "male"
district "male"
upozila "male"
password "1234567"
confirm_password "1234567"



via Chebli Mohamed

Laravel - return data group by month(and sum) and group by year

I have this function below, which i got to it thanks to the help of everyone in this question:

$records = TabelaAngariacao::select('preco', 'created_at')
            ->where('estado', '=', 'Vendido')
            ->get()
            ->groupBy(function($date) {
                return Carbon::parse($date->created_at)->format('m');
            })->transform(function ($value) { //it can also be map()

                $nStr = $value->map(function ($vl) {
                    return str_replace(".", "", $vl->preco);
                });
                return [
                    'preco_sum' => $nStr->sum()
                ];
            });

...this function is great, i had a problem because i´m saving the preco(prices) has varchar(which is wrong), but by using map i´m able to sum, and everything is working great giving me the result below:

10: {preco_sum: 160000}
11: {preco_sum: 220000}
12: {preco_sum: 1175000}

I have the months and the sum of them...but...then i realize i need to have the same thing but also related to the year, so i tried this:

return Carbon::parse($date->created_at)->format('Y-m');

which leads me to this result:

"2018-10" => array:1 [▶]
"2018-11" => array:1 [▶]
"2018-12" => array:1 [▶]
"2019-01" => array:1 [▶]

but how do i filter this by year on the client side?. I´m using chartjs, so one line should be all the months sumed OF 2018 and the same for 2017 for example.

Thanks for your time, regards



via Chebli Mohamed

laravel multi forms route

everybody, I have a multi form on the same page and same route all things are working fine but only last form is working

   Route::post('user/{user}/settings', 'UserController@Update_info');
   Route::post('user/{user}/settings', 'UserController@SaveSettings');
   Route::post('user/{user}/settings', 'UserController@Update_security');

So if I need SaveSettings I must change it to

Route::post('user/{user}/settings', 'UserController@Update_info');
Route::post('user/{user}/settings', 'UserController@SaveSettings');
Route::post('user/{user}/settings', 'UserController@Update_security');



via Chebli Mohamed

jeudi 27 décembre 2018

laravel Unable to load datatable js in ajax blade page

I need to filter the datatable object for that i am using datatable jquery. But its not working

I am using laravel 5.6 version , I added a new blade for my datatable filter. but its not filtering the datatable results.

I am getting the datatable result through AJAX. Needed a solution for filtering.

ajax blade code:
<div class="container-fluid page-body-wrapper">
      <div class="main-panel">
        <div class="content-wrapper">
          <div class="card">
            <div class="card-body">
              <h4 class="card-title">Data table</h4>
              <div class="row">
                <div class="col-12">
                  <div class="table-responsive">
                    <table id="order-listing" class="table">
                      <thead>
                        <tr>
                            <th>Name</th>
                            <th>Quantity</th>
                            <th>Price</th>
                            <th>SKU</th>
                            <th>Weight</th>
                            <th>Status</th>
                            <th>Seller Price</th>
                            <th>Action</th>
                        </tr>
                      </thead>
                      <tbody>
                        @foreach ($result as $data)
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td>      
                            <a class="btn btn-primary" href="">Edit</a>
                            </td>
                        </tr>
                        @endforeach

                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- content-wrapper ends -->

      </div>
      <!-- main-panel ends -->
    </div>

jquery code:

(function($) {
  'use strict';
  $(function() {
    $('#order-listing').DataTable({
      "aLengthMenu": [
        [5, 10, 15, -1],
        [5, 10, 15, "All"]
      ],
      "iDisplayLength": 10,
      "language": {
        search: ""
      }
    });
    $('#order-listing').each(function() {
      var datatable = $(this);
      // SEARCH - Add the placeholder for Search and Turn this into in-line form control
      var search_input = datatable.closest('.dataTables_wrapper').find('div[id$=_filter] input');
      search_input.attr('placeholder', 'Search');
      search_input.removeClass('form-control-sm');
      // LENGTH - Inline-Form control
      var length_sel = datatable.closest('.dataTables_wrapper').find('div[id$=_length] select');
      length_sel.removeClass('form-control-sm');
    });
  });
})(jQuery);

I expect the output with filtered datatable.



via Chebli Mohamed

In Lumen REST API framework request is showing pending on front-end side after hitting API

Need to restart API server each time after this problem occurs. After restarting the APIs is working fine.



via Chebli Mohamed

Laravel Amazon S3 package suddenly stopped working

I've been using this code forever:

  private function pushToS3($photo)
  {
    return $this->s3->putObject([
      'Bucket'        => $this->bucket,
      'Key'           => $photo->path,
      'ContentType'   => $this->fileInfo['mimetype'],
      'ContentLength' => filesize($this->tempFileName),
      'SourceFile'    => $this->tempFileName
    ]);
  }

All of a sudden, my queue is kicking out lots of errors about the files not matching and I have no idea how to fix it. This is the stack trace. Is anybody else having this issue suddenly with the "? If so, what did you do to solve it?

The error is: The provided 'x-amz-content-sha256' header does not match what was computed.

exception 'Aws\S3\Exception\S3Exception' with message 'Error executing "PutObject" on "https://real-estate-listings.s3.amazonaws.com/naples/prestwick-place-at-lely-resort/217006408/0.jpg"; AWS HTTP error: Client error: `PUT https://real-estate-listings.s3.amazonaws.com/naples/prestwick-place-at-lely-resort/217006408/0.jpg` resulted in a `400 Bad Request` response:
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>XAmzContentSHA256Mismatch</Code><Message>The provided 'x-amz-content (truncated...)
 XAmzContentSHA256Mismatch (client): The provided 'x-amz-content-sha256' header does not match what was computed. - <?xml version="1.0" encoding="UTF-8"?>
<Error><Code>XAmzContentSHA256Mismatch</Code><Message>The provided 'x-amz-content-sha256' header does not match what was computed.</Message><ClientComputedContentSHA256>b14142ad250f999738ffb58372fc2022ded3faca2a4fd12ad2110df6889affce</ClientComputedContentSHA256><S3ComputedContentSHA256>fd657de6b5f5e3137de3a44e41358eb53f28878d1026e26a506386364d4144e1</S3ComputedContentSHA256><RequestId>CC785BA3A416CE14</RequestId><HostId>k3lstjw0kT3mTcfHgeYmuZsvtYGwAfaBmyrDnai1KrWuePeZPnDN8iyFbdINr4sVbD8xtxP0+Gk=</HostId></Error>'

GuzzleHttp\Exception\ClientException: Client error: `PUT https://real-estate-listings.s3.amazonaws.com/naples/prestwick-place-at-lely-resort/217006408/0.jpg` resulted in a `400 Bad Request` response:
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>XAmzContentSHA256Mismatch</Code><Message>The provided 'x-amz-content (truncated...)
 in /srv/www/listingnaples.com/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113
Stack trace:
#0 /srv/www/listingnaples.com/vendor/guzzlehttp/guzzle/src/Middleware.php(66): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
#1 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))
#2 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array)
#3 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/TaskQueue.php(47): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise\{closure}()
#4 /srv/www/listingnaples.com/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php(98): GuzzleHttp\Promise\TaskQueue->run()
#5 /srv/www/listingnaples.com/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php(125): GuzzleHttp\Handler\CurlMultiHandler->tick()
#6 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(246): GuzzleHttp\Handler\CurlMultiHandler->execute(true)
#7 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(223): GuzzleHttp\Promise\Promise->invokeWaitFn()
#8 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(267): GuzzleHttp\Promise\Promise->waitIfPending()
#9 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(225): GuzzleHttp\Promise\Promise->invokeWaitList()
#10 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(267): GuzzleHttp\Promise\Promise->waitIfPending()
#11 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(225): GuzzleHttp\Promise\Promise->invokeWaitList()
#12 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(62): GuzzleHttp\Promise\Promise->waitIfPending()
#13 /srv/www/listingnaples.com/vendor/aws/aws-sdk-php/src/AwsClientTrait.php(58): GuzzleHttp\Promise\Promise->wait()
#14 /srv/www/listingnaples.com/vendor/aws/aws-sdk-php/src/AwsClientTrait.php(77): Aws\AwsClient->execute(Object(Aws\Command))
#15 /srv/www/listingnaples.com/app/Models/PhotoProcessor.php(172): Aws\AwsClient->__call('putObject', Array)
#16 /srv/www/listingnaples.com/app/Models/PhotoProcessor.php(67): App\Models\PhotoProcessor->pushToS3(Object(App\Models\RetsPhoto))
#17 /srv/www/listingnaples.com/app/Models/ListingMigrator.php(86): App\Models\PhotoProcessor->process()
#18 /srv/www/listingnaples.com/app/Models/ListingMigrator.php(32): App\Models\ListingMigrator->processPhotos()
#19 /srv/www/listingnaples.com/app/Models/ListingMigrator.php(22): App\Models\ListingMigrator->migrate()
#20 /srv/www/listingnaples.com/app/Jobs/ProcessListing.php(44): App\Models\ListingMigrator::migrateListing(Object(App\Models\TempListingNaples), Object(App\Models\RetsFeed))
#21 [internal function]: App\Jobs\ProcessListing->handle()
#22 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#23 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#24 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#25 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(572): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#26 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container->call(Array)
#27 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\Bus\Dispatcher->Illuminate\Bus\{closure}(Object(App\Jobs\ProcessListing))
#28 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(App\Jobs\ProcessListing))
#29 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#30 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(49): Illuminate\Bus\Dispatcher->dispatchNow(Object(App\Jobs\ProcessListing), false)
#31 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(83): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\SqsJob), Array)
#32 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(327): Illuminate\Queue\Jobs\Job->fire()
#33 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(277): Illuminate\Queue\Worker->process('sqs', Object(Illuminate\Queue\Jobs\SqsJob), Object(Illuminate\Queue\WorkerOptions))
#34 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(118): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\SqsJob), 'sqs', Object(Illuminate\Queue\WorkerOptions))
#35 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(102): Illuminate\Queue\Worker->daemon('sqs', 'ImportQueue', Object(Illuminate\Queue\WorkerOptions))
#36 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(86): Illuminate\Queue\Console\WorkCommand->runWorker('sqs', 'ImportQueue')
#37 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#38 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#39 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#40 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#41 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(572): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#42 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
#43 /srv/www/listingnaples.com/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#44 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#45 /srv/www/listingnaples.com/vendor/symfony/console/Application.php(901): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#46 /srv/www/listingnaples.com/vendor/symfony/console/Application.php(262): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#47 /srv/www/listingnaples.com/vendor/symfony/console/Application.php(145): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#48 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Console/Application.php(89): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#49 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#50 /srv/www/listingnaples.com/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#51 {main}

Next Aws\S3\Exception\S3Exception: Error executing "PutObject" on "https://real-estate-listings.s3.amazonaws.com/naples/prestwick-place-at-lely-resort/217006408/0.jpg"; AWS HTTP error: Client error: `PUT https://real-estate-listings.s3.amazonaws.com/naples/prestwick-place-at-lely-resort/217006408/0.jpg` resulted in a `400 Bad Request` response:
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>XAmzContentSHA256Mismatch</Code><Message>The provided 'x-amz-content (truncated...)
 XAmzContentSHA256Mismatch (client): The provided 'x-amz-content-sha256' header does not match what was computed. - <?xml version="1.0" encoding="UTF-8"?>
<Error><Code>XAmzContentSHA256Mismatch</Code><Message>The provided 'x-amz-content-sha256' header does not match what was computed.</Message><ClientComputedContentSHA256>b14142ad250f999738ffb58372fc2022ded3faca2a4fd12ad2110df6889affce</ClientComputedContentSHA256><S3ComputedContentSHA256>fd657de6b5f5e3137de3a44e41358eb53f28878d1026e26a506386364d4144e1</S3ComputedContentSHA256><RequestId>CC785BA3A416CE14</RequestId><HostId>k3lstjw0kT3mTcfHgeYmuZsvtYGwAfaBmyrDnai1KrWuePeZPnDN8iyFbdINr4sVbD8xtxP0+Gk=</HostId></Error> in /srv/www/listingnaples.com/vendor/aws/aws-sdk-php/src/WrappedHttpHandler.php:191
Stack trace:
#0 /srv/www/listingnaples.com/vendor/aws/aws-sdk-php/src/WrappedHttpHandler.php(100): Aws\WrappedHttpHandler->parseError(Array, Object(GuzzleHttp\Psr7\Request), Object(Aws\Command), Array)
#1 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(203): Aws\WrappedHttpHandler->Aws\{closure}(Array)
#2 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(174): GuzzleHttp\Promise\Promise::callHandler(2, Array, Array)
#3 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/RejectedPromise.php(40): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise\{closure}(Array)
#4 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/TaskQueue.php(47): GuzzleHttp\Promise\RejectedPromise::GuzzleHttp\Promise\{closure}()
#5 /srv/www/listingnaples.com/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php(98): GuzzleHttp\Promise\TaskQueue->run()
#6 /srv/www/listingnaples.com/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php(125): GuzzleHttp\Handler\CurlMultiHandler->tick()
#7 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(246): GuzzleHttp\Handler\CurlMultiHandler->execute(true)
#8 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(223): GuzzleHttp\Promise\Promise->invokeWaitFn()
#9 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(267): GuzzleHttp\Promise\Promise->waitIfPending()
#10 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(225): GuzzleHttp\Promise\Promise->invokeWaitList()
#11 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(267): GuzzleHttp\Promise\Promise->waitIfPending()
#12 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(225): GuzzleHttp\Promise\Promise->invokeWaitList()
#13 /srv/www/listingnaples.com/vendor/guzzlehttp/promises/src/Promise.php(62): GuzzleHttp\Promise\Promise->waitIfPending()
#14 /srv/www/listingnaples.com/vendor/aws/aws-sdk-php/src/AwsClientTrait.php(58): GuzzleHttp\Promise\Promise->wait()
#15 /srv/www/listingnaples.com/vendor/aws/aws-sdk-php/src/AwsClientTrait.php(77): Aws\AwsClient->execute(Object(Aws\Command))
#16 /srv/www/listingnaples.com/app/Models/PhotoProcessor.php(172): Aws\AwsClient->__call('putObject', Array)
#17 /srv/www/listingnaples.com/app/Models/PhotoProcessor.php(67): App\Models\PhotoProcessor->pushToS3(Object(App\Models\RetsPhoto))
#18 /srv/www/listingnaples.com/app/Models/ListingMigrator.php(86): App\Models\PhotoProcessor->process()
#19 /srv/www/listingnaples.com/app/Models/ListingMigrator.php(32): App\Models\ListingMigrator->processPhotos()
#20 /srv/www/listingnaples.com/app/Models/ListingMigrator.php(22): App\Models\ListingMigrator->migrate()
#21 /srv/www/listingnaples.com/app/Jobs/ProcessListing.php(44): App\Models\ListingMigrator::migrateListing(Object(App\Models\TempListingNaples), Object(App\Models\RetsFeed))
#22 [internal function]: App\Jobs\ProcessListing->handle()
#23 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#24 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#25 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#26 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(572): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#27 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container->call(Array)
#28 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\Bus\Dispatcher->Illuminate\Bus\{closure}(Object(App\Jobs\ProcessListing))
#29 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(App\Jobs\ProcessListing))
#30 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#31 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(49): Illuminate\Bus\Dispatcher->dispatchNow(Object(App\Jobs\ProcessListing), false)
#32 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(83): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\SqsJob), Array)
#33 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(327): Illuminate\Queue\Jobs\Job->fire()
#34 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(277): Illuminate\Queue\Worker->process('sqs', Object(Illuminate\Queue\Jobs\SqsJob), Object(Illuminate\Queue\WorkerOptions))
#35 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(118): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\SqsJob), 'sqs', Object(Illuminate\Queue\WorkerOptions))
#36 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(102): Illuminate\Queue\Worker->daemon('sqs', 'ImportQueue', Object(Illuminate\Queue\WorkerOptions))
#37 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(86): Illuminate\Queue\Console\WorkCommand->runWorker('sqs', 'ImportQueue')
#38 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#39 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#40 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#41 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#42 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(572): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#43 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
#44 /srv/www/listingnaples.com/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#45 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#46 /srv/www/listingnaples.com/vendor/symfony/console/Application.php(901): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#47 /srv/www/listingnaples.com/vendor/symfony/console/Application.php(262): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#48 /srv/www/listingnaples.com/vendor/symfony/console/Application.php(145): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#49 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Console/Application.php(89): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#50 /srv/www/listingnaples.com/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#51 /srv/www/listingnaples.com/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#52 {main}



via Chebli Mohamed