vendredi 29 septembre 2017

Laravel 5.1 - Get artisan arguments from internal call

I do

when I run artisan queue:work or artisan queue:listen it runs the current commands with their corresponding Arguments. Now my question is, how can I Access those Arguments?

As you can see in the following Picture, the Arguments are there but I have no clue how to Access them?

enter image description here



via Chebli Mohamed

How to make laravel Blueprints morphs method to add column after a specified coloum

While creating migration scripts I can do something like this

Schema::table('books', function(Blueprint $table)
        {
            $table->string('reference')->after('access');
        });

this will create my reference column after access column. But if I want to use morph how would I do this. I was thinking of doing this

Schema::table('books', function(Blueprint $table)
        {

            $table->morphs('reference')->after('access');
        });

However, this gives me a migration error when I try to run the migration. This is because morphs doesn't have a after method. I am using laravel 5.1. I am not sure how I could have the reference columns after access. Any help or suggestion would be great. Thank you



via Chebli Mohamed

Class 'Symfony\Component\HttpFoundation\ParameterBag' not found

I'm getting the following error when I try to run php artisan on a clean install of Laravel 5.1.43 on a Vagrant box. I've listed the versions below.

PHP Fatal error:  Class 'Symfony\Component\HttpFoundation\ParameterBag' not found in /var/www/vendor/symfony/http-foundation/Request.php on line 240
PHP Stack trace:
PHP   1. {main}() /var/www/artisan:0
PHP   2. Illuminate\Foundation\Console\Kernel->handle() /var/www/artisan:36
PHP   3. Illuminate\Foundation\Console\Kernel->bootstrap() /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:105
PHP   4. Illuminate\Foundation\Application->bootstrapWith() /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:208
PHP   5. Illuminate\Foundation\Bootstrap\SetRequestForConsole->bootstrap() /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:203
PHP   6. Symfony\Component\HttpFoundation\Request::create() /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/SetRequestForConsole.php:20
PHP   7. Symfony\Component\HttpFoundation\Request::createRequestFromFactory() /var/www/vendor/symfony/http-foundation/Request.php:398
PHP   8. Symfony\Component\HttpFoundation\Request->__construct() /var/www/vendor/symfony/http-foundation/Request.php:1943
PHP   9. Symfony\Component\HttpFoundation\Request->initialize() /var/www/vendor/symfony/http-foundation/Request.php:222


  [Symfony\Component\Debug\Exception\FatalErrorException]
  Class 'Symfony\Component\HttpFoundation\ParameterBag' not found

Host machine:

  • macOS 10.13 17A365
  • Vagrant 2.0.0
  • Composer 1.5.2 2017-09-11 16:59:25

Vagrant box:

  • Ubuntu 14.04.5 LTS (GNU/Linux 3.13.0-132-generic x86_64)
  • PHP 5.6.31-6+ubuntu14.04.1+deb.sury.org+1 (cli) with Xdebug v2.5.5

If it is helpful, I can upload my Vagrantfile and install.sh files, and also my composer.json file.



via Chebli Mohamed

lundi 25 septembre 2017

Laravel 5.1 - Possible incorrect route configuration

I have the following routes set in my routes.php file:

  Route::resource('eventos', 'EventosController');
    Route::group(['prefix' => 'eventos'], function () {
        Route::get('filtrar', ['as' => 'eventos.filtrar', 'uses' => 'EventosController@filtrar']);
        Route::get('/', ['as' => 'eventos.index', 'uses' => 'EventosController@index']);
    });

Using the command line tool php artisan route:list I get the following output:

        | GET|HEAD                       | eventos                                              | eventos.index        | App\Http\Controllers\EventosController@index                  | auth,s
etViewVariables |
|        | POST                           | eventos                                              | eventos.store        | App\Http\Controllers\EventosController@store                  | auth,s
etViewVariables |
|        | GET|HEAD                       | eventos/create                                       | eventos.create       | App\Http\Controllers\EventosController@create                 | auth,s
etViewVariables |
|        | GET|HEAD                       | eventos/filtrar                                      | eventos.filtrar      | App\Http\Controllers\EventosController@filtrar                | auth,s
etViewVariables |
|        | GET|HEAD                       | eventos/{eventos}                                    | eventos.show         | App\Http\Controllers\EventosController@show                   | auth,s
etViewVariables |
|        | DELETE                         | eventos/{eventos}                                    | eventos.destroy      | App\Http\Controllers\EventosController@destroy                | auth,s
etViewVariables |
|        | PUT                            | eventos/{eventos}                                    | eventos.update       | App\Http\Controllers\EventosController@update                 | auth,s
etViewVariables |
|        | PATCH                          | eventos/{eventos}                                    |                      | App\Http\Controllers\EventosController@update                 | auth,s
etViewVariables |
|        | GET|HEAD                       | eventos/{eventos}/edit                               | eventos.edit         | App\Http\Controllers\EventosController@edit                   | auth,s
etViewVariables |
|        | GET|HEAD                       | usuarios                                             | usuarios.index       | App\Http\Controllers\UsersController@index                    | auth,s
etViewVariables |

The problem is that the route eventos.filtrar is not redirecting to the filtrar method in EventosController.

Here's the form that should redirect when submitted to the route in question:

{!! \Form::open(['route' => 'eventos.filtrar', 'method' => 'GET']) !!}

In EventosController@filtrar all I'm doing is dding the request, but all I get is a blank page. Instead of the request object.

public function filtrar(Request $request)
{
    dd($request->all());
}

All the RESTful routes seems to be working fine as well as the route that redirects to the index method.

Any suggestions?



via Chebli Mohamed

samedi 23 septembre 2017

Generate random number onclick and count generated numbers?

Hi i want go generate 6 digits unique random numbers on button click, and i want to controll how numbers was generate using select list. I make controller and i make few methods that generate the numbers but i don't know how to run methods on button click.

This is my controller:

 public function index(){
    $numbers = Number::all();
    return view('authUser.generatedNumbers', compact('numbers'));
}

public function store(Request $request){

    $number = new Number;

    $number->number = $this->getGenaratedNumber();
    $number->save();
}


public function getGeneratedNumber(){
    do{
        $rand = $this->generateRandomNumber(6);
    }while(!empty(Number::where('number',$rand)->first()));
    return $rand;
}



public function generateRandomNumber($length) {
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomNumber = '';
    for ($i = 0; $i < $length; $i++) {
        $randomNumber .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomNumber;
}

and this is my form:

 <form class="form-horizontal" method="POST" action="">
                            

                            <div class="form-group">
                                <div class="col-md-6">
                                    <label for="prefix">Prefix</label>
                                    <select name="prefix" class="form-control">
                                        <option value="0888">0888</option>
                                        <option value="0877">0877</option>
                                        <option value="0889">0889</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="count">Count</label>
                                    <select name="count" class="form-control">
                                        <option value="100">100</option>
                                        <option value="200">200</option>
                                        <option value="300">300</option>
                                        <option value="400">400</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-md-12">
                                    <button type="submit" class="btn btn-primary btn-block">
                                        Generate Numbers
                                    </button>
                                </div>
                            </div>
                        </form>



via Chebli Mohamed

vendredi 22 septembre 2017

¿Create model with multiple relationships?

Basically I have the following models

  • Applications
  • Products
  • Users

These models are related in the following way

A request contains a type of product and this request is made by a user

Then the relationships for model requests are

//Usuario que hace la solicitud
public function user(){
  return $this->belongsTo(User::class);
}


public function product(){
      return $this->belongsTo(Product::class);
    }

Relationships for the user model

public function solicitudes(){
  return $this->hasMany(Solicitud::class);
}

Relationships for the model Product

  public function solicitudes(){
  return $this->hasMany(Solicitud::class);
}

The doubt arises since the request model has two relations with user and product then what would be the best way to create the request model since now as I am doing it is as follows.

$user->solicitudes()->create(['product_id'=>1,'size_dd'=>'22','snapshot'=>1]);

as it is basically observed I am passing the product id to the * create * method so that it does not generate errors, but I want to know what would be the best way to do it considering that it has double relation.



via Chebli Mohamed

jeudi 21 septembre 2017

How can I enable a certain route access only when a certain condition is true?

GOAL

I'm trying to block my main login page base on a flag of my .env file. I'm not sure if this is the right approach.


Steps

In my .env I've added

LOGIN_PAGE=true

Then in my route file

I add that if check

if(env('LANDING_PAGE') == true){

    Route::get('/',['as' => 'login', 'uses'=>'AuthController@getSignIn']);
    Route::post('/', 'AuthController@postSignIn');
}


Result

LOGIN_PAGE=fasle

I go to my log-in page, I got 404 Page not found which is good.

LOGIN_PAGE=true

I go to my log-in page, I still got 404 Page not found which is not good. I should see my log-in page.

What did I forget ? How would one and go about and #GOAL

I'm trying to block my main login page base on a flag of my .env file. I'm not sure if this is the right approach.


Steps

In my .env I've added

LOGIN_PAGE=true

Then in my route file

I add that if check

if(env('LANDING_PAGE') == true){

    Route::get('/',['as' => 'login', 'uses'=>'AuthController@getSignIn']);
    Route::post('/', 'AuthController@postSignIn');
}


Result

LOGIN_PAGE=fasle

I go to my log-in page, I got 404 Page not found which is good.

LOGIN_PAGE=true

I go to my log-in page, I still got 404 Page not found which is not good. I should see my log-in page.

What did I forget ? How would one and go about and enable a certain route access only when a certain condition is true ?

Any hints / suggestions will be much appreciated !



via Chebli Mohamed

Laravel 5.1 Session store not set on request. at /vendor/laravel/framework/src/Illuminate/Http/Request.php:411

I have got this exception while running the following command

php artisan schedule:run

I have already added in middleware too

\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,

The exception is,

Session store not set on request. {"exception":"[object] (RuntimeException(code: 0): Session store not set on request. at /var/www/html/laravel5.5/vendor/laravel/framework/src/Illuminate/Http/Request.php:411)



via Chebli Mohamed

Laravel 5.1 constrain and eager load multiple nested relations

I have four models: OwnerCompany, Owner, User, and Role.

I want to get all OwnerCompanys eager loading their Owner and also eager loading its Users who have the Role with the name 'admin'.

OwnerCompany::with('owner.users')->whereHas('owner.users.roles', function ($query) {
    $query->where('name', 'admin');
})->get();

This loads in the models but doesn't constrain the users, they are all loaded.



via Chebli Mohamed

Laravel Email Function - REST API

Quick Fire Question, I am using mail function of laravel 5.1, but it still gives me variable not defined error, I have debugged and checked the variable I am printing is valid.

$email_id = $users[0]['email_id'];
//i have checked $email_id by printing and it is working.

    Mail::send('emails.forgetpassword', ['title' => $title, 'name' => $name, 'content' => $content, 'link' => $link], function ($message)
                    {
                        $message->from('xyz@gmail.com', 'xyz Team');
                        $message->to($email_id);
                        $message->subject('xyz App - Forget Password');
                    });

I have checked the documentation I don't know what it is missing. It throws me error at this line

$message->to($email_id);

I don't know why $email_id is already defined and working.



via Chebli Mohamed

mercredi 20 septembre 2017

I can have the same session for two Laravel projects?

I have two laravel projects in te same server (mydomain.com and sub.mydomain.com) with different database but the user ID's are the same.

I want the session to be the same on both platforms, How I do this? It is posible?



via Chebli Mohamed

lundi 18 septembre 2017

Auth::attemp() is not working. Laravel 5.5

My registration form is working and it store users to db but when user login then Auth::attempt() return false. Here is my code for login. I store the password in db in sha1 encription.

Route::post('login',function(){
$creds=array(
        'email' => Input::get('email'),
        'password' => sha1(Input::get('password'))
    );
$auth = Auth::attempt($creds);

dd($auth);



via Chebli Mohamed

jeudi 14 septembre 2017

How to get rid of laravel_session cookie from Laravel Application ?

I'm trying to get rid of laravel_session.

I've tried to create a middleware for it

http://ift.tt/2f9Bnmh

Change the driver to use : array file, database

None of that works. Everytime, I refresh - I always see this

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!

Is it even possible to do ?



via Chebli Mohamed

Return Redirect with body in Laravel

Goal

I'm trying to do a redirect with body in Laravel


I've tried

return Redirect::to($log_in_url)->with('body','<html><head><title>Redirecting to your page</title></head><body>If you are not redirected within 5 seconds, please <a href="'.$log_in_url.'">cl ick here</a>.</body></html>');

I look in the network tab, I don't really see anything.


Question

How would one go about and achieve something like this?

Should I start looking into alternative tools like cURL?

I'm open to any suggestions at this moment.

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



via Chebli Mohamed

mardi 12 septembre 2017

Laravel view suddenly stop updating changes made to the code

I am working on a project with Laravel. Getting to a point, I restarted my system, turning my development back on, every change I make to Laravel view does not effect. Even after save and refresh. Have restarted the server and system multiple times, cleared all browser data. The problem Still persist. Any help please.



via Chebli Mohamed

Laravel, how to update two tables with a one-to-one relationship from a single form

I have these two very simple models:

class Episode extends Model
{
    protected $fillable = ['number', 'language_code', 'published_at'];

    function content()
    {
        return $this->hasOne('App\EpisodeContent');
    }
}

class EpisodeContent extends Model
{
    protected $table = 'episodes_content';
    protected $fillable = ['episode_id', 'title', 'description'];

    function episode()
    {
        return $this->belongsTo('App\Episode');
    }
}

Where basically every Episode has one content. I could've used a single table, but I thought it could make sense to keep these sets of data separate.

In a form, I'd like to edit the Episode and its content at the same time, but after several attempts I haven't figured out how.

This is what I'm doing:

public function update(Request $request, $id)
{
    $rules = [
        'number' => 'required',
    ];
    $this->validate($request, $rules);
    $episode = Episode::with('content')->findOrFail($id);

    $episode->published_at = $request->get('published_at');
    $episode->number       = $request->get('number');
    $episode->content->title       = $request->get('title');

    $episode->update();

    return redirect('admin/episodes');
}

This way, nothing changes in the episodes_content table.

In another attempt, I tried this:

    $episode->published_at = $request->get('published_at');
    $episode->number       = $request->get('number');
    $episode->active       = $request->get('active');

    $episodeContent        = new EpisodeContent;
    $episodeContent->title = $request->get('title');

    $episode->content()->save($episodeContent);

This way, a new episodes_content row is created, while I'd like to update an existing one.



via Chebli Mohamed

lundi 11 septembre 2017

Vague Error Message in Laravel FileSystem Unlink

Good day,

I modified this file.

vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php

This is the function I modified.

public function handleError($level, $message, $file = '', $line = 0, $context = [])

I made it send me an email. The email has the $message and the $file and the $line.

This is what the email said.

MESSAGE FILE vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php LINE 126

The message is blank, but it's running into an error in a file. I open the file.

public function delete($paths)
{
    $paths = is_array($paths) ? $paths : func_get_args();

    $success = true;

    foreach ($paths as $path) {
        try {
            if (! @unlink($path)) { # the error is here
                $success = false;
            }
        } catch (ErrorException $e) {
            $success = false;
        }
    }

    return $success;
}

I am confused. Why was the error not caught by the catch block? What type of error would not give a message to the error handler of laravel? Is there something I can do to get more information regarding the error?

This is our version of Laravel.

Laravel Framework version 5.1.45 (LTS)



via Chebli Mohamed

Laravel queues and supervisor - php runs out of memory and parallel processing issues

I am working on a data importing functionality for a website. I am using Laravel 5.1 on homestead, and have given the machine 4GB of RAM and two virtual cpus. For importing the data I used the Laravel Excel package, with its chuncking mechanism that basically breaks the data set in chunks and adds the processing to the queue. The workflow for this is as follows:

  • the user uploads the excel file;
  • a job is dispatched to handle the excel file;
  • this job then chunks the file and dispatches multiple other jobs to process the chunked data;
  • each of these chunks dispatches another job to do some background logic on the inserted data when they are done.

I have setup a queue named 'import' in supervisor for these processes. Along with this queue, I also have a default one (for sending mails and other, less intensive, stuff) and a low priority queue for dispatching jobs from other jobs. Here is my supervisor configuration:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=/usr/bin/php /home/vagrant/Code/iris/artisan queue:work --tries=1 --daemon --queue=default,import,background1
autostart=true
autorestart=true
user=vagrant
numprocs=8
redirect_stderr=true
stdout_logfile=/home/vagrant/Code/iris/storage/logs/worker.log

With smaller files this works well, but when I attempt to import a ~30k row document, the php processes spawned by supervisor run out of memory toward the end and in the laravel log I start seeing InvalidArgumentException: No handler registered for command [__PHP_Incomplete_Class] in Illuminate\Bus\Dispatcher (this happens especially when I run two imports in parallel or I attempt to download something through websockets) and I am really confused as to why this is happening. No one process exceeds the 512 MB limit as far as I can tell from using memory_get_usage(). Is this a garbage collector issue? Should I summon it manually?

And since I mentioned the websockets, I was also trying to create a separate queue (with higher priority) for handling web socket requests. I tried multiple supervisor configurations (created dedicated worker in supervisor configuration files, added the queue to the --queue= option in the config, etc.) but to no avail. I implemented report downloading through web sockets, and it works fine by itself, but when there are other things in the queue, the socket request gets handled after several items in the lower priority 'import' queue finish, leaving me to believe that I do not understand queue priorities very well. Is there a way to have a separate queue for socket requests that responds immediately to these requests?



via Chebli Mohamed

samedi 9 septembre 2017

Session values gets destroyed when it is redirected after registration in laravel 5.1

I want to show errors and session flash message after redirection,I have dumped the session values after redirection.It shows only token value.All other session values are lost.My routes are grouped and its middleware is Auth.



via Chebli Mohamed

vendredi 8 septembre 2017

Laravel controller session store/retrieve troubles

I'm having troubles storing/retrieving data from session. My session variable from_date is not changing. At beginning, I'm checking if session has no value.

    if (!($request->session()->has('from_date')))
    {
        $from= date('Y-m-d', mktime(0, 0, 0, date("m") - 1, "01", date("Y")));
        session(['from_date' => $from]);            
    }
    else
    {
       $from=$request->session()->get('from_date');              
    }



via Chebli Mohamed

jeudi 7 septembre 2017

How to fetch values from URL in laravel 5.1

I have well researched and found that this question is unique. I am newbie to Laravel, I am sending link in email for forget password while in link there are 3 parameters email,id and time all encoded. Now When user click on that link further operations will begin. Now I am stuck at how to get all values from URL.

Here is my Link Code:

$url = $baseurl . "/changepwd/" . $id_enc . "/" . $email_enc . "/" . $time;

Here is my route:

Route::get('/changepwd/{$id}/{$email}/{$time}', 'UserController@change_password_web');

When user clicks on link that function:

public function change_password_web($id ,$email, $time)
    {
        echo $request->route('id');
    }

My Url says:

http://localhost/laravelproject/changepwd/MQ==/amF5bWluemFwQGdtYWlsLmNvbQ==/1504772185

When I try this error says

Sorry, the page you are looking for could not be found. NotFoundHttpException

Can anyone help me to resolve it?



via Chebli Mohamed

mercredi 6 septembre 2017

How to send Plain text body in email in laravel 5.1?

My email is sending properly with subject name, now I dont know how to send email body with simple text. The thing just now I am doing is sending blank email with just a subject name on it. Can anyone help me?

$data = array('title' => 'Forget Password - App', 'content' => 'This is the content of mail body');
           Mail::send(['text' => 'view'],$data, function ($message) {
                $message->from('fromemail@gmail.com', 'Social Team');
                $message->to('randomemail@gmail.com');
                $message->subject('App - Forget Password');
            });



via Chebli Mohamed

REST API post field validation Laravel 5.1

I need to check if I have all posted variables are required or else throw error. Till Now I am doing like this

Routes.php

Route::post('/api/ws_fetchuser', 'UserController@fetch_user_details');

UserController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
  public function fetch_user_details(Request $request)
    { 
        if(!empty($request) && $request->id!='')
        {
            print_r($request->id);    
        }
        else
        {
            return response(array(
            'error' => false,
            'message' =>'please enter all form fields',
            ),200);        
        }

    }
}

I am checking like this $request->id!='', is there any validation rules or methods which I can use to check id is required field.

I have added this validation in my controller as well but what if id is not present how can I show the error?

Updated Validation Code:

public function fetch_user_details(Request $request)
    { 
        $this->validate($request, [
        'id' => 'required'
        ]);

        print_r($request->id);

    }



via Chebli Mohamed

samedi 2 septembre 2017

Class 'Illuminate\Foundation\Auth\User' not found JWT Auth Laravel

I have written code for registration and login using JWT authentication. In this code registration function works fine but login function doesn't works. Login function prompts an error as Class 'Illuminate\Foundation\Auth\User' not found

My user model is

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    protected $table = 'users';
    public $timestamps = false;
    protected $primaryKey = 'user_name';
    protected $fillable = ['user_name','password'];
}

My UserController is

class UsersController extends Controller
{

    public function login()
    {
        $credentials = request()->only('user_name','password');
        try{
            $token = JWTAuth::attempt($credentials);
            if($token){
                return response()->json(['error'=>'invalid_credentials'],401);
            }
        }
        catch(JWTException $e){
            return response()->json(['error'=>'something went wrong'],500);
        }
        return response()->json(['token'=>$token],200);
    }

    public function register()
    {
        $user_name = request()->user_name;
        $password = request()->password;
        $user = User::create([
            'user_name'=>$user_name,
            'password'=>bcrypt($password)
        ]);

        $token = JWTAuth::fromUser($user);

        return response()->json(['token'=>$token],200);
    }
}

The login function shows the error as

Class 'Illuminate\Foundation\Auth\User' not found



via Chebli Mohamed

vendredi 1 septembre 2017

Laravel scheduled task without overlapping, run on demand

I have a scheduled task with Laravel defined as below to run every 10 minutes. I also need the same job to be run on-demand without it overlapping if it is already running or preventing the scheduled job starting to run if the on-demand job is running.

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
  $schedule->call(function () {
    $job = new \App\Jobs\ImportJob();
    $job->handle();
  })->name('Import')->everyTenMinutes()->withoutOverlapping();
}

Is there a nice, simple way of achieving this with the schedular API or should the Job take care of its own mutex flag?



via Chebli Mohamed