mardi 3 mars 2020

Laravel command "__construct" has a parameter but where does it come from?

The vendor's code looks like this:

/**
 * Create a new SendEmailsCommand instance.
 *
 * @param Store $store
 */
public function __construct(Store $store)
{
    parent::__construct();

    $this->store = $store;
}

But when I invoke this command with say php artisan mail:send, where does the value of $store come from? Is this what is meant by this cryptic documentation quote?

Note that we are able to inject any dependencies we need into the command's constructor. The Laravel service container will automatically inject all dependencies type-hinted in the constructor.

I see that Laravel (5.2) documentation on console commands seems to do a similar thing with an object called Drip ... https://laravel.com/docs/5.2/artisan#command-structure

Is Laravel taking upon itself to realize that there's a type-name given to the constructor, and it automagically instantiates a corresponding object instead of expecting your constructor to do so itself?



via Chebli Mohamed

Post API breaks with long parameter values

I have a Laravel 5.7 backend that receives API calls generally fine. However I am trying to pass a long base64 string as a post request (testing in postman) and strange things are happening.

Post URL is: http://localhost:8000/api/group/uploadGroupImage?group_id=1&input_img=data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAIQAABtbnRy... (Abbreviated )

No Specific headers set apart from authentication

If the length of the input_img value is short the post works fine. However if it's more than about 15,000 characters, the response from laravel is:

"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"file": "/Users/myuser/Sites/laravel/fxdoc/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
"line": 179,

And if the string gets up to more than 100,000 characters then I get (in postman):

Could not get any response
There was an error connecting to http://localhost:8000/api/group/uploadGroupImage?group_id=1&input_img=data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAIQAABtbnRy... (Abbreviated )
Why this might have happened:
The server couldn't send a response:
Ensure that the backend is working properly
Self-signed SSL certificates are being blocked:
Fix this by turning off 'SSL certificate verification' in Settings > General
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General

(this can be the response within a few seconds sometimes)

In postman I've turned off all proxy and SSL options (Backend is definitely working as it works for short values) and timeout is set to 0 (no timeout)

Can anyone help me? Literally the only difference between it working and breaking is the length of the parameter value.



via Chebli Mohamed

Laravel inline if statement in select

I would like to know if it is possible to add an inline if statement in Laravel's form select element

I am able to do it this way:

<select>
<option value="1">One</option>
<option value="2">Two</option>
{!! $variable=='Hello'?'<option value="3">Three</option>':'' !!}
</select>

But I would like to know if there is a way similar to this:

{!! Form::select('action',array('1'=>'One','2'=>'Two',@if($variable=='Hello') '3'=>'three' @endif),null,['class'=>'form-control']) !!}


via Chebli Mohamed

Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_1_::make

I have written this test that is returning the following error:

Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_1_My_Class::make(array('valid_until'=>'2020-03-04',)). Either the method was unexpected or its arguments matched no expected argument list for this method

Now I have this code in my test:

$rateValidator->shouldReceive('make')->once()
            ->withArgs([$attributes])->andReturn(mockery::self());

$rateValidator->shouldReceive('addContext')
            ->withArgs(['update_rate_validity'])->andReturn(mockery::self());

And This is the code this test is testing:

$attributes = [
    'valid_until' => $command->validUntilDate
];

$validator = $this->rateValidator->make($attributes)->addContext('update_rate_validity');

What am I doing wrong here? For me the only problem could be in the arguments ($attributes) that the method make is receiving but I cant figure out what that could be?



via Chebli Mohamed

How can i put more details into GeoChart (lavacharts)

What Version?

Run composer show khill/lavacharts if you don't know Version 3.1

Issue

Please describe the issue.

Hi, I'm trying to do a geo chart with LavaCharts, and I wanted to add more columns. Like I would like to have Country, Users, Description, Etc. (another column from the database). I did some code but when I refresh my page appears without the 'Country' label/text

the blade view, here you can see how my data/columns from database are, missing Country, and the description doesn't have a column, it just appears as a label.

Controller Code (chart creation code)
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Khill\Lavacharts\Lavacharts;
use App\Visitor;
class VisitorController extends Controller
{
    public function index(){
        $lava = new Lavacharts;

        $data = Visitor::select( "country as -1","description as 0","users as 1")->get()->toArray();



        $popularity= $lava->DataTable()
                    ->addStringColumn("Country")    
                    ->addStringColumn("Description")  
                    ->addNumberColumn("Users    ")      
                    ->addRows($data);

        $lava->GeoChart("Popularity", $popularity);

        return view("visitor",["lava"=>$lava]);
    }
}

(Controller)

Model
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Visitor extends Model
{
    protected $fillable=['country','description','users'];
}

(Model)


blade: 
`
<div  id="visitor" style="width:80%;margin:0 auto;"></div>
<?=$lava->render("GeoChart","Popularity","visitor");?>
`
web.php:
` Route::get('/visitor', 'VisitorController@index')->name('visitor');`






If i do something like this :

  $popularity = $lava->DataTable();

            $popularity->addStringColumn('Country')
                ->addNumberColumn('Popularity')
                ->addStringColumn('Desc')
                ->addRow(array('Germany', 200,'asdad'))
                ->addRow(array('United States', 300,'asdad'))
                ->addRow(array('Brazil', 400,'asdad'))
                ->addRow(array('Canada', 500,'asdad'))
                ->addRow(array('France', 600,'asdad'))
                ->addRow(array('RU', 700,'asdad'));

The error is: Incompatible data table: Error: Table contains more columns than expected (Expecting 2 columns)×


via Chebli Mohamed

lundi 2 mars 2020

Laravel Token in create

I'm building a user management system...

when I create a user and put an image in 'avatar field' the user will create successfully

but when I let 'avatar field' empty he show me Token and the data that I insert in the field

I already put @csrf in my form

{
    "_token":"f8UnQweYC4xR6WahdsUDlFGoGxyuyzm61rpBEXXXX",
    "_method":"post",
    "email":"example@abc.xyz",
    "name":"example",
    "password":"123456789"
}

Store Method

    public function store(Request $request)
{
    $this->validate($request, array(
        'name'         => 'required|string|max:255',
        'email'          => 'required|string|email|max:255|unique:users',
        'password'          => 'required|string|min:8',
    ));
    $password = Hash::make($request->password);
    $user = new User;
    $user->name = $request->input('name');
    $user->email = $request->input('email');
    $user->password = $password;
    $user->roles()->detach();
    if ($request['user']) {
        $user->roles()->attach(Role::where('name','User')->first());
    }
    if ($request['editor']) {
        $user->roles()->attach(Role::where('name','Editor')->first());
    }
    if ($request['admin']) {
        $user->roles()->attach(Role::where('name','Admin')->first());
    }
    if($request->hasFile('avatar')){
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();
        Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );

    } else {
        return $request;
        $user->avatar = '';
    }
    $user->save();
    return view('content.admin.user.index');
}


via Chebli Mohamed

Laravel don't show errors like model path wrong

I update Laravel to version 6.8 from 5.5 and some errors stop to show, like when you write the namespace wrong or something in model instead show only timeout error, I think this is something related about whoops and ignition I changed too the errors interface whoops to ignition

Here my composer

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": [
    "framework",
    "laravel"
],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=7.2.5",
    "barryvdh/laravel-dompdf": "^0.8.5",
    "davejamesmiller/laravel-breadcrumbs": "^5.3",
    "fideloper/proxy": "^4.2",
    "guzzlehttp/guzzle": "^6.3",
    "laravel/framework": "^6.8",
    "laravel/helpers": "^1.1",
    "laravel/telescope": "^2.1",
    "laravelcollective/html": "^6.0",
    "maatwebsite/excel": "^3.1",
    "rap2hpoutre/fast-excel": "^1.6",
    "spatie/laravel-permission": "^3.0",
    "yajra/laravel-datatables-oracle": "^9.6"
},
"require-dev": {
    "barryvdh/laravel-debugbar": "^3.2",
    "composer/composer": "^1.8",
    "facade/ignition": "^1.6",
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~6.0",
    "spatie/laravel-web-tinker": "^1.5"
},
"autoload": {
    "files": [
        "app/Helpers/helper.php"
    ],
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"extra": {
    "laravel": {
        "dont-discover": []
    }
},
"scripts": {
    "post-root-package-install": [
        "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "@php artisan key:generate"
    ],
    "post-autoload-dump": [
        "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
        "@php artisan package:discover"
    ]
},
"config": {
    "preferred-install": "dist",
    "sort-packages": true,
    "optimize-autoloader": true
}

}



via Chebli Mohamed