lundi 30 novembre 2015

Laravel: How to get URLs of uploaded files?

I have created an upload folder at the same level of app and storing uploaded files there. Now I need to access those file via browser so need to have an http:// based address.

First, am I doing right? What are Laravel 5.1's recommendation? Where should files be stored? If no recommendation then how do I get ULRs?



via Chebli Mohamed

How to show stores with nearest long/lat values using search function - Laravel 5 eloquent

Ideally I am looking for an Laravel 5 relevant answer. I am trying to make a store locator app. I am up to the point where I'm trying to match one pair of lat/long coordinates (calculated from an address that a user enters into search box) with the nearest (within 100km radius) coordinates/existing stores in my database.

The user enters an address which is converted (using geocoding) into lat and lng coordinates. These are sent to my 'articles' page which has a list of stores & a google map. I used a simple tutorial about scope search to show my articles/stores based on their text 'address'. But this obviously doesn't work for two coordinates. I have a table called Articles which has: id, address, lat, lng, website, title etc..

I need something like this or this but using eloquent.

Current Article Model:

    public function scopeSearch($query, $search){

    return $query->where('address', 'LIKE', "%$search%" );
   }

Articles Controller

 public function index(Request $request)
{
     $query = $request->get('q');
     $articles = $query
    ? Article::search($query)->get()
    : Article::all();
    return view('articles.index', compact('categories'))->withArticles($articles);
}

Current form/ geocode:

    {!! Form::open(['method' => 'GET', 'id' => 'searchForm', 'name' => 'searchForm', 'route' => 'articles_path']) !!}
      {!! Form::input('search', 'q', null, ['placeholder' => 'LOCATION', 'class' => 'locationSearch', 'id' => 'searchInput'])!!}
      {!! Form::hidden('lat', null, ['id' => 'lat'])!!}
      {!! Form::hidden('lng', null, ['id' => 'lng'])!!}
      {!! Form::submit('MAKE ME HAPPY', array('id' => 'submitButton')) !!}
    {!! Form::close() !!}

 <script>
$('#submitButton').on('click', function(event){
    event.preventDefault();
    var address = $('#searchInput').val();
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
             var lat = results[0].geometry.location.lat();
             var lng = results[0].geometry.location.lng();
             $('#lat').val(lat);
             $('#lng').val(lng);
          $('#searchForm').submit();

        } else {
            alert("Geocode was not successful");
        }
    });
});
</script>  



via Chebli Mohamed

Laravel 5.1 PHPUnit - press() gives me 'Unreachable field ""'

When trying to call the press() method, I always get

InvalidArgumentException: Unreachable field ""

at that line.

According to the docs:

"Press" a button with the given text or name.

My method: press('Create') and my button is <button class="btn btn-lg btn-primary" type="submit" name="submit">Create</button>. I have also tried to use the name with the same result.

I have also tried submitForm('Create') which works, but then seeInDatabase('employees', ['email' => 'john@email.com']) always fails.

Unable to find row in database table [employees] that matched attributes [{"email":"john@email.com"}].

Here is my full method

public function testExample()
{

  $this->actingAs(\App\Employee::where('username', 'grant')->first())
    ->visit('/employees/create')
    ->type('john', 'username')
    ->type('1234', 'password')
    ->type('john@email.com', 'email')
    ->submitForm('Create')
    ->seeInDatabase('employees', ['email' => 'john@email.com'])
    ->see('Employee Directory');
}



via Chebli Mohamed

PHPUnit and Laravel's Middleware

Currently I am supplying constants to views where the user is logged in by using the below Middleware:

<?php

namespace App\Http\Middleware;

use Closure;

/*
 * Middleware has replaced what used to be "filters"
 */
class AddConstantsFilesToAllRoutes
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        require_once app_path('constants') . '/constants2013andearlier.php';
        require_once app_path('constants') . '/constants20142015.php';
        require_once app_path('constants') . '/constants20152016.php';

        return $next($request);
    }
}

This works well for my views. However, when I try testing a user logging in with PHPUnit, I get an error that my constants are undefined, specifically in a service provider that I am using to supply the same sets of data to multiple views (which also works fine when not testing). Here is the error that PHPUnit gives me:

1) ExampleTest::testToSeeIfLoginLoads
A request to [http://ift.tt/1Q9CBqk] failed. Received status code [500].

C:\xampp\htdocs\BuddoBotLaravel\vendor\laravel\framework\src\Illuminate\Foundation\Testing\InteractsWithPages.php:166
C:\xampp\htdocs\BuddoBotLaravel\vendor\laravel\framework\src\Illuminate\Foundation\Testing\InteractsWithPages.php:64
C:\xampp\htdocs\BuddoBotLaravel\vendor\laravel\framework\src\Illuminate\Foundation\Testing\InteractsWithPages.php:110
C:\xampp\htdocs\BuddoBotLaravel\vendor\laravel\framework\src\Illuminate\Foundation\Testing\InteractsWithPages.php:64
C:\xampp\htdocs\BuddoBotLaravel\vendor\laravel\framework\src\Illuminate\Foundation\Testing\InteractsWithPages.php:86
C:\xampp\htdocs\BuddoBotLaravel\vendor\laravel\framework\src\Illuminate\Foundation\Testing\InteractsWithPages.php:653
C:\xampp\htdocs\BuddoBotLaravel\vendor\laravel\framework\src\Illuminate\Foundation\Testing\InteractsWithPages.php:640
C:\xampp\htdocs\BuddoBotLaravel\tests\ExampleTest.php:35
C:\xampp\php\pear\PHPUnit\TextUI\Command.php:176
C:\xampp\php\pear\PHPUnit\TextUI\Command.php:129

Caused by
exception 'ErrorException' with message 'Use of undefined constant NUM_TOTAL_ALB_BADGES - assumed 'NUM_TOTAL_ALB_BADGES'' in C:\xampp\htdocs\BuddoBotLaravel\app\Providers\ViewComposerServiceProvider.php:131
Stack trace:
#0 C:\xampp\htdocs\BuddoBotLaravel\app\Providers\ViewComposerServiceProvider.php(131): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Use of undefine...', 'C:\\xampp\\htdocs...', 131, Array)
#1 C:\xampp\htdocs\BuddoBotLaravel\app\Providers\ViewComposerServiceProvider.php(80): App\Providers\ViewComposerServiceProvider->provideALBTrackerData(Object(Illuminate\View\View))

If anyone can help me figure out how to get PHPUnit to recognize my constants, I'd appreciate it. Here is my PHPUnit test:

     /**
     * Tests to see if the login page loads 
     */
    public function testToSeeIfLoginLoads()
    {
        $this->visit('/login')
            ->see('Login')->see('Email Address')->see('Password')
            ->type('email@email.com', 'email')->type('mypassword', 'password')
            ->press('Log In')->see('Complete Course Summary');
    }

The problem is NOT that I have disabled the middleware in the PHPUnit test by using the withoutMiddleware() method or class. However, the problem I have described above does act like I have disabled the middleware, at least the middleware that my constants are being supplied in.

Thanks in advance.



via Chebli Mohamed

Laravel routes are not working

I have this really weird issue where the routing process on Laravel seems to not work at all.. I get NotFoundHttpException every time I try to load another route except the default one(/)

These are my files:

routes.php

<?php

Route::get('/', function () {
    return view('welcome');
});

Route::get('/test', function () {
    return "WORKING?";
});

website apache config (myquotes.conf located in /etc/apache2/sites-available)

<VirtualHost *:80>
    ServerName my.qoutes
    ServerAlias www.my.quotes
    ServerAdmin admin@my.quotes
    DocumentRoot /var/www/myquotes/public/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

hosts rule

127.0.0.1   my.quotes

And php artisan route:list returns this

+--------+----------+------+------+---------+------------+
| Domain | Method   | URI  | Name | Action  | Middleware |
+--------+----------+------+------+---------+------------+
|        | GET|HEAD | /    |      | Closure |            |
|        | GET|HEAD | test |      | Closure |            |
+--------+----------+------+------+---------+------------+

So I don't really understand where the problem is. If I try to load /test I get the error, if I edit the function form /, nothing happens in the browser, the same view with Laravel 5 on it is shown. I have some other websites in /var/www, are those the problem or influencing it? The routes from the other websites are not working either. What should I do?

EDIT: Tested in both Chromium and Firefox and the same



via Chebli Mohamed

Laravel 5.1 - Override default errors variables of the default login to differentiate between two forms on the same page

I am using Laravel 5.1 and i have a create form with a sidebar which also has a login form. Whenever i submit the create form and it has errors, i see the errors on both the login form and the create form. I understand why it's happening. I am using @include('errors.list') on both forms.

The list.php file inside errors

@if  ($errors->any())
        <div class="alert alert-danger alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            @foreach ($errors->all() as $error)
              <strong>• {{$error}}</strong><br/>
            @endforeach
        </div>
@endif

Now, i want to change the errors value on the login form when validation fails. I am using the default authentication form. I want to create something like if validation fails -> return with ('login_errors') instead of the default errors so i can use something like @if ($login_errors->any())

2nd question would be, how would i do the reverse without using custom validation? I am using $request, if i wanted to return the errors to the create form with custom_errors.



via Chebli Mohamed

manage big file in laravel.(how to load?)

I've a proxy file, it has 5000 different proxies, currently what I'm doing is, loading all proxies using Configurations(Laravel Config I personally thought that it is not a good technique). So please suggest some solution about this issue, another possible solution is to put file in storage directory and access it. I'm looking for some solution with good reason. Thanks

PS: I need one random proxy in each request(throughout the application life cycle), So what best way could be to implement it?

Thanks again.



via Chebli Mohamed

Returning Errors From AJAX Calls in Separate Javascript

Using the Laravel 5.1 framework, I have a situation where my page makes a call that is run through a Request form created with artisan where I have my requirements for the incoming data. This call goes through a function in an included javascript that contains a generic ajax call with parameters allowing its use on multiple pages. My issue is that if the Request throws an error (for formatting, or otherwise), it is returned through the ajax call to the external javascript, and because of the asynchronous nature the function ends before I can get the information back to the calling page where the errors need to be displayed.

Because (to my knowledge), you cannot return from an error/done callback, I've had to resort to moving the function to the page where it can be accessed in another instance of the issue. I'm hoping to avoid that here, though, as this function is used by four different pages and that would result in a lot of replication of code.

So my question is, how can I avoid making ajax synchronous to make a return work, or should I simply move the functions to the calling page?

Apologies if this is unclear, I'm writing in javascript but my understanding of best-practice architecture is still WIP.



via Chebli Mohamed

500 internal server error on fresh Laravel installation

I have just installed Laravel on my host following the official site's step by step guide and created an app called core, using the command

laravel new core

after seeing the success message I uploaded everything to my host, but when i try to access the /core/public folder from the browser i get 500 error on Chrome and nothing at all on firefox. if i run the command

php artisan list

On SSH inside my core folder i get:

Status: 500 Internal Server Error
Content-type: text/html

Can anyone of you Laravel experts let me know please where did i go wrong? thanks in advance

In the error log i found:

PHP Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in ...public_html/laravel/core/public/index.php on line 50

even though i haven't touched any files, line 50 is:

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);



via Chebli Mohamed

How to check if row is soft-deleted in Eloquent?

In Laravel 5.1 is there a nice way to check if an eloquent model object has been soft-deleted? I'm not talking about selecting data but once I have the object e.g. Thing::withTrashed()->find($id)

So far the only way I can see is

if ($thing->deleted_at !== null) { ... }

I do not see any relevant method in the API that would allow for example

if ($thing->isDeleted()) { ... }



via Chebli Mohamed

Laravel 5.1 Create table from controller

This is the situation: I have a list of user, this user are associate to a company and those companies are associate to a group. Each user can create a client who is associate to the user and the company in which the user belong. For the moment, all my client are in the same database table. But I want to have a clients table for each company.

I'm looking for the right way to create a clients table when i create a company. Example, when I create company A, the controller add the row A in the companies table then retrieve the company_id and create clients_id table. For now, I tried this:

    public function storeCompany(Request $request)
{
    $company= new Company;
    $company-> group_id     = Request::get('group_id');
    $company-> company_name  = Request::get('company_name');
    $company-> phone        = Request::get('phone');
    $company-> save();
    $company_id = DB::table('companies')->where('company_name',$company->company_name)->first();
    Schema::create('clients_'.$company_id, function($table) {
        $table->increments('id');
        $table->string('columntest');
    });
    return redirect('admin/managecompany');
}

I added this :

use Illuminate\Database\Schema\Blueprint;

But I got this error :

Class 'App\Http\Controllers\Admin\Schema' not found

Finally, I am trying to find an issue for my error and I want to know if there is an option to make it easier or any other suggestion to do it in a better way.

Thank you!



via Chebli Mohamed

Laravel 5.1 Task Scheduling command issue

I am trying to execute two console commands.Below is my two commands in my Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->command('users:get')->everyMinute();

    $schedule->command('users:update')->dailyAt('01:00');
}

When I run php artisan schedule:run, Only the command which is/are scheduled as everyMinute is scheduled.

Running scheduled command: '/usr/bin/php5' 'artisan' users:get > /dev/null 2>&1 &

If I change the dailyAt to everyMinute for the second command, both are scheduled as shown below

Running scheduled command: '/usr/bin/php5' 'artisan' users:get > /dev/null 2>&1 &

Running scheduled command: '/usr/bin/php5' 'artisan' users:update > /dev/null 2>&1 &



via Chebli Mohamed

Manageable structure in Eloquent

I need to use a Photo in several different places and cannot quite figure out what would be the best approach.

So basically, there is a gallery page on the website that shows a bunch of Photos. There is also a portfolio page, where each project has many Photos. There is a blog section too, and each blog has many Photos.

The common thing with these photos are that they have an image_url and a caption.

Project and Blog are Eloquent models and Photo model is a polymorphic model.

Project and Blog have:

public function photos()
{
    return $this->morphMany('App\Photo', 'imageable');
}

And the Photo model has:

public function imageable()
{
    return $this->morphTo();
}

This bit works fine. But my problem is that I want to attach this Photo model to the gallery as well. I'm thinking the two options I have, are:

  1. Create a Gallery model, which will have just one entry, as the gallery is just one page. And the model would have the same photos() method as above.
  2. When loading up the gallery page, retrieve all the photos that have imageable_id and imageable_type set to null. (This would mean that the photos that do not belong to neither Project nor Blog).

But I think there's a different, better approach that I cannot see. Any suggestions?



via Chebli Mohamed

How to use PostgreSQL's string_agg in Laravel Eloquent?

When I am trying to use, it's being treated as a string rather than as a function:

->select(['string_agg(file_name,',') as file_names'])



via Chebli Mohamed

Same route but call different controller in Laravel 5.1 routing

I have two url's one for category and one for brand such as:

http://localhost/project/womens-fashion #category
http://localhost/project/babette-clothes #brand

I just wanted to make one route but call different controller. I have written the route but its not work for me its send error. See below code:

<?php
use \DB;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Facades\Redirect;

Route::get('/','HomeController@index');
Route::get('/product', array('uses' => 'ProductController@index'));
Route::get('/{slug}', function($slug) {
    $result = DB::select('SELECT controller FROM url_setting where slug = ?', [$slug]);

    if ($result[0]->pw_us_controller == 'CategoryController@view') {
        return Redirect::action('CategoryController@view', array($slug));
    } elseif ($result[0]->pw_us_controller == 'CategoryController@view') {
        return Redirect::action('BrandController@index', array($slug));
    } else {
        return Redirect::action('HomeController@index');
    }
});

Error: InvalidArgumentException in UrlGenerator.php line 576: Action App\Http\Controllers\CategoryController@view not defined.

I am pretty confused, what went wrong? any idea!!!



via Chebli Mohamed

Laravel - Handle pages with wildcard route

In my application I need to set a route that respond to any pages.

I have put in my routes.php file:

// Handle all the pages
Route::get('{slug?}', 'Frontend\PageController@show');

and it works, the problem is that now I need an admin section so in my routes.php I added before the previous route:

Route::group( [ 'prefix' => 'admin', 'middleware' => config('admin.filter.auth') ], function(){
    // other routes
}  );

The problem is that the url site.com/admin has been catch by the wildcard so I'm not able to visit that url.

This is the full routes file:

//admin routes
Route::group( [ 'prefix' => 'admin', 'middleware' => config('admin.filter.auth') ], function(){

    Route::get('upload-file', 'Backend\UploadController@index');
    Route::post('upload-file', 'Backend\UploadController@uploadFile');
    Route::get('load-contacts', 'Backend\UploadController@loadContacts');

}  );

// Handle all the pages
Route::get('{slug?}', 'Frontend\PageController@show');

How should I manage this?



via Chebli Mohamed

Laravel Intervention Image Class - Class 'Image' not found

i'm trying to install 'intervention/image` from composer, but after install that i get this error:

Class 'Image' not found

1: install via composer:

composer require intervention/image 

2: add to providers array:

'Intervention\Image\ImageServiceProvider' 

3: add to aliases array:

'Image' => 'Intervention\Image\Facades\Image'

4: upadte composer

composer update

5: publish:

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5" 

public result:

Nothing to publish for tag [].

6: autoload

composer dump-autoload



via Chebli Mohamed

laravel 5.1 error in validating doc docx type file

Hi i am facing a docx type validation problem. I tried

$validator = Validator::make($request->all(), [
            'resume'   => 'mimes:doc,pdf,docx'
        ]);

It will upload pdf file with no error but whenever i try to upload docx files it gives validation error 'must be a file of type: doc, pdf, docx'
any idea



via Chebli Mohamed

Laravel how many relationship can be chained

I have a database composed by users, users_child, child.

I create a ONE to MANY relationship between Users and users_child, then i create a relationship between users_child and child. Now the below code work:

    $test = users::find(1)->users_child
    $test1= users_child::find(1)->child

Now i want to know if is possible to create a single row that link the three table like this:

    $test = users::find(1)->users_child->child

I create the relationship in the model but in the db i don't create Foreign Key, it's a problem? on the model i specify the field for link table.



via Chebli Mohamed

Laravel Access to several tables

I'm having an issue in accessing to data that are related in more than one table, here my code:

<table class="table table-striped">
    <thead>
        <th>Ejercicio</th>
        <th>Unidad</th>
        <th>Descripcion</th>
        <th>Tipo actividad</th>
        <th>Operaciones</th>
    </thead>
    @foreach($exercises as $exercise)
    <tbody>
        <td>{{$exercise->name}}</td>
        <td>{{$exercise->unit}}</td>
        <td>{{$exercise->description}}</td>
        <td>{{$exercise->activity_id}}</td>
        <td>
            <?php echo link_to('exercise/edit/'.$exercise->id, $title = 'Editar', $attributes = array('class' => 'btn btn-primary'), $secure = null); ?>                
        </td>
    </tbody>
    @endforeach
</table

on line <td>{{$exercise->activity_id}}</td> this is just a foreign key for another table named activity_type which has an id and a name, so what I wanted to be shown is the name with this id.

How can I do that?



via Chebli Mohamed

dimanche 29 novembre 2015

How to use Laravel 5.1 schedule?

I'm trying to use laravel 5.1 scheduler to run a data grabbing commands from twitter and store it in the database. If I put the actual command within the Kernel.php file it runs no worries and gets/inserts the data into the database but when I try put it into an external file to run and just put the command in the Kernel I get this

Running scheduled command: (touch/storage/framework/schedule-4ff51352255727a7381f73c7bd3eb90c; '/Applications/MAMP/bin/php/php5.5.18/bin/php' 'artisan' lookup; rm /storage/framework/schedule-4ff51352255727a7381f73c7bd3eb90c) > /dev/null 2>&1 &

This is my Kernal.php file

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use DB;
use Session;
use Carbon\Carbon;
use Thujohn\Twitter\Facades\Twitter;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
protected $commands = [
    \App\Console\Commands\Inspire::class,
    \App\Console\Commands\Scheduled_post::class,
];

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->command('lookup')
             ->everyMinute()
             ->withoutOverlapping();
}
}

and my command

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;

class Lookup extends Command
{
/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'Lookup';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Performing user lookup';

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $user_lookup = Twitter::getUsersLookup(['screen_name' => 'some_user', 'format' => 'object']);
        $social_user = array(
            'email'                     => null,
            'screen_name'               => $user_lookup[0]->screen_name,
        );
        DB::table('social_users')->insert( $social_user );
}
}

Testing in MAMP, manually executing php artisan schedule:run through terminal to test.

Im not sure how to fix this or whats going on?



via Chebli Mohamed

Bootstrap css help : centered well

i want to center the well .. plz help me out.. here is my code and screenshot. the well i have added should appear in the middle.. what should i do?

<div class="container" id="profile" >

        <div class="col-md-6">
            <div class="well well-sm">
                <div class="row">
                    <div class="col-sm-6 col-md-4">
                        <img src="img/tawsif.jpg" alt="" class="img-rounded img-responsive" />
                    </div>
                    <div class="col-sm-6 col-md-8">
                        <h4>
                            Tawsif Karim</h4>
                        <small><cite title="Dhaka, Bangladesh">Dhaka, Bangladesh <i class="glyphicon glyphicon-map-marker">
                        </i></cite></small>
                        <p>
                            <i class="glyphicon glyphicon-envelope"></i>tawsif.karim@gmail.com
                            <br />
                            <i class="glyphicon glyphicon-globe"></i><a href="http://ift.tt/1kH0iEY">http://ift.tt/1NhKe8J;
                            <br />
                            <i class="glyphicon glyphicon-gift"></i>June 08, 1992</p>


                    </div>
                </div>
            </div>
        </div>

</div> 

enter image description here

after using offset



via Chebli Mohamed

Laravel insert FOREIGN KEY in Form Request method

in my application some tables are relationShip and i must be insert FOREIGN KEY to table as User id. i dont have any problem with create new instanse from model and use save() method. but i like to use Form Request method to create and update records,

i get this error and i can not solve that:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a >child row: a foreign key constraint fails (epaypro.merchand_web_service, >CONSTRAINT merchand_web_service_user_id_foreign FOREIGN KEY (user_id) >REFERENCES users (id)) (SQL: insert into merchand_web_service >(updated_at, created_at) values (2015-11-29 11:31:54, 2015-11-29 11:31:54))

this is my model:

namespace app;
use Illuminate\Database\Eloquent\Model;
use Morilog\Jalali\jDate;

class Merchant extends Model
{
    protected $table = 'merchand_web_service';
    protected $fillable = ['customer_key', 'company_name', 'company_logo'];

    /**
     * @return mixed
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

store method on Controller:

public function store(StoreMerchantWebServiceRequest $request)
{
    Merchant::create($request->all());
    return redirect()->route('post.index');
}

StoreMerchantWebServiceRequest class:

class StoreMerchantWebServiceRequest extends Request
{
    public function authorize()
    {
        if (Auth::check()) {
            return true;
        } else
            return false;
    }

    public function forbiddenResponse()
    {
        return Response::make(trans('message.permission_denied'), 403);
    }

    public function rules()
    {
        return [
            'agent_company_name' => 'required',
            'agent_company_logo' => 'mimes:jpg,jpeg,bmp,png|max:300',
        ];
    }
}

My Test (in controller):

public function store(StoreMerchantWebServiceRequest $request)
{
    $order = Merchant::create($request->all());
    $this->user_id = Auth::user()->id;
    $order->save();
    return redirect()->route('post.index');
}



via Chebli Mohamed

laravel 5.1 MarphToMany & MarphByMany with custom fields

I am having custom fields in table and want to MorpTohmany with other tables. how to do it with custom fields.

In below model (salepurchase) request_to is supplier model foreign key, where salepurchase_type and salepurchase_id these will contain other model relation, Like Warehouse, Shop etc

SalePurchase Model

+----+------------+-------------------+-----------------+-------------+
| id | request_to | salepurchase_type | salepurchase_id | total_items |
+----+------------+-------------------+-----------------+-------------+
|  1 |          1 | Warehouse         |               1 |          10 |
|  2 |          1 | Warehouse         |               1 |          10 |
|  3 |          1 | Warehouse         |               1 |          11 |
|  4 |          1 | Shop              |               7 |          15 |
|  5 |          1 | Shop              |               5 |          19 |
+----+------------+-------------------+-----------------+-------------+

Warehouse Model

+----+-------------+
| id | name        |
+----+-------------+
|  1 | warehosue 1 |
|  2 | warehosue 2 |

Shop Model

+----+-------------+
| id | name        |
+----+-------------+
|  5 | Shop 1      |
|  7 | Shop 2      |

Supplier Model

+----+--------------------------+
| id | qualified_person         |
+----+--------------------------+
|  1 | Marks                    |
|  2 | test                     |
+----+--------------------------+



via Chebli Mohamed

LaravelLocalization::localizeURL with variable

I have got some problem. I create edit form - http://localhost/article/edit/{id}. This form redirect to http://localhost/article/edit/{id} with POST method.

{!! Form::open(array('route' => array('article_edit', $article->id))) !!}

If something was wrong redirecto to edit form with:

return redirect()->back()->withErrors($validator)
                        ->withInput();

but when everything is okay i would like redirect to article show

return redirect(
    LaravelLocalization::localizeURL(
        LaravelLocalization::transRoute('routes.article_show')
    )
)->with('slug', $slug);

but this not work.

What i should do?

My router file:

Route::group(['prefix' => LaravelLocalization::setLocale()], function()
{
    Route::get(
        LaravelLocalization::transRoute('routes.article_edit'),
        array(
            'as' => 'article_edit',
            'uses' => 'ArticlesController@edit'
        )
    )->where('id', '[0-9]+');
    Route::post(
        LaravelLocalization::transRoute('routes.article_edit'),
        array(
            'as' => 'article_edit',
            'uses' => 'ArticlesController@update'
        )
    )->where('id', '[0-9]+');
    Route::get(
        LaravelLocalization::transRoute('routes.article_show'),
        array(
            'as' => 'article_show',
            'uses' => 'ArticlesController@showByString'
        )
    )->where('slug', '[A-Za-z]+');
}

lang router:

return [
    "article_edit"  =>  "article/edit/{id}",
    "article_show"  =>  "article/show/{slug}",
];

Thanks for answer



via Chebli Mohamed

Laraval 5.1 HasMany Relationship Issue

I have 3 tables posts, comments and likes. One post can have multiple comments and one comments can have multiple likes. How can I define relationship between 3 tables to fetch all posts details, including comments and likes of particular post_id in laravel 5.1?

Tables in DB

  1. posts

    • post_id
    • post_detail
  2. comments

    • comment_id
    • post_id
    • comment
  3. likes

    • like_id
    • comment_id


via Chebli Mohamed

Laravel - Deleting Reset Passwords Does nothing

so we are trying to modify the resetpasswords.php file found in /vendor/laravel/src/illuminate/foundation/auth/etc...

So when we modify it locally and test it works fine on my xampp install running windows.

When we modify it on our webserver and test it on linux. It doesn't. No matter the changes to the file nothing happens at all.

We can delete the file and the site will still work even though those functions are not there anymore.

Could use ANY advice on this.

Thank you!



via Chebli Mohamed

Laravel 5.1 - File::exists doesn't work?

Interestingly enough if I use this to check for the existence of a file:

if (File::exists('path/to/file')) { do stuff }

I get a File Not Found error that breaks the app if the file doesn't exist. Am I doing something wrong here?



via Chebli Mohamed

Creating a manageable structure for Eloquent in L5

I need to use a Photo in several different places and cannot quite figure out what would be the best approach.

So basically, there is a gallery page on the website that shows a bunch of Photos. There is also a portfolio page, where each project has many Photos. There is a blog section too, and each blog has many Photos.

The common thing with these photos are that they have an image_url and a caption.

Project and Blog are Eloquent models and Photo model is a polymorphic model.

Project and Blog have:

public function photos()
{
    return $this->morphMany('App\Photo', 'imageable');
}

And the Photo model has:

public function imageable()
{
    return $this->morphTo();
}

This bit works fine. But my problem is that I want to attach this Photo model to the gallery as well. I'm thinking the two options I have, are:

  1. Create a Gallery model, which will have just one entry, as the gallery is just one page. And the model would have the same photos() method as above.
  2. When loading up the gallery page, retrieve all the photos that have imageable_id and imageable_type set to null. (This would mean that the photos that do not belong to neither Project nor Blog).

But I think there's a different, better approach that I cannot see. Any suggestions?



via Chebli Mohamed

How can I manage OAuth refresh tokens with Laravel?

The Socialiate plugin provides an implementation for OAuth in Laravel, but it seems to be designed for mostly for the purpose of allowing them to not have to make a user account on your own site.

I am making an application that helps manage their Youtube account, meaning the scope of the auth request is broader (which was easy to change) but I also need a refresh token (versus just an access token) for long-term access to their account.

Is there a package out there for Laravel that already handles this? I haven't been able to find one, but maybe I'm searching for the wrong thing.

If not, how should I approach this? When I write my code that interacts with Youtube's API, do I simply need to check whether the access token is expired, and if so, write a function that does an HTTP request to get a new one with the refresh token I have stored in the database? And I guess also extend Socialite to retrieve a refresh token?

I feel like there's got to be a better way that doesn't involve me re-inventing the wheel. Google has the api-client-library for PHP but no one has integrated this into Laravel, and doing so is a bit outside my abilities.



via Chebli Mohamed

New IIS 7 site not loading any PHP/HTML pages

we have an IIS 7 server hosting different sites/applications. Take not that this server is hosting other site/site-applications running on either asp or php. There is already an existing site application running thru fastCGI php.

I now added a new site (not a site-application) - a laravel 5.1 framework, to the IIS server, but this new site is not loading anything. Tried a test php page which echos phpinfo() only and i also made a static html file with just "Hello world" on it but to no avail.

Checked my handlers, and my php handler is there.

When i try to browse the sites host name I get this error:

The server at [mysubdom].[domain].com can't be found, because the DNS
lookup failed. DNS is the network service that translates a website's name to
its Internet address. This error is most often caused by having no connection to
the Internet or a misconfigured network. It can also be caused by an 
unresponsive DNS server or a firewall preventing Google Chrome from accessing 
the network.

Is this really a DNS problem?



via Chebli Mohamed

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.store' doesn't exist

When I try to save data from laravel form to a database table I am getting the following exception:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.store' doesn't exist (SQL: select count(*) as aggregate from store where name = samplename)

the table store exists but still I am getting the error

this is my contoller that is processing the form:

 <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use App\storestore;
    use App\Http\Requests\storeFormRequest;



    class AddstoreController extends Controller
    {
        //

        public function create()
        {
            //

        }

        public function store( storeFormRequest $request)
        {

            $store = new Store;
            $store->name = Input::get('name');
            $store->description = Input::get('description');
            $store->store_vendor_id = Input::get('owner');
            $store->contact_email = Input::get('contact_email');
            $store->postal_address = Input::get('postal_address');
            $store->city = Input::get('city');
            $store->zip = Input::get('zip');
            $store->phone = Input::get('phone');
            $store->business_logo = Input::get('logo');
            $store->save();
            return \Redirect::route('add_store_success')
          ->with('message', 'Thanks for joining us!');
        }
    }

This is my Store model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Store extends Model
{
    //

    protected $table = 'stores';

     protected $fillable = ['name', 'description', 'vendor_id',
     'contact_email','postal_address','city','zip','phone',
     'meta_description','business_logo'];

 }

StoreRequest file:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

use App\StoreController;


class StoreFormRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
    'name' => 'required|unique:dstore',
    'vendor_id' => 'required',
    'contact_email' => 'required|email|max:100|unique:dstore',

    'business_logo' => 'required',

        ];

         //validate
        if ($validation->fails())
        {
            return redirect()->back()->withErrors($v->errors());
        }

    }


}

These are the get and post routes:

Route::get('/store_form', ['as' => 'add_store_form', 'uses' => 'StoreController@create']);
Route::post('/store_form',['as' => 'dstore', 'uses' => 'StoreController@store']);

Both routes are listed when I run php artisan route:list command

I have tried to goggle for solution but the one I landed on pointed out to missing tables as a course, but in my case the store table is existing but still I am getting the error.

Any help please!



via Chebli Mohamed

How to make a url with parameters? Laravel 5.1

I need to make a url with undetermined number of parameters. So I want to make search.

For example:

http://ift.tt/1jrEWA2?}

http://ift.tt/1XpFQja
http://ift.tt/1jrEXE4
http://ift.tt/1XpFSHD
test.com/breakfast

ingredients and eingredients are arrays.

ingredients - included in the recipe (ids) eingredients - excluded from the recipe (ids)

I have an idea:

Route::get('/recipes/{category?}/{country?}/{ingredients?}/{eingredients?}', 'RecipeController@index')
->where(['ingredients' => '^ingredients/[0-9\/]+$', 'eingredients' => '^eingredients/[0-9\/]+$']);

but it does not work:

http://ift.tt/1jrEXE4

I get page 404...

How i can make it?

P.S: I just started learning laravel.



via Chebli Mohamed

Laravel 5.1: $errors->all() like response via ajax

Laravel 5.1: When a user is authenticated via regular POST request, an array of all validation errors can be accessed via method $errors->all(). However when a user is authenticated via Ajax request, that property is not available in the returned object. How can I make Validator to return error messages with $errors->all() or in the same structure when authenticating via Ajax request?

public function postLogin(Request $request)
{
    $this->validate($request, [
            $this->loginUsername() => 'required', 'password' => 'required',
        ]);

    $credentials = $this->getCredentials($request);

    if (Auth::attempt($credentials, $request->has('remember'))) {
        return $this->handleUserWasAuthenticated($request, $throttles);
    }
}



via Chebli Mohamed

Laravel 5.1 file upload, File's same name for folder and database

My controller code where i store the file name into a database table and also moving the file to a folder.

The issue is that i am storing the original name of a file in database table, in contrast i am moving files with uniqueid() and time() . It will arise issues in future. because in database table file name and moved file are with different names.

if(Input::hasFile('profile_pic')){
            $pic = Input::file('profile_pic');
            $mobile->photo1 = $pic[0]->getClientOriginalName();
            $mobile->photo2 = $pic[1]->getClientOriginalName();
            $mobile->photo3 = $pic[2]->getClientOriginalName();
            $mobile->photo4 = $pic[3]->getClientOriginalName();
            $mobile->photo5 = $pic[4]->getClientOriginalName();
                foreach ($pic as $k=>$file){
                    if(!empty($file)){
                        $file->move(public_path() . '/uploads/', time() . uniqid() . '-' . $k . '-laptop');
                    }
                }
        }



via Chebli Mohamed

JasperPHP error "Your report has an error and couldn't be processed! ...."

I'm trying to generate reports using JasperPHP library in my laravel application and facing the error:

Exception in JasperPHP.php line 178: Your report has an error and couldn't be processed! Try to output the command using the function output(); and run it manually in the console.

My php code:

$database = array(
        'driver'    => 'mysql',
        'database'  => 'infolady_service',
        'username'  => 'root',
        'host' => 'localhost',
        'password'  => '',
        'charset'   => 'utf8',
    );
    $output = public_path() . '/report/'.time().'_codelution';
    $ext = "pdf";

    $jasper = new JasperPHP;
    // Compile a JRXML to Jasper
    $jasper->compile(__DIR__ . '/../../vendor/cossou/jasperphp/examples/hello_world.jrxml')->execute();

    // Process a Jasper file to PDF and RTF (you can use directly the .jrxml)
    $jasper->process(
        __DIR__ . '/../../vendor/cossou/jasperphp/examples/hello_world.jasper',     //.jasper file link
        $output,                                                                    //Output location
        array($ext),                                                                //Extension name
        array(),                                                                    //Any parameter as variable
        $database,                                                                  //DB informations
        false,                                                                      
        false
    )->execute();



via Chebli Mohamed

How can i run Laravel Queue only once?

I used laravel 5.1 Queue for my background function with async. But i want to run that function for only 1 time. If that function fail, i want to do other process. How can i detect my job is failed or not? Am i doing right or wrong ? What should i change? ps: I'm beginner. I used like this in my controller.

$job = new myjob($var1, $var2);
$this->dispatch($job);
$job->release();
if ($job->attempts() >= 1)
{
    $job->delete();
    //will do other process
}



via Chebli Mohamed

Using Cache Fasade in Laravel 5 Service Provider

I have to write Custom Service provider in Laravel 5 and I am getting this error:

[Symfony\Component\Debug\Exception\FatalErrorException] Call to undefined method Illuminate\Support\Facades\Cache::forever()

Here is my code:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use TADPHP\TADFactory;
use Cache;


class TADServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $options = [
            'ip' => '192.168.0.201',
            'internal_id' => 1,
            'com_key' => 0,
            'soap_port' => 80,
            'udp_port' => 4370,
            'encoding' => 'utf-8',    // iso8859-1 by default.
            'connection_timeout' => 2
        ];

        Cache::forever('options', $options);

        // $this->app->instance('TADF',$this->app->make('TADPHP\TADFactory', [$options])->get_instance());

        $this->app->bind('TADF', 'TADPHP\TADFactory', function($app)
        {
            return new TADPHP\TADFactory(Cache::get('options'));
        });

    }
}

Basically I am trying to store the options array in cache and later in my app when I call app()->make('TADF') to get an instance of this class using the options stored in cache. I am new to Laravel, so there is a better way to do this. Thanks.



via Chebli Mohamed

laravel having: Column not found

my following code is like this:

$places = DivePlace::selectRaw("*,(st_distance_sphere( POINT(".$lon.",".$lat.") ,  point(lon, lat))/1000) as distance")
    ->havingRaw("distance < ".$radius)
    ->orderBy("distance")
    ->paginate(10);

without the "havingRaw" everything is good. After adding it, the following error came up:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'distance' in 'having clause' (SQL: select count(*) as aggregate from dive_places having distance < 300)

Any solution?



via Chebli Mohamed

How to get postback data in laravel blade

If I have a form with a hidden input how can I check that value in my blade template upon validation postback?

So in the example below how can I get the value of form_type:

@if (Request::isMethod('post') && $request->form_type == 'login')
   // some stuff 
@elseif (Request::isMethod('post') && $request->form_type == 'register')
  // some other stuff
@endif

 {!! Form::open(['method' => 'POST', 'url' => 'login']) !!}
     {!! Form::hidden('form_type', 'login') !!}
     // some other inputs
 {!! Form::close() !!}

 {!! Form::open(['method' => 'POST', 'url' => 'register']) !!}
     {!! Form::hidden('form_type', 'register') !!}
     // some other inputs
 {!! Form::close() !!}



via Chebli Mohamed

Laravel create simple RelationShip and get User data from other table

i'm created simple RelationShip from two table as User and Merchant :

class User extends Model implements AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    protected $table = 'users';

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }
    public function merchant()
    {
        return $this->hasMany('App\Merchant');
    }
}

in App\Merchant is:

class Merchant
{
    protected $table = 'merchand_web_service';
    protected $fillable = ['agent_unique_id', 'agent_company_name', 'agent_company_logo'];

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

and my Migration file is:

class MerchandWebService extends Migration
{
    public function up()
    {
        Schema::create('merchand_web_service',function(Blueprint $table){
            $table->increments('id');
            $table->string('customer_key','50');
            $table->string('company_name','50');
            $table->string('company_logo','100');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('merchand_web_service');
    }
}

now i want to access User data on Merchant table on database by this code on Controller :

$all_records = Merchant::with('user')->orderBy('id', 'DESC')->paginate(50);

Unfortunately i get this error:

Call to undefined method app\Merchant::with()



via Chebli Mohamed

Laravel 5.1 file upload naming

My controller code where i store the file name into a database table and also moving the file to a folder.

The issue is that i am storing the original name of a file in database table, in contrast i am moving files with uniqueid() and time() . It will arise issues in future. because in database table file name and moved file are with different names.

What i want is to store the file name into database table and move the file to folder with with uniqueid() and time().

Code :

if(Input::hasFile('profile_pic')){
            $pic = Input::file('profile_pic');
            $mobile->photo1 = $pic[0]->getClientOriginalName();
            $mobile->photo2 = $pic[1]->getClientOriginalName();
            $mobile->photo3 = $pic[2]->getClientOriginalName();
            $mobile->photo4 = $pic[3]->getClientOriginalName();
            $mobile->photo5 = $pic[4]->getClientOriginalName();

                foreach ($pic as $k=>$file){
                    if(!empty($file)){
                        $file->move(public_path() . '/uploads/', time() . uniqid() . '-' . $k . '-laptop');
                    }
                }
        }



via Chebli Mohamed

Verify ownership of a website

I'm creating a website where people can sell and buy digital products like websites, domains, scripts etc. My question is how can I determine if the user who wants to sell his website is really the owner of the website and not just an administrator or a developer who has access to the files? If anybody can give my an answer on this and a reference of technology to use to verify the ownership would be really great. I'm using laravel 5.1 for this project. Thanks in advance



via Chebli Mohamed

Modify input in laravel middleware

Some service makes HTTP request to my site and passes some input. This input has a little bit wrong structure for me, so I'm trying to modify it.

I made a middleware and attached this middleware to my route. The handle method looks like this:

public function handle($request, Closure $next)
{
    $input = $request->all();

    // Input modification

    $request->replace($input);
    \Log::info($request->all()); // Shows modified request

    return $next($request);
}

However in my controller I got old input. Also I'm a little bit confused since I also use FormRequest, and as I realize these two requests are different entities. Then how can I modify the input in the middleware?



via Chebli Mohamed

samedi 28 novembre 2015

Laravel: How to insert an item in Select which is pre populated with records?

I am using Laravel 5.1. In form I am generating drop down as:

{!! Form::select('ptype', $p_types,null,['class' => 'form-control text-capitalize']) !!}

While in controller $p_types is set as:

$p_types = PType::lists('name', 'id');

I want to show an option as Select here on top of drop down. How do I do tat?



via Chebli Mohamed

syntax error, unexpected '!' in laravel 5.1

I am trying to use Html:: class in blade template 5.1, I have tried everything before I was getting error of class HTML not found but when I use {{ !! HTML:: !!}} before html, the error is now FatalErrorException in 75e2b4fe5a49ad69bec8641db04b4b16 line 10: syntax error, unexpected '!' guide me please here is code, Index.blade.php

    <li> {{ !! Html:: link_to_route('author',
    $authorname->name, array($authorname->id)) !! }}</li>

    Route: Route::get('authors/{id}', array('as' => 'author', 'uses' => 
    'authors_controller@get_view'));

    Composer.json: `"require": {
    "laravelcollective/html": "5.1.*"
   },

   app.php Providers: `Collective\Html\HtmlServiceProvider::class,`             
   app.php Aliases: 
   'Form' => Collective\Html\FormFacade::class,
   'Html' => Collective\Html\HtmlFacade::class,

and I have used the composer update command or composer require illuminate/html all of these things



via Chebli Mohamed

my laravel stop working after i cut and repaste css and view file

my laravel 5.1 suddenly stop working after cut and repaste the css and views folder

it displays this error

Warning: require(C:\xampp\htdocs\yssb\public/../bootstrap/autoload.php): failed to open stream: No such file or directory in C:\xampp\htdocs\yssb\public\index.php on line 22

Fatal error: require(): Failed opening required 'C:\xampp\htdocs\yssb\public/../bootstrap/autoload.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\yssb\public\index.php on line 22



via Chebli Mohamed

How to setup MySQL database for demo version?

My Laravel project uses MySQL. I want to host my project's demo version where anyone can login using the given credentials and perform any operation he is permitted to with his role. When he logs out the changes he made should be gone. And at the same time multiple users with same credentials can manipulate data which should be isolated without making changing to other's current database. How can I achieve this ?



via Chebli Mohamed

Laravel 5.1: Many-to-many alongside one-to-many relationship

I'm making an event RSVP app where a user creates an event (or events), and can allow other users to manage the event with them.

I also need to specify which user is the owner (creator) of an event.

My goal is to determine:

the user that owns an event

the users that can manage an event

the events a user owns

the events a user can manage

And also:

How I can create a user, then create an event, assign its owner and also add it to the event_user table at the same time

These are my current relationships...

Event Class - App\Event

public function owner()
{
    return $this->belongsTo('App\User', 'owner_id');
}

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

User Class - App\User

public function owns()
{
    return $this->hasMany('App\Event', 'owner_id');
}

public function manages()
{
    return $this->belongsToMany('App\Event');
}

Current migrations...

Users migration - users

$table->increments('id');
$table->string('name');

Events migration - events

$table->increments('id');

$table->integer('owner_id')->unsigned();

$table->string('name');

$table->timestamps();

$table->foreign('owner_id')->references('id')->on('users')
    ->onUpdate('cascade')->onDelete('cascade');

Event User - event_user

$table->increments('id');
$table->integer('event_id')->unsigned();
$table->integer('user_id')->unsigned();

$table->foreign('event_id')->references('id')->on('events')
      ->onUpdate('cascade')->onDelete('cascade');

$table->foreign('user_id')->references('id')->on('users')
      ->onUpdate('cascade')->onDelete('cascade');

However when I play around in artisan tinker I can only get one of the methods to work.

$user = App\User::find(1);
$event = new App\Event(['name' => 'Event 1']);

$user->owns()->save($event);

The above example works to assign the owner_id in the events table

$user = App\User::find(1);
$event = new App\Event(['name' => 'Event 2']);

$user->sites()->save($site);

This fails outright, where previously it did work before adding the one-to-many methods...

How can I create a user, then create an event, assign its owner and also add it to the event_user table?



via Chebli Mohamed

How to include html tags to laravel flash message?

Is there a way to include html tags within a flash message. I have the following but the tags get escaped when rendered in blade?

 flash()->success('Confirmation email sent to <strong>' . $user->email . '</strong>');



via Chebli Mohamed

Laravel 5.1 querying a database with millions of records

I have a product database with close to 3 million records. I am writing a webservice to query the db. The output will be assigned to an array in the client for string matching (exprience similar to you start type ipod in google's search box). Any suggestions on how can I optimize the query or cache it in such a way that new cache is created only upon the product refresh. The product DB will be refreshed every week with new products which means the number of records will grow over time.



via Chebli Mohamed

Modify all attributes of a Laravel model

Accessors will do their job on a single attribute perfectly, but I need a way to have a method to do an Accessor/Getter job on all attributes and automatically.

The purpose is that I want to replace some characters/numbers on getting attributes and then printing them out. I can do it from within controller and manually but I think it would be great to have it from model side and automatically.

Like overriding getAttributes() method:

public function getAttributes()
{
    foreach ($this->attributes as $key => $value) {
        $this->attributes[$key] = str_replace([...], [...], $value);
    }
    return $this->attributes;
}

But I have to call it every time on model $model->getAttributes();

Any way to do it automatically and DRY?



via Chebli Mohamed

How to move the laravel 5.1 User model to \App\Models\User?

Is it possible to tell Laravel that I have moved the User.php model?

Laravel 5.1

FatalErrorException in EloquentUserProvider.php line 126: 
Class '\App\User' not found

I really wasn't keen on having all the models at the root of the App folder in laravel 5.1 so I created a new folder and placed all the model php files within it: \App\Models

I altered the auth controller to use the new use App\Models\User; and corrected all the model files within the model folder..

However when i load the page I get the error mentioned above.

(the other model files of course work fine as it is my code accessing them, it is just the prebuilt auth stuff from laravel 5.1)



via Chebli Mohamed

Strange Exception telling the file does not exist or is not readable in Laravel 5.1

I'm getting reports with exceptions like these:

exception 'InvalidArgumentException' with message 'The file "/var/www/http://ift.tt/1MWBYvF" does not exist or is not readable.' in /var/www/http://ift.tt/1RdcwHL
Stack trace:
#0 /var/www/http://san
...

As you can see it's weird that it's trying to access that does not exist for sure /var/www/http://sandbox4b5ace....

The type of Exception may change. I've put here the full dump of it.

I've no clue of why is this throwing this Exception, the only thing I recognize is the file path has as string taken from the mailgun api sandbox credentials. So, I'ts strange.

Any light on this is welcome.

The full project is here



via Chebli Mohamed

Laravel 5.1 GeoIP Non-static method should not be called statically, assuming $this from incompatible context

I am using Torann\GeoIP And I am getting this error when I try

    use Torann\GeoIP\GeoIP;
Route::get('geoip', function() {
    $location = GeoIP::getLocation();
});

but when I try with

    $geo = new GeoIP();
$geo - getLogation();

I have this error 'Argument 1 passed to Torann\GeoIP\GeoIP::__construct() must be an instance of Illuminate\Config\Repository, none given'

so I am missing the arguments for the __construct ....$config, $session so it should be looking like this

$loc = new GeoIP($config, $session);
$loc ->getLocation();

but what do I need to give to $config = ? and $session = ?

Any siggestions will be helpfull. Thank you

If there is better way to get the GeoLocation data it would be great.



via Chebli Mohamed

Laravel 5.1 with gettext gives undefined function _() in console commands

I'm using Laravel 5.1 on Homestead. I translate strings with the Xinax/Gettext package (http://ift.tt/1Ngew03). It all works perfectly except for when trying to run a console command containing translatable strings, for example _('Test string').

The error I get is:

[Symfony\Component\Debug\Exception\FatalErrorException]  
Call to undefined function App\Console\Commands\_()

Any ideas on how to get the gettext functionality to work in the console environment?



via Chebli Mohamed

Laravel Blade Name Convention

Is there a naming convention for laravel blade templates e.g should I use hyphens, snake case or camel case where I have a template name that consists of two or more words?

register-confirm.blade.php

or

register_confirm.blade.php

or

registerConfirm.blade.php



via Chebli Mohamed

Page on VPS in laravel don't working

I bought VPS and installed on it Laravel, main page working normal and i getting subtitle "Laravel 5" but when i created test page i route file:

Route::get('/test', function() { return 'test' ; });

I getting this:

`Not Found

The requested URL /test was not found on this server.

Apache/2.4.7 (Ubuntu) Server at plerp.net.pl Port 80`

Sory for not format post, i writting on phone. I chmod storage folder on 777.Please help me, thanks.



via Chebli Mohamed

Laravel request URI not working

I have the following route group:

Route::group(['prefix' => 'admin'], function () {

     Route::get('/', 'PagesController@index');

     // some more routes...
});

In my layout file I have the following condition:

 @if (Request::is('admin/*'))
            @include('layouts.partials.admin_header')
 @else
            @include('layouts.partials.header')
 @endif

When I navigate to http://ift.tt/1XmTvHH it's not displaying in the admin header file?



via Chebli Mohamed

Setting up Queue in Lumen Framework

I'm trying to set up queue in Lumen using the guide from lumen page: http://ift.tt/1XxL9rt

<?php

namespace App\Jobs;

use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

class BlastEmail extends Job implements SelfHandling, ShouldQueue
{
    public function sendEmail()
    {
        [...CODE TO SEND EMAIL...]
    }

    public function handle()
    {
        $this->sendEmail();
    }
}

and in My Controller

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Jobs\BlastEmail;
use App\Models\Blast;
use App\Models\Subscriber;
use Illuminate\Http\Request;
use Validator;

class BlastsController extends BaseController
{
    public function queue(Request $request)
    {
        $job = (new BlastEmail($email,$request->input('content'),$request->input('title')));
        $this->dispatch($job);
    }
}

And I got "Undefined method App\Http\Controllers\BlastsController::dispatch"

Do I miss something?



via Chebli Mohamed

vendredi 27 novembre 2015

Method Not Allowed exception Laravel 5.1

This is probably something super basic but consider the route file:

Route::get('/', 'WelcomeController@getIndex');
Route::post('/', 'WelcomeController@postIndex');

Route::get('/registered-games', 'GameController@getIndex');

When I am on getIndex for WelcomeController and I make a post via a form I should be redirected back to the getIndex as per the controller below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Squidward\Domain\Entities\GameEntity;

class WelcomeController extends Controller {

    public function getIndex() {
        return view('welcome', ['homeEnabled' => true]);
    }

    public function postIndex(Request $request) {

        $gameEntity = new GameEntity();
        $gameEntity->name = $request['game_name'];
        $gameEntity->save();

        return redirect('/')->with('success', 'Game has been registered successfully.');
    }
}

But Instead I get:

MethodNotAllowedHttpException in RouteCollection.php line 219:

in RouteCollection.php line 219
at RouteCollection->methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php line 206
at RouteCollection->getRouteForMethods(object(Request), array('GET', 'HEAD')) in RouteCollection.php line 158
at RouteCollection->match(object(Request)) in Router.php line 754
at Router->findRoute(object(Request)) in Router.php line 663
at Router->dispatchToRoute(object(Request)) in Router.php line 639
at Router->dispatch(object(Request)) in Kernel.php line 236
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
....

I am sure its something super basic and noobish but this error doesn't make sense to me ...



via Chebli Mohamed

How to show a fancy 404 page and recording/emailing all exception to Admin

I am on Laravel 5.1. Usually it shows exception etc on page. I'd like to add a custom 404 page with human readable error and at the same time email to Admin with entire Error Dump( Would be good if it's nicely formatted in HTML as shows on page)

How can I do this?



via Chebli Mohamed

Email Verification in Laravel 5.1.*

I want to add email verification on my laravel app. Just after submitting the registration form the user will get an email with confirmation link. How can I implement this by using laravel's default auth controller? I have added two fields on my user table (confirmed, confirmation_code). Please someone help me...



via Chebli Mohamed

Laravel 5.1 with Foundation-apps intergration

Id like to use foundation-apps into my laravel 5.1 app .Foundation-apps has being successfully installed into node_modules folder using 'npm' ,how would I intergrate foundation apps into elixir module (gulp.js) file .



via Chebli Mohamed

foundation-apps VS angular material - using laravel

Am developing a laravel based app (5.1) , id like to know which of the 2 frontend frameworks :

  • Foundation-apps
  • Material Angular

have advantage over the other when using laravel as for backend.



via Chebli Mohamed

How to display journal entries filtered by date and associated to baskets / topics in a table view?

Im building a system with laravel to manage an associations interests including a functionality for keeping track of finances. I want to display a complex table-layout an ended up in big trouble with loops and how to structure my code for building the table.

My 'plan':

  • Every account movement is saved as an entry in a journaling-table
  • Every entry is connected to an account and a 'basket' with shall represent its intern financial allocation
  • An Account within a business year has its journal-view, witch displays all movements concerning this account associated with all baskets used in this year. Also I would like to add new movements here.
class Journaling extends Model {
        protected $table = 'journaling';

    public function account()
    {
        return $this->belongsTo('App\Finance\Account');
    }
    public function basket()
    {
        return $this->belongsTo('App\Finance\Basket');
    }
}

 

class Account extends Model {
        public function journaling(){
                return $this->hasMany('App\Finance\Journaling', 'account_id');       
        }
     public function years(){
                return $this->belongsToMany('App\Finance\Year');
        }
}

 

class Year extends Model{
     public function accounts(){
                return $this->belongsToMany('App\Finance\Account', 'accounts_years', 'account_id', 'year_id');
        }
}



class Basket extends Model{
    public function journaling(){
                return $this->hasMany('App\Finance\Journaling', 'basket_id');        
        }

        public function parent()
    {
        return $this->belongsTo('App\Finance\Basket', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('App\Finance\Basket', 'parent_id');
    }
}

Here is a mockup for the final result with annotations:

Some mockup Can somebody give an advice how to get the data in this table structure?



via Chebli Mohamed

laravel Undefined variable: :

i get this error i don't no why the line between section id and books

Undefined variable: section (View: C:\xampp\htdocs\lib\resources\views\books\create_book.blade.php)

the link <a href="{{url('admin_book/createbook',$section->id)}}"class="btn btn-success">New Book</a>

my create_book.blade.php

{!! Form::open(['url'=>'admin_book/store','method'=>'POST','files'=>'true']) !!}
{!! Form::hidden('section_id',$section->id) !!}
<div class="form-group ">
{!! Form::label('Book Title', 'Enter the Title of Book:') !!}
{!! Form::text("book_title",'',['class'=>'form-control']) !!}
</div>
 <div class="form-group ">
{!! Form::label('Book Edition', 'Enter the Edition of Book:') !!}
{!! Form::text("book_edition",'',['class'=>'form-control']) !!}
</div>
 <div class="form-group ">
{!! Form::label('Book Description', 'Enter the Description of Book:') !!}
{!! Form::textarea("book_description",'',['class'=>'form-control']) !!}
 </div>
 <div class="form-group">
{!! Form::label('upload', 'Upload an Image:') !!}
{!! Form::file('image','',['class'=>'form-control']) !!}
 </div>
 <br>
 <div class="form-group">
{!! Form::submit('Create',['class'=>'btn btn-info btn-block']) !!}
 </div>
{!! Form::close() !!}

and my booksControllers

public function create()
    {
        return view('books.create_book');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $book_title = $request ->input('book_title');
        $book_edition = $request ->input('book_edition');
        $book_description = $request ->input('book_description');
        $file = $request ->file('image');
        $destinationPath = 'images';
        $filename = $file ->getClientOriginalName();
        $file ->move($destinationPath,$filename);

        $section_id = $request -> section_id;


        $new_book = new Book;
        $new_book ->book_title = $book_title;
        $new_book ->book_edition = $book_edition;
        $new_book ->book_description = $book_description;
        $new_book ->image_name = $filename;

        $new_book ->section_id = $section_id;

        $new_book ->save();
        return redirect('admin_book/'.$section_id);
    }

and my route

Route::get('admin_book/createbook','BooksController@create');



via Chebli Mohamed

Laravel 5.1, Button open a new blade page

Thanks. Very quick and short. I have only seen how to open a blade page with link, how do I use a button to do the same? Thanks again.



via Chebli Mohamed

`composer install` terminates with "Script php artisan clear-compiled handling the post-install-cmd event returned with an error"

I am trying to install Composer dependencies like this:

root@cityofangels:/var/www/trackstats# composer install
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files
> php artisan clear-compiled



  [ErrorException]                                
  dirname() expects exactly 1 parameter, 2 given  



Script php artisan clear-compiled handling the post-install-cmd event returned with an error



  [RuntimeException]  
  Error Output:       



install [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--no-plugins] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--ignore-platform-reqs] [--] [<packages>]...

Any idea about what is happening, and how I can exactly fix it? I am currently running on Ubuntu 14.04.3 LTS, with the output from php -v being:

PHP 5.5.9-1ubuntu4.14 (cli) (built: Oct 28 2015 01:34:46)

Here is my composer.json, for anyone interested: http://ift.tt/1Ngeu8u

Here is a the directory tree of the folder vendor: http://ift.tt/1jnNbgt

Any help would be appreciated.



via Chebli Mohamed

Laravel 5.1 Gettext gives Call to undefined function App\Models\_() when trying to send email from console command

TL;DR Does anyone know how to inject the Xinax\Gettext dependencies into the Mail-closure?

I have a setup with Laravel 5.1 and the Xinax Gettext package (http://ift.tt/1Ngew03) which works perfectly for translating strings, except for when running an artisan command which attempts to send an email containing a model.

In my model I have a few attribute mutators, for example:

MyModel.php

public function getTranslatedStringAttribute(){
    return _('Translated string');
}

The command calls a repository which sends an email, like this:

public function sendEmailFromRepository(){
    $modelsToInclude = \App\Models\MyModel::get();    

    \Mail::queue('emails.myTemplate', ['theData' => $modelsToInclude], function ($message) {
        $message->from('no-reply@example.org', 'App name');
        $message->to('test@exmaple.org');
        $message->subject('Delivering some stuff to you');
    });
}

Here's the issue, this gives me:

[Symfony\Component\Debug\Exception\FatalErrorException]  
Call to undefined function App\Models\_()

I've figured this is probably because of the \Mail::queue-closure creating a scope which is isolated from the autoloaded helpers, Xinax\Gettext included. Does anyone know how to inject the gettext dependencies into the Mail-closure, or have any other clues on what may be my problem?



via Chebli Mohamed

Laravel 5.1: Show all selected tags when update article

I have a problem to show all selected tags when I try to update some article.

I'm newb in laravel and php so, here is my code:

<select name="tags[]" class="form-control" multiple="multiple">
    @foreach($tags as $key => $value)
        @foreach($news->tags as $tag)
            <option value="{{ $key }}" @if($tag->name == $value) selected @endif>{{ $value }}</option>
        @endforeach
   @endforeach
</select>

But the result is not that I'm actualy expect:

<select name="tags[]" class="form-control" multiple="multiple">
    <option value="1" selected="">1</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="3" selected="">3</option>
</select>

It must be like this:

<select name="tags[]" class="form-control" multiple="multiple">
    <option value="1" selected>1</option>
    <option value="2">2</option>
    <option value="3" selected>3</option>
</select>

How can i do that? Thanks!



via Chebli Mohamed

getstream.io SSL certificate unable to get local issuer certificate

I need some help. I'm integrating getstream.io into my laravel application (v5.1), I'm stuck with this error:

cURL error 60: SSL certificate problem: unable to get local issuer certificate

This is my code:

use GetStream\Stream\Client;

public function index()
{

 $client = new Client('rrzp7mz8htgn', '8cgs94jg2z5da2h4q2an8q6q5vktrp8y8w7rsft3zndf63c8y9n59g2h2qvtdhqq');

 $ericFeed = $client->feed('user', 'eric');

  $data = [
    "actor"=>"eric",
    "verb"=>"like",
    "object"=>"3",
    "tweet"=>"Hello world"
  ];
  $ericFeed->addActivity($data);

}

I followed the instructions below from packalyst

  1. Add the get-stream into your composer:

    "require": { "get-stream/stream-laravel": "~2.1" },

  2. then run composer update

  3. I also added the provider and the aliases

    'providers' => array( 'GetStream\StreamLaravel\StreamLaravelServiceProvider', ... ),

    'aliases' => array( 'FeedManager' => 'GetStream\StreamLaravel\Facades\FeedManager', ... ),

  4. I run:

    php artisan vendor:publish --provider="GetStream\StreamLaravel\StreamLaravelServiceProvider"

  5. I emailed already getstream.io, but no response yet. I'll be updated this post when I received some answers from them.

I also checked this post from laracast, but there's no answer. http://ift.tt/1TaqB7j



via Chebli Mohamed

PDF files getting downloaded instead of showing in fancybox in safari browser

I am working in laravel 5.1. I have a functionality where different file types will be shown in fancy box. It is working fine in all case but incase of safari browser for PDF files, instead of showing the PDF files in fancybox, it is getting downloaded and shown. Anyone knowing the solution, please help to fix this!



via Chebli Mohamed

PHP -> NumberFormatter not working

I have php file test.php:

use App\Classes\test_class;

$xml = new DOMDocument( "1.0", "ISO-8859-15" );
echo 'DOMDocument-ok<br/>';

$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo 'NumberFormatter-ok<br/>';
new test_class();

And test_class.php:

class test_class{

    public function __construct()
    {
        $xml = new \DOMDocument( "1.0", "ISO-8859-15" );
        echo 'DOMDocument-ok<br/>';

        $formatter = new \NumberFormatter('en_US', \NumberFormatter::DECIMAL);
        echo 'NumberFormatter-ok<br/>';
    }

}

When I run this code output is:

DOMDocument-ok
NumberFormatter-ok
DOMDocument-ok
NumberFormatter-ok

But in plugin "sebastian/money" when I use plugin I get this error "Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN) HELP Class 'NumberFormatter' not found"

For code:

<?php
namespace SebastianBergmann\Money;

use NumberFormatter;

class IntlFormatter implements Formatter
{
    private $numberFormatter;
    public function __construct($locale)
    {
        $this->numberFormatter = new NumberFormatter(
            $locale,
            NumberFormatter::CURRENCY
        );
    }

For line :

$this->numberFormatter = new NumberFormatter(
            $locale,
            NumberFormatter::CURRENCY
        );

EDITED:

Apparently NumberFormatter not working inside all Laravel app, but I don't know why, can someone help?



via Chebli Mohamed

Laravel 5.1 multiple images move() issue

I have the following controller code, it should move all the five images to uploads directory but it moves only one image.

Controller:

if(Input::hasFile('profile_pic')){
    $pic = Input::file('profile_pic');
    $mobile->photo1 = $pic[0]->getClientOriginalName();
    $mobile->photo2 = $pic[1]->getClientOriginalName();
    $mobile->photo3 = $pic[2]->getClientOriginalName();
    $mobile->photo4 = $pic[3]->getClientOriginalName();
    $mobile->photo5 = $pic[4]->getClientOriginalName();

     foreach ($pic as $file){
       if(!empty($file)){
         $file->move(public_path() . '/uploads/', time() . '-' . 'laptop');

       }
    }

}

The images name are storing in database table fields successfully. But the not all images are moving to the destination folder only one image moves to the folder, Check foreach loop.



via Chebli Mohamed

upload_max_filesize doesn't change within Laravel 5.1

I'm working on multiple file upload while that time I've got an error

The file "theOne.mp3" exceeds your upload_max_filesize ini directive (limit is 2048 KiB).

So after that I've increased the post_max_size = 20M and upload_max_filesize = 20M and checked it within test.php file it shows

Screenshot

Even though it shows 2M within my Laravel Project and throws the error. What could be the reason behind this.



via Chebli Mohamed

Laravel 5.1 multiple images upload issue

I am uploading multiple images from a single form file input. When i dd() the file field it returns single image.

Controller :

if(Input::hasFile('profile_pic')){
        $demo = $mobile->photo1 =  Input::file('profile_pic');
        dd($demo);
    }

View :

<div class="form-group">
 <label>Image Gallery</label>
 <input type="file" class="form-control" id="profile_pic" name="profile_pic" multiple>
</div>

Output of dd($demo) is :

UploadedFile {#29 ▼
  -test: false
  -originalName: "10422119_755988897809878_5614812569937154817_n.jpg"
  -mimeType: "image/jpeg"
  -size: 50782
  -error: 0
}



via Chebli Mohamed

Returning the custom validation method parameter in error message

I have a created a custom validation function along with a custom error message for it. How can I show the value "1000" in my error message?

  // in my request file
  function rules() 
  {
    return [
        'my_field' => 'myValidator:1000',
    ];    
  }

  // in my custom validator file
  public function validateMyValidator($attribute, $value, $parameters)
  {
      return true;
  }

  // in resources/lang/eng/validation.php
  'custom' => [
    'my_field' => [
        'my_validator' => 'Value must be 1000',
    ],
  ]



via Chebli Mohamed

Get record from database inserted in last two hour [Laravel 5.1]

i want to get all the record from the database inserted in last two hours in Laravel 5.1, i am able to get the record for last 1 hour by using the following code,

$all_bridal_requests_check2 = \DB::table('bridal_requests')
                    ->where(function($query)
                    {
                        $query->where('publisher', '=', 'bq-quotes.sb.com')
                              ->orWhere('publisher', '=', 'bq-wd.com-bsf');
                    })
                    ->where('created_on', '>=', \Carbon\Carbon::now()->subHour())
                    ->orderBy('created_on', 'desc')
                    ->get();

But don't know how to do the same for 2 hours.

Please help me to sort out this issue.
Thanks..



via Chebli Mohamed

Check if url exist laravel

how to check if an url is exists in laravel 5.1? for example i want to check if google is exists..

$url ="www.google.com";
if(exists(url)){
     // do something
}

Thanks before



via Chebli Mohamed

jeudi 26 novembre 2015

Why are there 2 ways to Validate in Laravel 5.1?

You can use Model Validation Rules and FormRequest/Request Validaiton Rules.

So there are Scenarios:

  • Form

  • Rest Create

Should you use a Model Validation regardless? Why are there 2 methods?



via Chebli Mohamed

LARAVEL 5 routing and jquery validation error

I'm getting a routing error with my jquery validation. mostly in my exp. Laravel is not accepting URL with ? in it. I'm not sure if I'm wrong or I'm just doing it wrong.

the URL I'm generating is canvas/users/validate?email=email@email.com

JavaScript

email: {
            required: true,
            email: true,
            remote: {
                    url:  'canvas/users/validate/email',
                    type: "GET"
            }
        },

route.php

Route::get('canvas/users/validate/email?{email}',
                array('uses'=>'Canvas\UserController@validateEmail'));

controller.php

protected function validateEmail($email) {
        $user = User::where('email',$email)->get();
        if ($user->isEmpty()){
            return 'false';
        }else{
            return 'true';
        }
    }



via Chebli Mohamed

convert to nested format php

I just want some help in displaying the correct structure of the image data below. Basically what i want is to display it in nested form. From the data below, I would like it to display like this:

  • Engel (parent which parent_id = 0)
    • Chest Fridge - Freezers
      • Small Engel
      • digital platinum
    • Upright Fridge
      • Built-in fridge
    • Fridge Accessories
      • Blankets
      • Carry handles

enter image description here

I hope anyone can help me. Im using php fyi.



via Chebli Mohamed

Programmatically add exception from CSRF check from Laravel package

The Problem in a Nutshell

I'm looking for a way to remove VerifyCsrfToken from the global middleware pipeline from within a package without the user having to modify App\Http\Middleware\VerifyCsrfToken. Is this possible?

The Use Case

I'm developing a package that would make it easy to securely add push-to-deploy functionality to any Laravel project. I'm starting with Github. Github uses webhooks to notify 3rd party apps about events, such as pushes or releases. In other words, I would register a URL like http://myapp.com/deploy at Github, and Github will send a POST request to that URL with a payload containing details about the event whenever it happens, and I could use that event to trigger a new deployment. Obviously, I don't want to trigger a deployment on the off chance that some random (or perhaps malicious) agent other than the Github service hits that URL. As such, Github has a process for securing your webhooks. This involves registering a secret key with Github that they will use to send a special, securely hashed header along with the request that you can use to verify it.

My approach to making this secure involves:

Random Unique URL/Route and Secret Key

First, I automatically generate two random, unique strings, that are stored in the .env file and used to create a secret key route within my app. In the .env file this looks like:

AUTODEPLOY_SECRET=BHBfCiC0bjIDCAGH2I54JACwKNrC2dqn
AUTODEPLOY_ROUTE=UG2Yu8QzHY6KbxvLNxcRs0HVy9lQnKsx

The config for this package creates two keys, auto-deploy.secret and auto-deploy.route that I can access when registering the route so that it never gets published in any repo:

Route::post(config('auto-deploy.route'),'MyController@index');

I can then go to Github and register my webook like this:

Github webhook registration screen

In this way, both the deployment URL and the key used to authenticate the request will remain secret, and prevent a malicious agent from triggering random deployments on the site.

Global Middleware for Authenticating Webhook Requests

The next part of the approach involves creating a piece of global middleware for the Laravel app that would catch and authenticate the webhook requests. I am able to make sure that my middleware gets executed near the beginning of the queue by using an approach demonstrated in this Laracasts discussion thread. In the ServiceProvider for my package, I can prepend a new global middleware class as follows:

public function boot(Illuminate\Contracts\Http\Kernel $kernel)
{
    // register the middleware
    $kernel->prependMiddleware(Middleware\VerifyWebhookRequest::class);
    // load my route
    include __DIR__.'/routes.php';
}

My Route looks like:

Route::post(
    config('auto-deploy.route'), [
        'as' => 'autodeployroute',
        'uses' => 'MyPackage\AutoDeploy\Controllers\DeployController@index',
    ]
);

And then my middleware would implement a handle() method that looks something like:

public function handle($request, Closure $next)
{
    if ($request->path() === config('auto-deploy.route')) {
        if ($request->secure()) {
            // handle authenticating webhook request
            if (/* webhook request is authentic */) {
                // continue on to controller
                return $next($request);
            } else {
                // abort if not authenticated
                abort(403);
            }
        } else {
            // request NOT submitted via HTTPS
            abort(403);
        }
    }
    // Passthrough if it's not our secret route
    return $next($request);
}

This function works right up until the continue on to controller bit.

The Problem in Detail

Of course the problem here is that since this is a POST request, and there is no session() and no way to get a CSRF token in advance, the global VerifyCsrfToken middleware generates a TokenMismatchException and aborts. I have read through numerous forum threads, and dug through the source code, but I can't find any clean and easy way to disable the VerifyCsrfToken middleware for this one request. I have tried several workarounds, but I don't like them for various reasons.

Workaround Attempt #1: Have user modify VerifyCsrfToken middleware

The documented and supported method for solving this problem is to add the URL to the $except array in the App\Http\Middleware\VerifyCsrfToken class, e.g.

// The URIs that should be excluded from CSRF verification
protected $except = [
    'UG2Yu8QzHY6KbxvLNxcRs0HVy9lQnKsx',
];

The problem with this, obviously, is that when this code gets checked into the repo, it will be visible to anyone who happens to look. To get around this I tried:

protected $except = [
    config('auto-deploy.route'),
];

But PHP didn't like it. I also tried using the route name here:

protected $except = [
    'autodeployroute',
];

But this doesn't work either. It has to be the actual URL. The thing that actually does work is to override the constructor:

protected $except = [];

public function __construct(Illuminate\Contracts\Encryption\Encrypter $encrypter)
{
    parent::__construct($encrypter);
    $this->except[] = config('auto-deploy.route');
}

But this would have to be part of the installation instructions, and would be an unusual install step for a Laravel package. I have a feeling this is the solution I'll end up adopting, as I guess it's not really that difficult to ask users to do this. And it has the upside of at least possibly making them conscious that the package they're about to install circumvents some of Laravel's built in security.

Workaround Attempt #2: catch the TokenMismatchException

The next thing I tried was to see if I could just catch the exception, then ignore it and move on, i.e.:

public function handle($request, Closure $next)
{
    if ($request->secure() && $request->path() === config('auto-deploy.route')) {
        if ($request->secure()) {
            // handle authenticating webhook request
            if (/* webhook request is authentic */) {
                // try to continue on to controller
                try {
                    // this will eventually trigger the CSRF verification
                    $response = $next($request);
                } catch (TokenMismatchException $e) {
                    // but, maybe we can just ignore it and move on...
                    return $response;
                }
            } else {
                // abort if not authenticated
                abort(403);
            }
        } else {
            // request NOT submitted via HTTPS
            abort(403);
        }
    }
    // Passthrough if it's not our secret route
    return $next($request);
}

Yeah, go ahead and laugh at me now. Silly wabbit, that's not how try/catch works! Of course $response is undefined within the catch block. And If I try doing $next($request) in the catch block, it just bangs up against the TokenMismatchException again.

Workaround Attempt #3: Run ALL of my code in the middleware

Of course, I could just forget about using a Controller for the deploy logic and trigger everything from the middleware's handle() method. The request lifecycle would end there, and I would never let the rest of the middleware propagate. I can't help feeling that there's something inelegant about that, and that it departs from the overall design patterns upon which Laravel is built so much that it would end up making maintenance and collaboration difficult moving forward. At least I know it would work.

Workaround Attempt #4: Modify the Pipeline

Philip Brown has an excellent tutorial describing the Pipeline pattern and how it gets implemented in Laravel. Laravel's middleware uses this pattern. I thought maybe, just maybe, there was a way to get access to the Pipeline object that queues up the middleware packages, loop through them, and remove the CSRF one for my route. Best I can tell, there are ways to add new elements to the pipeline, but no way to find out what's in it or to modify it in any way. If you know of a way, please let me know!!!

Workaround Attempt #5: Use the WithoutMiddleware trait

I haven't investigated this one quite as thoroughly, yet, but it appears that this trait was added recently to allow testing routes without having to worry about middleware. It's clearly NOT meant for production, and disabling the middleware would mean that I'd have to come up with a whole new solution for figuring out how to get my package to do its thing. I decided this was not the way to go.

Workaround Attempt #6: Give up. Just use Forge or Envoyer

Why reinvent the wheel? Why not just pay for one or both of these service that already supports push-to-deploy rather than go to the trouble of rolling my own package? Well, for one, I only pay $5/month for my server, so somehow the economics of paying another $5 or $10 per month for one of these services doesn't feel right. I'm a teacher who builds apps to support my teaching. None of them generate revenue, and although I could probably afford it, this kinda thing adds up over time.

Discussion

Okay, so I've spent the better part of two solid days banging my head against this problem, which is what brought me here looking for help. Do you have a solution? If you've read this far, perhaps you'll indulge a couple of closing thoughts.

Thought #1: Bravo to the Laravel guys for taking security seriously!

I'm really impressed with how difficult it is to write a package that circumvents the built-in security mechanisms. I'm not talking about "circumvention" in the I'm-trying-to-do-something-bad way, but in the sense that I'm trying to write a legitimate package that would save me and lots of other people time, but would, in effect, be asking them to "trust me" with the security of their applications by potentially opening them up to malicious deployment triggers. This should be tough to get right, and it is.

Thought #2: Maybe I shouldn't be doing this

Frequently if something is hard or impossible to implement in code, that is by design. Maybe it's Bad Design™ on my part to want to automate the entire installation process for this package. Maybe this is the code telling me, "Don't do that!" What do you think?

In summary, here are two questions:

  1. Do you know a way to do this that I haven't thought of?
  2. Is this bad design? Should I not do it?

Thanks for reading, and thank you for your thoughtful answers.

P.S. Before someone says it, I know this might be a duplicate, but I provided much more detail than the other poster, and he never found a solution, either.



via Chebli Mohamed