dimanche 23 février 2020

How to use Pthread in laravel application?

Currently I'm working on a booking application using laravel framework and I already integrated multi hotels providers so when the users searching for hotels the application calling each provider's endpoint the is responsible for this particular action.

The problem is I call this end points once using guzzel and I should wait until received the last response so let's say that this process take 5 second so If I have 100 users that searching for hotels at the same time then the user number 100 should wait 500 second in order to get the response.

I've read some articles talking about using pthread in such cases. So if anyone could help me to accomplish this process using pthread or anything else?.



via Chebli Mohamed

save image path in cart session in laravel

I want to store product image path in session for that i'm using following code :

 $product = $this->productRepository->findProductById($request->input('productId'));
    $options = $request->except($request->input('_token'), $request->input('productId'),$request->input('productPrice'), $request->input('quantity'),$product->images[0]['full']);
    Cart::add(array('id'=>uniqid(), 'name'=>$product->name, 'price'=>$request->input('productPrice'),  'quantity'=>$request->input('quantity'),'image'=>$product->images[0]['full'], 'attributes'=>array($options)));

other details are being stored in cart but image path is not getting stored.



via Chebli Mohamed

samedi 22 février 2020

How to convert array with objects to one object like Laravel Request object

I have an array like this:

[{FirstName: "fff"},
{LastName: null},
{Nationality: null},
{Year: null},
{Month: null},
{Day: null}]

I need to convert it to one object like this: (with Laravel or with JS)

{FirstName: "fff",
LastName: null,
Nationality: null,
Year: null,
Month: null,
Day: null}

I need one object exactly like Laravel request object. How can I do this?



via Chebli Mohamed

Request failed when using Axios in ReactJs and Laravel

I using ReactJs as my front-end engine and I handle a request using Axios to get data from my Post table by Laravel I set route in api.php when I get a response and console.log it it shows Access to XMLHttpRequest at error at my chrome DevTool

api.php file:

<?php

use Illuminate\Http\Request;

Route::get('/', [
    'uses' => 'PagesController@getIndex'
]);

my controller file:

<?php

namespace App\Http\Controllers;

use App\Posts;
use Illuminate\Http\Request;

class PagesController extends Controller
{
    public function getIndex(){
        $post = Posts::all();

        return $post;
    }
}

my ReactJs file(App.js):

import React from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';

class App extends React.Component{

    getData(){
        console.log(123);
        axios.get('http://localhost:8000/')
            .then(function (response) {
                console.log(response.data);
            }).catch(function (error) {
            // handle error
            console.log(error);
        });
    }

    render(){
        return (
            <div className="App">
                <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <p>
                        Edit <code>src/App.js</code> and save to amir.
                    </p>
                    { this.getData() }
                    <a
                        className="App-link"
                        href="https://reactjs.org"
                        target="_blank"
                        rel="noopener noreferrer"
                    >
                        Learn React
                    </a>
                </header>
            </div>
        );
    }
}

export default App;

Error screenshot:

enter image description here



via Chebli Mohamed

My Laravel 5.5 app not working on remote server namecheap VPS after deployment but working fine on local server with WAMP

Everything about this app is working fine on my local sever, but refused to work remotely. if i visit the app www.mysite.com. It always shows internal server error. Though i don't have any route in web.php but i expected to redirect back to 404 not found page but not doing that but it does on localhost.

The other main problem is , i have many routes in api.php, if i send data to any of the routes, they accept data and might even save them in database where it is necessary but it will never return the json Response that i have defined after every successful operation. The response i always get is 500 internal server error even if the operation was successful. I have been on this issue for over two weeks now.

I am using PHP 7.2 on the server

Here is my .htaccess file

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>
    RewriteEngine On
    RewriteBase /
    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]
    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

api.php

<?php

Route::group(['prefix' => 'user', 'namespace' => 'User'], function () {

    Route::post('/login', 'UserAuthController@userLogin');
    Route::post('/signup', 'UserAuthController@userSignup');

});

UserController.php

public function userSignup(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:200',
            'password' => 'required|between:8,100|confirmed',
            'phone' => 'unique:users|required|digits:11|numeric',
            'email' => 'unique:users|required|email',

        ];
        $validator = Validator::make($request->all(), $rules);
        $code = mt_rand(100000, 900000);
        $hCode = FacadesHash::make($code);
        if ($validator->passes()) {
            $user = User::create([
                'name' => $request['name'],
                'email' => $request['email'],
                'phone' => $request['phone'],
                'otp' => $hCode,
                'password' => FacadesHash::make($request['password']),
            ]);

            $data = [
                'name' => $request['name'], 'subject' => 'Email Confirmation',
                'view' => 'mails.emailconfirm', 'code' => $code
            ];


            return response()->json(['success' => true, 'status' => 200, 'message' => 'Your account has been created successfully and an OTP code has been sent to your email'], 200);
        } else {

            return response()->json(['success' => false, 'status' => 200, 'message' => $validator->errors()->first()], 200);
        }
    }

the signup route for example, is working fine but will never return the Json response i specified, it will rather return 500 internal server error even if everything went well.

No error is being logged in my storage/log if everything went well and i dont get the response. But i do see error there if the operation was not successful.

all folders have 777 permissions and i have as well clear all caches so many times



via Chebli Mohamed

Make Laravel request from array with objects

I have an array that makes in front end with js and pass that to my controller with ajax.

structure of array is this:

[{FirstName: "fff"},
{LastName: null},
{Nationality: null},
{Year: null},
{Month: null},
{Day: null}]

I can't validate this array with request validation laravel. Now I'm going to turn this array into a Larval request to apply the rules to it.

Rules:

 $validator = Validator::make($maked_laravel_request_from_array, [
                    'FirstName' => 'required',
                    'lastName' => 'required',
                ]);

Can any one helps?



via Chebli Mohamed

Get values from blade to Model function Laravel

Am trying to import excel file. From current state I can upload the file, But I want insert excel file on each different table depending on the values in the combo box. ie if Value is A insert into tableA,Value is B insert into tableB like that. Am looking for, is it possible to check the values in the route and call model function.

Blade file

<form id="ExcelImportForm" method="post" enctype="multipart/form-data" action="">
   <table class="table">
      <tr>
         <td>Select Project *</td>
         <td>
            <select required class="form-control" name="ExcelProject" id="ExcelProject">
               <option selected disabled>Select Technology</option>
               <option value="A">A</option>
               <option value="B">B</option>
               <option value="C">C</option>
               <option value="D">D</option>
            </select>
         </td>
      </tr>
      <tr>
         <td>Select File *</td>
         <td><input class="form-control" type="file" id="file" name="file" required  ></td>
      </tr>
      <tr>
         <td></td>
         <td><button type="submit" id="ExcelMasterBtn" class="btn btn-success pull-right"><i class="fa fa-upload"></i> Upload</button></td>
      </tr>
   </table>
</form>

Below give is route which is working in single case, is it possible to implement an if statement inside that.

route.php

Route::get('/upload-panel/', function () {
    (new  \App\Http\Model\Excelentry())->importToDb();

        return view('admin.upload-panel.excel-upload-panel');
});

Or anyother way to get this combobox value inside the model function



via Chebli Mohamed