vendredi 1 mars 2019

Laravel application problem on Ubuntu 18.04.2 LTS‬ with Plesk Onyx 17.8.11 Update Nr. 42

I have got a vserver with Ubuntu 18.04.2 LTS‬ and Plesk Onyx 17.8.11 Update Nr. 42 and PHP 7.2 FastCGI Process Manager (PHP 7.2.15 by OS vendor).

On that server I have installed a Laravel 5.7 application. In Plesk, the domain for that particular website points to a directory httpdocs/public (/var/www/vhosts/domain.tld/httpdocs/public) underneath the associated website. I only have that one domain with two other subdomains registered in Plesk.

From time to time it happens that my website is not reachable anymore. In the error_log (found in /var/www/vhosts/domain.tld/logs) there is just the following error

[date] [proxy_fcgi:error] [pid 24975:tid 140420147222272] (70007)The timeout specified has expired: [client xxx] AH01075: Error dispatching request to : (polling)

I took a look at other log files. But nothing relevant in there.

When I let Plesk point the domain to the directory httpdocs only and I create a file with name index.php in that directory (root directory of my Laravel installation), that particular file will be shown for the domain.

After that I let Plesk again point to directory httpdocs/public. Now, the website is available again!

What is going on here? Do you have any hints for me to do such that this strange behavior does not appear anymore?

Thanks a lot in advance.



via Chebli Mohamed

Need to insert i products table from more than one tables with dynamic id

I have 3 tables users, products and temp_table. i have imported an xlsx file having 1,00,000 records in to temp_table. now i have to insert these records to products table. and here i have to save user_id from users table to products table as well. Note: user_id is dynamic(i.e. in xlsx file there is a column called email and I have created a new user for their email). so in products table user_id will be dynamically inserted. I have used below query, but it is taking too much time. and sometimes my MySQL get locked.

INSERT INTO products
        (user_id,
        brand_id,
        points_discount,
        amount,
        sub_total,
        added_on)
        SELECT users.user_id, 
            brand_id,
            discount,
            amount,
            sub_total,
            added_on
        FROM temp_table
        INNER JOIN users 
        ON email = users.email;



via Chebli Mohamed

laravel route prefix not redirect properly

What wrong with this code ?

Auth::routes();
Route::get('/',function (){
    return redirect('admin');
});
Route::get('login', ['as' => '/', 'uses' =>'Web\AuthController@showLoginPage']);
Route::get('register', ['as' => '/', 'uses'=>'Web\AuthController@showLoginPage']);
Route::prefix('admin')->group(function (){
    Route::get('/','Web\AuthController@showLoginPage');
});

When I try to hit http://localhost/restaurant/ it redirects me to http://localhost/restaurant/admin which is fine but the problem is on this url it says :

** Not Found The requested URL /restaurant/admin was not found on this server. **



via Chebli Mohamed

I get a 404 error when he should not :laravel

I developed an API and I have a problem whith this page I add it in my route and always I get a 404 error I don't know why

this my controller:

class InsertPPictureController extends Controller
{
    public function profilepicture (Request $request)
    {
        $input = $request->all();

        $validator =    Validator::make($input, [
            'id_user'=> 'required',
            'picture'=> 'image|nullable|max:1999'
        ] );

        $user = User::findOrFail($request->id);
        $user_id = $request->id ;

        if($request->hasFile('picture')){
            // Get filename with the extension
            $filenameWithExt = $request->file('picture')->getClientOriginalName();
            // Get just filename
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            // Get just ext
            $extension = $request->file('picture')->getClientOriginalExtension();
            // Filename to store
            $fileNameToStore= $user_id.'.'.$extension;
            // Upload Image
            $path = $request->file('picture')->storeAs('public/profilepic', $fileNameToStore);
            $user->pic_path = $fileNameToStore ;
            $user->update();


        } else {
            $fileNameToStore = 'noimage';
        }

        return response()->json(' Success : User updated with success ',200);
    }
}

and this is my api.php

Route::group(['middleware' => ['jwt.verify']], function() {
    Route::get('logout', 'AuthController@logout');
    Route::post('postcreditscards', 'CreditsCardsController@stockcards');
    Route::get('getcreditscards', 'CreditsCardsController@index');
    Route::get('getmybalance', 'MyBalanceController@index');
    Route::get('getuserdata', 'AuthController@getuser');
    Route::post('sendMoneyTransaction', 'MyBalanceController@updatebalance');
    Route::post('isvalidnumber', 'AuthController@validnumber');
   Route::post('updateuser', 'AuthController@updateuser');
     Route::post('insertprofilepicture','InsertPPictureController@profilepicture');

});

all the pages work fine only this page don't work Route::post('insertprofilepicture','InsertPPictureController@profilepicture');



via Chebli Mohamed

WhereHas not works as expected - Polymorphic many to many relation

I'm trying to build a filter query but when I filter using whereHas method it returns extremely odd results.

when($request->has("brand", function($q) use ($request) {
   $q->whereHas("tags", function ($q) use ($request) {
        $q->where("tags.id", $request->brand); # brand id
   });
}))

Here is sql result if I filter only by brand (by tag)

select `products`.`id`, `products`.`title`, `products`.`slug`, `products`.`price` from `products` 
where exists (select * from `tags` inner join `taggables` on `tags`.`id` = `taggables`.`tag_id` 
where `products`.`id` = `taggables`.`taggable_id` 
and `taggables`.`taggable_type` = 'App\Models\Product' and `tags`.`id` = '10');

It returns couple result but doesn't relevant with above query. Results even have not same brand.

But when I send brand name instead id and change query like $q->where("tags.name", $request->brand); # brand name, it working as well

select `products`.`id`, `products`.`title`, `products`.`slug`, `products`.`price` from `products` 
where exists (select * from `tags` inner join `taggables` on `tags`.`id` = `taggables`.`tag_id` 
where `products`.`id` = `taggables`.`taggable_id` 
and `taggables`.`taggable_type` = 'App\Models\Product' and `tags`.`name` = 'Action')

What is wrong with it ? I'm using polyhmorphic many yo many relationship between product and tags, there some other taggable models.



via Chebli Mohamed

getting error message with phpunit testing in laravel 5

I got a class Fight, which implements a logic of a fight between two heroes. After the fight one of the hero may lose some health points. i wrote a php Unit test but getting an error

TypeError: Argument 1 passed to Tests\Unit\Fight::makeFight() must implement interface Tests\Unit\HeroInterface, string given, called in location\ExampleTest.php on line 61

here is my code with classes and interface and the test method

interface HeroInterface
{

    public function getForce(): int;

    public function getImmunity(): int;

    public function getHealthPoints(): int;

    public function setHealthPoints(int $healthPoints);
}

class DamageHelper
{
    const DAMAGE_RAND_FACTOR = 0.2;

    public static function getDamage(HeroInterface $attacker, HeroInterface $defender)
    {
        if ($attacker->getForce() < $defender->getForce()) {
            return 0;
        }

        $damageBase = round(($attacker->getForce() - $defender->getForce()) / $defender->getImmunity());

        $damageFactor = $damageBase * self::DAMAGE_RAND_FACTOR;
        $minDamage    = $damageBase - $damageFactor;
        $maxDamage    = $damageBase + $damageFactor;

        return mt_rand($minDamage, $maxDamage);
    }
}

class Fight
{

    public function makeFight(HeroInterface $attacker, HeroInterface $defender)
    {
        $damage = DamageHelper::getDamage($attacker, $defender);
        $defender->setHealthPoints($defender->getHealthPoints()-$damage);
    }
}

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testMakeFight()
    {
        $fight = new Fight();

        $this->assertTrue($fight->makeFight('10', '2'));
    }
}

any help will be appreciated



via Chebli Mohamed

Laravel Crinsane/LaravelShoppingcart associate() doesn't work

In my Laravel I'm using this shoppingcart .

When i add one product to my shopping cart i wan to have associate() with App\Product Model .

This is my code :

  public function store(Request $request)
{
    // store product information to Cart


    Cart::add($request->id, $request->name, 1, $request->price)
    ->associate('App\Product');


    return redirect(route('cart.index'))->with('success_message','محصول با موفقیت به سبد اضافه شد');
}

But when i want to access model $item->model->id in view I get this error :

Trying to get property 'id' of non-object (View: C:\xampp\htdocs\digikala\resources\views\cart.blade.php)



via Chebli Mohamed