mercredi 30 août 2017

Pheanstalk\Exception\ServerExceptionvendor/pda/pheanstalk/src/Command/ReleaseCommand.php:63

Job 58520 NOT_FOUND: does not exist or is not reserved by client.

In my job script, I am doing two more things. One is DOM html parsing and other is sending cURL request.

I re-attempts curl request 5 times with one second delay in each attempt unless I get success response.

This is a very rare error which occurs 0.1%. We are unable to re-generate it. Any help will be gracious..



via Chebli Mohamed

mardi 29 août 2017

Storing additional data in Laravel jobs table

Is there a way to store additional data in the Laravel jobs table? I am using Laravel 5.1 and the database queue driver. For certain jobs, they're being dispatched to process data for a particular model, and I'd like to record the ID of that model in the row so I can query if there's a job queued up for it.

Otherwise, is there a recommended way to know what the job is queued up for?



via Chebli Mohamed

samedi 26 août 2017

Return the model I belongTo based on foreign key

How can I get the full model based on the foreign key in a table using Laravel?

A user row will have a single tier it's associated with, represented by the ID as the foreign key.

I need to return the user with the tier it belongs to, and the entire contents of that tier as well.

In my User model, I've tried protected $with = ['tier'];, but this doesn't work.

User:

public function tier()
{
    return $this->belongsTo('App\Tier');
}

Tier:

public function users()
{
    return $this->hasMany('App\User');
}

User's table:

enter image description here

User's table structure fk index:

enter image description here



via Chebli Mohamed

vendredi 25 août 2017

AWS cognito user authentication with laravel

We are trying to implement Amazon Cognito services for user authentication with our built in laravel 5.1 application. We are looking for a composer package for laravel 5.1 that allow to Amazon Cognito User Pools, registering user's into User Pools, password resets etc.



via Chebli Mohamed

mercredi 23 août 2017

Does Package creation changes with routes in laravel 5.4

Do we need to maintain separate route like web.php and api.php for routes while creating package in laravel5.4 .

I have a laravel package which is in 5.1 if i need to move in 5.4 do i need to change its route like web and api . Currently i have it in http -> routes.php.



via Chebli Mohamed

mardi 22 août 2017

Undefined offset error when trying to store multiple records in laravel [duplicate]

Hello everyone i am facing this issue when trying to store multiple records in database.

The Error says: Undefined index

Here is my code:

$str1 = $request->s_start[$i];
            $str2 = $request->s_end[$i];
            $startint = preg_replace("/[^0-9]/", "", $str1);
            $endint = preg_replace("/[^0-9]/", "", $str2);
            $words = preg_replace('/[[:digit:]]/', '', $str1);

            for ($i = $startint; $i < $endint; $i++) {
                $newstring = $words . $i;

                    $pls = new \App\ItemSeries();
                    $pls->pl_id = $pl->id;
                    $pls->series = $newstring;

                    $pls->save();

            }

Any one please help me out.



via Chebli Mohamed

lundi 21 août 2017

Laravel DB Query with multiple sub strings

I am looking to run a a DB query where if a user queries with multiple sub-strings across two columns they can bey queried. For example,

Column 1 is Country Name and Column 2 is City and Country Name. Sample data:

Column1| Column2
USA | Portland, Oregon, United States of America
USA | Portland, Maine, United State of America
USA | Bellevue, Washington, United State of America
USA | Bellevue, Nebraska, United State of America

Now user can query using various option. For example:

Portland America 
Portland USA
Portland Oregon USA
Portland Oregon America
Portland United States
... and so on

I am looking to build a query that can solve this for me. I tried the combination of where and orwhere but that didn't solve for it.



via Chebli Mohamed

Laravel 5.1 translate an array pass to blade

I have this in my controller

public function editProfile(Request $request){
  $question1 = Question::where('group',1)->lists('question', 'id');
  $question2 = Question::where('group',2)->lists('question', 'id');

  return view('user', compact(''question1', 'question2'));
}


$question = {\"1\":\"What is the first name of your best friend in high school?\",\"2\":\"What was the name of your first pet?\",\"3\":\"What was the first thing you learned to cook?\",\"4\":\"What was the first film you saw in the theater?\"}

$question2 = {\"5\":\"Where did you go the first time you flew on a plane?\",\"6\":\"What is the last name of your favorite elementary school teacher?\",\"7\":\"In What city or town does your nearest sibling live?\"}

I would like to translate the value in both question 1 and question 2 and pass it to user blade without changing the key, Any suggestions?



via Chebli Mohamed

Laravel autocomplete search questions

I am working on online shop that has categories page and in accordance of the category that is chosen products page is displayed . I want to create an autocomplete search field that will be available in those 2 pages that will show products only , once that match the search.

Where should I create my search field?How my route should look?What view should I return? I would appreciate very much even farther instructions of creating autocomplete search field. Thank you



via Chebli Mohamed

Social logins with Masked domain

I use sub-domain for all clients like client.example.com and then i masked their domain over it. i have added social logins Google, Facebook and LinkedIn.

Facebook and LinkedIn Seems to be working but the issue with Google Login its just showing blank white page when i hit the URL for login.

is it possible to use social logins for masked domain?

because other two are working fine and google is not throwing any error so could not figure out the solution.

Project is in Laravel-5.1 and i use Socialite

Any help would be great

Thank you in advance



via Chebli Mohamed

php code is working in laravel view files but core simple laravel code is not in laravel view file (laravel version:5.2.45)

In laravel view file:

@if(Session::has('success'))
       <p class="alert alert-info"></p>
@endif

above code not working, its getting display on view file as it is..

But I am using simple php instead of that:

<?php if (Session::has('success')){ ?>
   <p class="alert alert-info"><?php echo Session::get('success'); ?></p>
<?php } ?>

Its working properly.. then why this is happning

php code is working properly but simple laravel code is not working in laravel view/blade file.. its getting printed on view page as it is..

please clarify this..



via Chebli Mohamed

dimanche 20 août 2017

Laravel Query Builder convert to array

How to convert the retrieved data items from the database to an array.

 $data = DB::table('Reports')
            ->where('mv_name','=',$Movie_name)
            ->where('date','=',$date)
            ->where('sh','=',$show)->get()->toArray();

If I give the above code. Error is displayed as

Call to a member function toArray() on array



via Chebli Mohamed

Laravel Query Builder Iteration

I have two tables "A" and "B". I need to do multiply all the column with integer values with table "B". How can I achieve that using Laravel Query Builders

$Agree =DB::table('agreements')->get();

foreach($Agree as $ag)
{
$th_name=$ag->theater_name;
$wk1_terms=$ag->wk1_terms;
$Aud=DB::table('Aud')->where('th','=',$th_name)->get();
foreach($Aud as $a){
    $wk1_aud=$a->wk1_aud;
    $result=$wk1_aud*$wk1_terms;
dd($result);
    }
}

If I execute the above code I get only the result of the first record from both the tables get multiplied.



via Chebli Mohamed

samedi 19 août 2017

Laravel: Remove an attribute in returned result

I have the following code:

$orders = Order::all();
return $orders;

This returns something like this:

[
     {
         "id": 123,
         "qr_code": "foo.png",
         "qr_code_url": "http://ift.tt/1zQvqaF"
     },
     {
         "id": 112,
         "qr_code": "bar.png",
         "qr_code_url": "http://ift.tt/2x1EX5R"
     }
]

Note that qr_code_url is an appended attribute, and not an attribute stored in the database.

I want to return this collection back to the user without the attribute: qr_code, in this case. So like this:

[
     {
         "id": 123,
         "qr_code_url": "http://ift.tt/1zQvqaF"
     },
     {
         "id": 112,
         "qr_code_url": "http://ift.tt/2x1EX5R"
     }
]

Looking at the collection functions, i can't seem to find an easy way to do this: http://ift.tt/2mY64f6

The only functions I have found close to what I want is: except and forget, but they seem to just work on a 1 dimension array. Not a collection result returned by a model.

How can I solve my problem?



via Chebli Mohamed

Laravel 5.4 Lumen ,Sending an Email

I am developing an API in laravel Lumen 5.4 and I am stuck in sending mails i.e to send a mail when a new user signup and so on different operations.

I am gettign this error:

my mail sending Function is

 use App\config\maill;
use App\config\services;
use Illuminate\Support\Facades\Hash;
 use Illuminate\Support\Facades\Mail;
use Illuminate\Contracts\Mail\Mailer;
 public function basic_email()
 {

      $data = array('name'=>"ahmad");

      Mail::send(['hiii'],$data, function($message) {
         $message->to('ahmadbinizhar@gmail.com', 'welcome')->subject('Laravel Basic Testing Mail');
         $message->from('a*****d@gmail.com','ahmad');
      });
     return response('Basic Email Sent. Check your inbox');
   } 

My Route is

$app->get('sendbasicemail','UserController@basic_email');

My .Env File is

MAIL_DRIVER = smtp
MAIL_HOST = smtp.gmail.com
MAIL_PORT = 587
MAIL_USERNAME = a*******d@gmail.com
MAIL_PASSWORD = ThisIsNotSecret
MAIL_ENCRYPTION = tls

i have check through mailgun Driver also but the same error .



via Chebli Mohamed

mercredi 16 août 2017

Adding an integer value into string in laravel

Hello Every one, I have an issue that is, I want to add an integer into a string for example I have two text field one is called series start and the other one is called series end now if user enters

FAHD1000001 into series start field

AND

FAHD1000100 into series end field

the algorithm should store 100 values into the database with increment into the each entry that is going to store into the database. i.e

FAHD1000001, FAHD1000002, FAHD1000003, ........., FAHD1000100

Is it possible to do so, if yes then how. Please help me



via Chebli Mohamed

dimanche 13 août 2017

Laravel 5 Middleware not working properly

I have define a middleware in laravel 5. But when I login it redirect me to dashboard but dashboard doesn't show and an error occurred. I have upload a picture of it. http://ift.tt/2fC4aiV

AdminAuth.php

<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class AdminAuth 
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check())
        {
            $user = Auth::user();
            return redirect()->route('admin_display_dashboard'); 
        }  else {
            return redirect()->route('admin_display_login');
        }
    }
}   

Kernel.php

<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],
        'api' => [
            'throttle:60,1',
        ],
    ];
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'adminAuth' => \App\Http\Middleware\AdminAuth::class,
    ];
}

Route.php

Route::group(['middleware' => ['adminAuth']], function () {

Route::get('admin/dashboard', array('as'=>'admin_display_dashboard', 'uses'=>'AdminViewController@displayDashboard'));

});



via Chebli Mohamed

jeudi 10 août 2017

Storing data during single request

We're white labeling our system, which is built using Laravel 5.1. It'll be the same code base and database, but things like the logo and CSS will be different based on the domain.

I figure I'm going to use Laravel's sub-domain routing do capture which domain the user is accessing, but is there a recommended way for me to store the domain during the request? For instance, I want to be able to know if they are on DomainA vs DomainB anywhere in the system, so I can easily check and use that as a condition. One idea I had was to set this up in the middleware, and store the domain wildcard using Config::set().

Or if there is a particular approach to the white labeling that would help, I'm all ears. Any input would be appreciated. Thanks.



via Chebli Mohamed

can someone help me in laravel to fix when i add image on db i got this D:\youssfi\wamp\tmp\php5571.tmp but i want the original name of image

this is my function store in controller :

public function store(VehiculeRequest $request)
{
    $image = $request->image_VH;

    if($image->isValid()) {
        $chemin = config('images.path');
        $extension = $image->getClientOriginalExtension();
        do {
            $nom = str_random(10) . '.' . $extension;
        } while(file_exists($chemin . '/' . $nom));

        $image->move($chemin, $nom);
    }

    $inputs = array_merge($request->all($image));
    $this->VHRepository->store($inputs);
    return redirect(route('vehicules.index'));
}

and this my class repository:

<?php

    namespace App\Repositories;

    use App\Vehicule;
    use App\Http\Requests\VehiculeRequest;

    class VHRepository
    {

        protected $Vehicule;

        public function __construct(Vehicule $Vehicule)
        {
            $this->Vehicule = $Vehicule;
        }

        public function getPaginate($n)
        {
            return $this->Vehicule->with('user')
            ->orderBy('vehicules.created_at', 'desc')
            ->paginate($n);
        }

        public function store($inputs)
        {
            $this->Vehicule->create($inputs);
        }

        public function destroy($id_vehicules)
        {
            $this->Vehicule->findOrFail($id_vehicules)->delete();
        }

    }



via Chebli Mohamed

Model Factories don't run in test setUp() method Laravel 5.1

I am using Laravel 5.1 and I have the following test class where I am using some model factories in the setUp() method to temporarily seed the database.

class PendingUserWithManualStudentDetailsTest extends TestCase
{
    use DatabaseMigrations, WithoutMiddleware;

    public function setUp()
    {
        parent::setUp();

        $this->studentDetail = factory(StudentDetail::class)->create();

        // ... more factories
    }

    // ... some tests
}

When running the test I get the following error:

General error: 1 no such table: student_details

When I move the factory calls into a test method they execute just fine. So I am guessing that the order in which the setUp() and my test methods are called are causing the issue. Is there any way I can fix this?

This is my testcase class:

class TestCase extends Illuminate\Foundation\Testing\TestCase
{
    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
    protected $baseUrl = 'http://myapp.dev';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

        $app->setLocale('en');

        return $app;
    }
}



via Chebli Mohamed

mercredi 9 août 2017

Where clause on a model relation

I want to eager load locales with items- but only want to load items with locale of a specified value.

I.e., If the current locale is set to ID 2, I want all items with locale ID 2 in its related table item_locale.

How can I do this?

public function locales($localeId)
{
    return $this->belongsToMany(Locale::class, 'item_locale')
        ->withPivot('target')
        ->where('locale', $localeId); // <-- how can I accomplish this?
}


User Controller:

return $userGameProfile = User::with(
    [
        ...
        'items' => function($query) use ($profile_id) {
            $query->where('profile_id', '=', $profile_id);
        },
        ...
    ]
)->find($id);

...

User Model:

class User extends Model ...
{
    public function items()
    {
        return $this->belongsToMany(Item::class, 'user_item')
            ->withPivot('item_count');
    }
    ...

Item Model:

class Item extends Model
{
    protected $with = [..., 'locales'];

    public function locales($localeId)
    {
        return $this->belongsToMany(Locale::class, 'item_locale')
            ->withPivot('target')
            ->where('locale', $localeId);
    }
}

Locale Model:

class Locale extends Model
{
    ...
    public function items()
    {
        return $this->belongsToMany(Item::class);
    }
}

item_locale table:

   item_id | locale_id | target
        1         1         狗  // don't want these results
        1         2         dog // only want result of locale ID 2



via Chebli Mohamed

lundi 7 août 2017

Laravel: File not found exception for a 'video' file

I am creating a new Model (called Media) and by uploading a video file from the field userfile I have this error:

FileNotFoundException in Filesystem.php line 40:
File does not exist at path

my Controller

    public function store(Request $request)
   {
      // Validation //
      $validation = Validator::make($request->all(), [
         'caption'     => 'required',
         'description' => 'required',
         'category' => 'required',
         'userfile'     => 'sometimes|'
      ]);

      // Check if it fails //
      if( $validation->fails() ){
         return redirect()->back()->withInput()
                          ->with('errors', $validation->errors() );
      }

      $media = new Media;
      //dd($request);

      // upload the media //
      $file = $request->file('userfile');
      $filename = str_random(6).'_'.$file->getClientOriginalName();

      if($file){
        Storage::disk('local')->put($filename, File::get($file));
      }
      dd($file);
      $destination_path = 'uploads/';
      $file->move($destination_path, $filename);

      // save media data into database //
      $media->file = $destination_path . $filename;
      $media->caption = $request->input('caption');
      $media->category = $request->input('category');
      $media->description = $request->input('description');
      $media->save();

      return redirect('/medias')->with('message','You just uploaded an media!');
   }

line 40 correspond to Storage::disk('local')->put($filename, File::get($file));

FileSystem.php

'disks' => [

    'local' => [
        'driver' => 'local',
        'root'   => public_path('uploads'),
    ],

All my Medias model are being store on the folder public/uploads but Laravel can't find the video files on the server but if I upload a picture file it's ok?



via Chebli Mohamed

laravel: how to display the assets that are inside the Public folder

On the server (shared-hosting) all the assets that are inside the public folder are not displayed. i.e.

<img src="" >

output this

<img src="http://ift.tt/2vHFtbP" >

it supposed to have a public folder

http://ift.tt/2wB1w0q

On my Public_html folder I have this folder structure

PUBLIC_HTML
├───app
├───bootstrap
├───cgi-bin
├───config
├───database
├───public
│   ├───css
│   ├───img
│   ├───js
│   ├───uploads
│   └───videos
│   .htaccess(file)
│   .index.php(file)
├───resources
├───storage
└───tests
└   .htaccess(file)

both of the .htaccess file is like this file

DirectoryIndex public/index.php
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ public/index.php [L]
</IfModule>

permissions

enter image description here

So my questions is how can I set my configuration (.htaccess) so that I can display my assets on the shared-hosting site.



via Chebli Mohamed

samedi 5 août 2017

how get products by colors and sizes

   code result: get all sizes and  colors but 
   i wanna get products colors and  sizes 
    ex : get products  have small size and color red    
   below my code :
    $products=Product_property::where(function ($query) {
        $query->whereIN('color',explode(',',$request['colors']));
    })->where(function ($query) {
        $query->whereIN('size',explode(',',$request['colors']));
    });
    how can solve this problem , any help

i wanna get products colors and sizes ex : get products have small size and color red



via Chebli Mohamed

jeudi 3 août 2017

Laravel ERROR logging unexpected output

Below function is used to log an error with details

private function logError($xml, Exception $e, $fromWhere = "")
{
    $log = new Logger('REQUEST_ERROR_LOG');
    $logger = $log->pushHandler(
        new StreamHandler(
            storage_path('logs/error/'.date('Y').'/'.date('m').'/'.date('d') . '.log')
        ),
        Logger::INFO
    );

    $logger->addError('', [
        array(
            "FILE"    => $e->getFile(),
            "LINE"    => $e->getLine(),
            "MESSAGE" => $e->getMessage(),
            "FROM"    => $fromWhere,
            "XML"     => $xml
        )
    ]);
}

This is how i call it

private function addUser($xml)
{
    try {
        $xmlObj = simplexml_load_string($xml);
    } catch (Exception $e) {
        //Exception happens when xml parse error.
        $this->logError($xml, $e, "addUser()");
    }
}

This is the logged details Note that there are no details logged

[2017-08-03 12:45:55] REQUEST_ERROR_LOG.ERROR:   []
[2017-08-03 12:47:22] REQUEST_ERROR_LOG.ERROR:   []
[2017-08-03 12:48:42] REQUEST_ERROR_LOG.ERROR:   []
[2017-08-03 12:49:08] REQUEST_ERROR_LOG.ERROR:   []
[2017-08-03 12:50:28] REQUEST_ERROR_LOG.ERROR:   []

Is there someone who got in to this or any guesses why is this happening?



via Chebli Mohamed

Nginx Laravel Php double request per request

I'm having a problem with my Laravel 5.1 site that is deployed on a NGINX server with PHP 7 on Ubuntu. When I make request for any route the request are being duplicated ,I noticed it when I tried out a function that I had to prevent duplicate request , by generating a new token like CSRF token but for each request.

When I try to Log::info("test") on a function in any controller I get the following:

[2017-08-03 19:46:39] local.INFO: test  
[2017-08-03 19:46:39] local.INFO: test  

I don't have this issue on my local WAMP apache server though.



via Chebli Mohamed

mercredi 2 août 2017

Route model binding with regex in Laravel 5.1

I write api for mobile, since I have more than one version, I don't want to copy-paste the same routes, hence I decided to do something like this:

Route::model('callRequestNote', CallRequestNote::class);

Route::group([
    'prefix'     => 'api/v{version}/mobile',
    'where'      => ['version' => '[1|2]'],
], function () {
    Route::delete('/notes/{callRequestNote}', MobileNotesController::class . '@destroy');
    // other duplicated routes
});

public function destroy(CallRequestNote $callRequestNote)
{
    //
}

In this situation CallRequestNote is not binded to route properly and I get exception:

Argument 1 passed to NotesController::index() must be an instance of CallRequestNote, string given

But when I don't use parameters in prefix, like this:

Route::group([
    'prefix'     => 'api/v1/mobile',
], function () {
    Route::delete('/notes/{callRequestNote}', MobileNotesController::class . '@destroy');
});

Model is binded properly. Any ideas how to make it work?



via Chebli Mohamed

mardi 1 août 2017

Connection refused in laravel with windows machine

My Laravel Application is working on live linux server, when i copy my project from live to localhost(xampp), it showing "The connection reset error", any one please suggest better solution?



via Chebli Mohamed