samedi 30 janvier 2016

How to set up Browserify with Elixir and Browserify Shim on Laravel 5?

I am trying to set up Browserify with Elixir and Browserify Shim on Laravel 5.2 to use Gulp with my JavaScript files, but I didn't have much luck so far. This should be pretty straightforward to do, but it isn't.

Here is my package.json

{
  "private": true,
  "devDependencies": {
    "gulp": "^3.8.8"
  },
  "dependencies": {
    "bootstrap-sass": "^3.0.0",
    "browserify-shim": "^3.8.12",
    "jquery": "^2.2.0",
    "jquery-ui": "^1.10.5",
    "laravel-elixir": "^4.0.0"
  },
  "browser": {
    "app": "./resources/assets/js/app.js",
    "utils": "./resources/assets/js/utils.js",
  },
  "browserify": {
    "transform": [
      "browserify-shim"
    ]
  },
  "browserify-shim": {
    "app": {
      "depends": [
        "jquery:$",
        "utils:Utils"
      ]
    },
    "utils": {
      "depends": [
        "jquery:$"
      ]
    },
  }
}

gulpfile.js

var elixir = require('laravel-elixir');

elixir(function (mix) {
    mix.browserify('main.js', './public/js/bundle.js');
});

Entry script main.js looks like this:

var $ = require('jquery');
var Utils = require('utils');
var App = require('app');

app.js

var App = {
     init: function(){
         console.log(Utils);
         Utils.doSomething();
     }
    //other methods
};

In short: Utils depends on $, and App depends on both $ and Utils.

When I hit gulp from terminal, bundle.js is correctly created. All scripts are wrapped up in Browserify code (as expected). Each script has all included dependencies, like I configured in package.json so this part looks good as well.

The problem is that all my included dependencies are empty objects. For example, Utils in app.js is empty, and I get an error when I try to call its method "doSomething". Console log prints out an empty object "{}" instead of real object. The only correctly included script is jQuery and it's not an empty object.

What could be wrong here? Do I need to make some changes in my JS files or in configuration to make this work? It looks like I'm pretty close to the solution, but it still does not work and I can't use it at all.



via Chebli Mohamed

vendredi 29 janvier 2016

Laravel Permission Denied

Tonight, I tried to run composer install and all the dependencies installed correctly, and then composer ran php artisan clear compiled and I ran into trouble.

Here's the error it returned:

> php artisan clear-compiled


  [ErrorException]                                                                                                        
  file_put_contents(/srv/something/site/bootstrap/cache/services.php): failed to open stream: No such file or directory  


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>]...

Naturally, I googled it and found everyone on the laracast forums saying to make the directory I was missing, so I did and the command ran again fine. When I went to any page I got thew file_put_contents(/differentNameDependingOnPageButAlwaysRandomLettersAndNumbers.php): failed to open stream: Permission denied

For example here's the traceback for the login page:

ErrorException in Filesystem.php line 81:
file_put_contents(/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php): failed to open stream: Permission denied
in Filesystem.php line 81
at HandleExceptions->handleError('2', 'file_put_contents(/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php): failed to open stream: Permission denied', '/srv/something/site/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php', '81', array('path' => '/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php', 'contents' => '<?php $__env->startSection('title'); ?> Admin Login <?php $__env->stopSection(); ?> <?php $__env->startSection('form'); ?> <form class="form-horizontal" method="POST" action = "login"> <?php echo e($error); ?><?php /*TODO this doesn't show up now, when you do login make it show up*/ ?> <fieldset> <!-- Form Name --> <h1 class="section-heading" style="text-align: center;">Login</h1> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="email">Email</label> <div class="col-md-4"> <input id="email" name="email" type="email" id = "email" placeholder="user@domain.com" class="form-control input-md" required=""> </div> </div> <!-- Password input--> <div class="form-group"> <label class="col-md-4 control-label" for="password">Password</label> <div class="col-md-4"> <input id="password" name="password" type="password" placeholder="********" class="form-control input-md" required=""> </div> </div> <!-- Button --> <div class="form-group"> <label class="col-md-4 control-label" for="Submit"></label> <div class="col-md-4"> <button id="submit" name="submit" class="btn btn-primary">Submit</button> </div> </fieldset> </form> <?php $__env->stopSection(); ?> <?php $__env->startSection('message'); ?> <p class="text-muted" style="text-align:center">Don't have an account yet? Click <a href="../register">here</a> to register.</p> <?php $__env->stopSection(); ?> <?php echo $__env->make('auth.partials.master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>', 'lock' => false))
at file_put_contents('/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php', '<?php $__env->startSection('title'); ?> Admin Login <?php $__env->stopSection(); ?> <?php $__env->startSection('form'); ?> <form class="form-horizontal" method="POST" action = "login"> <?php echo e($error); ?><?php /*TODO this doesn't show up now, when you do login make it show up*/ ?> <fieldset> <!-- Form Name --> <h1 class="section-heading" style="text-align: center;">Login</h1> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="email">Email</label> <div class="col-md-4"> <input id="email" name="email" type="email" id = "email" placeholder="user@domain.com" class="form-control input-md" required=""> </div> </div> <!-- Password input--> <div class="form-group"> <label class="col-md-4 control-label" for="password">Password</label> <div class="col-md-4"> <input id="password" name="password" type="password" placeholder="********" class="form-control input-md" required=""> </div> </div> <!-- Button --> <div class="form-group"> <label class="col-md-4 control-label" for="Submit"></label> <div class="col-md-4"> <button id="submit" name="submit" class="btn btn-primary">Submit</button> </div> </fieldset> </form> <?php $__env->stopSection(); ?> <?php $__env->startSection('message'); ?> <p class="text-muted" style="text-align:center">Don't have an account yet? Click <a href="../register">here</a> to register.</p> <?php $__env->stopSection(); ?> <?php echo $__env->make('auth.partials.master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>', '0') in Filesystem.php line 81
at Filesystem->put('/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php', '<?php $__env->startSection('title'); ?> Admin Login <?php $__env->stopSection(); ?> <?php $__env->startSection('form'); ?> <form class="form-horizontal" method="POST" action = "login"> <?php echo e($error); ?><?php /*TODO this doesn't show up now, when you do login make it show up*/ ?> <fieldset> <!-- Form Name --> <h1 class="section-heading" style="text-align: center;">Login</h1> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="email">Email</label> <div class="col-md-4"> <input id="email" name="email" type="email" id = "email" placeholder="user@domain.com" class="form-control input-md" required=""> </div> </div> <!-- Password input--> <div class="form-group"> <label class="col-md-4 control-label" for="password">Password</label> <div class="col-md-4"> <input id="password" name="password" type="password" placeholder="********" class="form-control input-md" required=""> </div> </div> <!-- Button --> <div class="form-group"> <label class="col-md-4 control-label" for="Submit"></label> <div class="col-md-4"> <button id="submit" name="submit" class="btn btn-primary">Submit</button> </div> </fieldset> </form> <?php $__env->stopSection(); ?> <?php $__env->startSection('message'); ?> <p class="text-muted" style="text-align:center">Don't have an account yet? Click <a href="../register">here</a> to register.</p> <?php $__env->stopSection(); ?> <?php echo $__env->make('auth.partials.master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>') in BladeCompiler.php line 102
at BladeCompiler->compile('/srv/something/site/resources/views/auth/login.blade.php') in CompilerEngine.php line 51
at CompilerEngine->get('/srv/something/site/resources/views/auth/login.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'error' => '')) in View.php line 135
at View->getContents() in View.php line 106
at View->renderContents() in View.php line 80
at View->render() in Response.php line 53
at Response->setContent(object(View)) in Response.php line 197
at Response->__construct(object(View)) in Router.php line 1030
at Router->prepareResponse(object(Request), object(View)) in ControllerDispatcher.php line 95
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96
at ControllerDispatcher->callWithinStack(object(authController), object(Route), object(Request), 'getAdminLogin') in ControllerDispatcher.php line 54
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\authController', 'getAdminLogin') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 703
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 705
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 678
at Router->dispatchToRoute(object(Request)) in Router.php line 654
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54

So far, to try to fix this I've done the following:

  1. Checked permissions, changed everything to 777 and to be owned by www-data
  2. Tried recloning the empty repository with no vendor file, to no avail, same error on composer install
  3. Ran php artisan cache:clear
  4. Ran php artisan clear-compiled
  5. Ran php artisan dump-autoload
  6. Modified site/config/view.php on an irc suggestion, and changed compiled' => realpath(storage_path().'/framework/views') to 'compiled' => storage_path('framework/views'), which yielded a different error: file_put_contents(/srv/something/site/storage/framework/views/8ff8cea6e3bb10ecec87b9d62c64f9768c4c4ab1.php): failed to open stream: No such file or directory (probably because it's not supposed to be there, but who knows this information could be useful.)

All of this to no avail. The weird part is this issue seemingly showed up out of nowhere. Thanks for the help!



via Chebli Mohamed

Laravel Validation Error customise format of the Response

I am working with L5 Form Requests and don't I just love Taylor! Well, I am doing some AJAX requests and I still want to retain my form requests. The problem is that in the case of a validation error the Validator just returns a 422 error response and flashes the errors, but my AJAX frontend expects a very specific format of response from server whether validation is successful or not.

I want to format the response on Validation errors to something like this

return json_encode(['Result'=>'ERROR','Message'=>'//i get the errors..no problem//']);

My problem is how to format the response for the form requests, especially when this is not global but done on specific form requests.

I have googled and yet not seen very helpful info. Tried this method too after digging into the Validator class.

// added this function to my Form Request (after rules())
    public function failedValidation(Validator $validator)
{
    return ['Result'=>'Error'];
}

Still no success.



via Chebli Mohamed

Laravel validation throwing "NotFoundHttpException" when used in PostMan but works in Angular $http request

I am creating an API but stuck debugging.

Using this in my controller method:

$this->validate($request, [
    'project_id' => 'required',
    'content'    => 'required',
]);

If I call that route with PostMan I get a not found error return by Laravel's debugging screen.

However the API call works fine when using an Angular (ionic) $http request.

Any help?



via Chebli Mohamed

Laravel 5 missing required parameters on destroy route

I recently upgraded from laravel 5.1 to 5.2 and now I'm getting an error of Missing required parameters for [Route: example.destroy] [URI: example/{args}].

The error occurs here: <form class="form-horizontal" action="<?php echo route('example.destroy'); ?>" method="post"> on the action attribute of the form.

Route

Route::resource('example', 'ExampleController');

When I was in 5.1, there was no error with this line. Just went I upgrade to 5.2, it now occurs.

The functionality of this is that it will allow user to delete multiple entries by checking the checkboxes that they wish to be deleted. Then upon submit, it will redirect to the destroy method on the controller.



via Chebli Mohamed

Laravel 5 database table relationships

I am starting with learning the database table relationships in Laravel 5. As a cakePHPer something just work a little bit different. My first test is this...

Table containing different sql_types:

class ElementFieldType extends Model {

    protected $fillable = ['name', 'sql_type'];

}

Table containing fields linked to the sql_types in the ElementFieldType Model (element_field_type_id is a foreign key):

class ElementField extends Model {

    protected $fillable = ['api', 'element_field_type_id', 'label', 'type'];

    public function type() {
        return $this->hasOne('App\Models\ElementFieldType');
    }

}

In my controller after finding the ElementField, I want to access the sql_type using:

$field = ElementField::find($id);
echo $field->type->sql_type;

But I get below error, meaning to what I can tell, that there should be an element_field_id key in ElementFieldType, but that cannot be right.

What am I doing wrong?

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'element_field_types.element_field_id' 
in 'where clause' (SQL: select `sql_type` from `element_field_types` 
where `element_field_types`.`element_field_id` = 1 and `element_field_types`.`element_field_id` 
is not null limit 1)



via Chebli Mohamed

Difficulty in executing laravel 5.2 database query

This might be silly question, but since I am new to laravel, I am finding it somewhat difficult to setup database. I am using laravel 5.2. IN config>database.php these are my settings

'default' => env('DB_CONNECTION', 'mysql'),

and for mysql :

'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'larasite'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

Then I also changed .env and .env.example file's settings

DB_HOST=localhost
DB_DATABASE=larasite
DB_USERNAME=root
DB_PASSWORD=""

Now when in routes.php I have this code:

Route::get('about', function(){
  $posting = DB::query('select * from posts');
  dd($posting);
});

And then when I visit localhost:8000/about I get following error.

Builder {#118 ▼
#connection: MySqlConnection {#114 ▶}
#grammar: MySqlGrammar {#115 ▶}
#processor: MySqlProcessor {#116}
#bindings: array:6 [▶]
+aggregate: null
+columns: null
+distinct: false
+from: null
+joins: null
+wheres: null
+groups: null
+havings: null
+orders: null
+limit: null
+offset: null
+unions: null
+unionLimit: null
+unionOffset: null
+unionOrders: null
+lock: null
#backups: []
#bindingBackups: []
#operators: array:26 [▶]
#useWritePdo: false
}

I noticed that, even If I change settings and enter wrong details, I get same error. What's happening? How to solve this?



via Chebli Mohamed