jeudi 30 juin 2016

Error Class 'Laracast\Flash\FlashServiceProvider' not found

I got error message while using Laracast flash package

 Error Output: PHP Fatal error:  Class 'Laracast\Flash\FlashServiceProvider'  
   not found in /var/www/demo/vendor/laravel/framework/src/Illuminate/Foundat  
  ion/ProviderRepository.php on line 146  

If any suggestion please let me know.

Thanks



via Chebli Mohamed

google map api drag and drop pin in laravel

I want to add drag and drop google Api. I've made a map the but I do not know how to make it can be a drag and drop. in there i want make my latitude and longitude is auto fill when i drop the pin

here my view :

 <label for="inputIsiBerita"> Latitude:</label>
         <input type="text" class="form-control" required name="latitude">
         <label for="inputIsiBerita"> Longitude</label>
         <input type="text" class="form-control" required name="longitude">

here my script :

<script>
              function initMap() {
                var map = new google.maps.Map(document.getElementById('map'), {
                  center: {lat: -7.0157404, lng: 110.4171283},
                  zoom: 12
                });
                var input = /** @type {!HTMLInputElement} */(
                    document.getElementById('pac-input'));

                var types = document.getElementById('type-selector');
                map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
                map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);

                var autocomplete = new google.maps.places.Autocomplete(input);
                autocomplete.bindTo('bounds', map);

                var infowindow = new google.maps.InfoWindow();
                var marker = new google.maps.Marker({
                  map: map,
                  anchorPoint: new google.maps.Point(0, -29)
                });

                autocomplete.addListener('place_changed', function() {
                  infowindow.close();
                  marker.setVisible(false);
                  var place = autocomplete.getPlace();
                  if (!place.geometry) {
                    window.alert("Autocomplete's returned place contains no geometry");
                    return;
                  }

                  // If the place has a geometry, then present it on a map.
                  if (place.geometry.viewport) {
                    map.fitBounds(place.geometry.viewport);
                  } else {
                    map.setCenter(place.geometry.location);
                    map.setZoom(17);  // Why 17? Because it looks good.
                  }
                  marker.setIcon(/** @type {google.maps.Icon} */({
                    url: 'http://ift.tt/1rXG5Bt',
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(35, 35)
                  }));
                  marker.setPosition(place.geometry.location);
                  marker.setVisible(true);

                  var address = '';
                  if (place.address_components) {
                    address = [
                      (place.address_components[0] && place.address_components[0].short_name || ''),
                      (place.address_components[1] && place.address_components[1].short_name || ''),
                      (place.address_components[2] && place.address_components[2].short_name || '')
                    ].join(' ');
                  }

                  var latitude = place.geometry.location.lat();
                  var longitude = place.geometry.location.lng(); 

                  $("input[name=coordinate]").val(address);
                  $("input[name=latitude]").val(latitude);
                  $("input[name=longitude]").val(longitude);

                  infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
                  infowindow.open(map, marker);
                });

                // Sets a listener on a radio button to change the filter type on Places
                // Autocomplete.
                function setupClickListener(id, types) {
                  var radioButton = document.getElementById(id);
                  radioButton.addEventListener('click', function() {
                    autocomplete.setTypes(types);
                  });
                }

                setupClickListener('changetype-all', []);
                setupClickListener('changetype-address', ['address']);
                setupClickListener('changetype-establishment', ['establishment']);
                setupClickListener('changetype-geocode', ['geocode']);
              }
            </script>               
            <script src="http://ift.tt/299ixVJ"
        async defer></script>

and when i drag the pin its will auto change the point latitude and longitude



via Chebli Mohamed

Calling eloquent relation multiple times doesn't return data

I'm having this strange behavior in Laravel 5.1 where when I call the relation of an eloquent model more than once within the same code execution, then the second time it doesn't have the data.

class Items extends Eloquent {
    public $table = 'items'

    public function subItems() {
        return $this->hasMany(Item::class, 'items_id');
    }
}

class Item extends Eloquent {
    public $table = 'items_item'
    public $fillable = ['items_id'];
}


$items = Items::create();
Item::create([
    'items_id' => $items->id,
]);
Item::create([
    'items_id' => $items->id,
]);


// works
$first = $items->subItems;
// no data
$second = $items->subItems;
// works
$third = $items->subItems()->get();

Is this normal behavior? Do i have to somehow reset something before calling the relation again?



via Chebli Mohamed

Laravel 5.2 - Eloquent Many to Many Relationship

I have 2 models and 3 migrations, Models are

1-Media:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Media extends Model
{
  public function gallery(){
        return $this->hasMany('App\Gallery', 'media_gallery');
    }
}

2-Gallery:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Gallery extends Model
{
  public function media(){
        return $this->belongsToMany('App\Media', 'media_gallery');
    }
}

and Migrations are

1- for media table the schema is:

Schema::create('media', function (Blueprint $table) {
   $table->increments('id');
   $table->timestamps();
});

2- for gallery table the schema is:

Schema::create('galleries', function (Blueprint $table) {
   $table->increments('id');
   $table->timestamps();
   $table->string('path');
   $table->string('type');
});

3- a third joining table for media_gallery many to many relationship:

Schema::create('media_gallery', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
    $table->integer('media_id');
    $table->integer('gallery_id');
});

Concept: I have Dropzone installed and working so than I can upload items to the Gallery table, but what I want to do is that I make a Media item so that it holds one or more Gallery items, and a gallery item can be related to many media item

What I've tried: I made a form that holds each gallery item with a check box holds the id of the item, this is how I handle it in my controller...

public function MediaPostUpload(Request $request){

        $media = new Media();
        $media->save();

        //fetching ids of checked boxes
        $galleryItems = $request['galleryItems'];
        $ids = array();
        if(!empty($galleryItems)){
            foreach($galleryItems as $itemId){
                $ids[] = $itemId;
            }
        }
        $media->gallery()->attach($ids);
}

Error shows up:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'galleries.media_gallery' in 'where clause' (SQL: select * from galleries where galleries.media_gallery = 1 and galleries.media_gallery is not null)



via Chebli Mohamed

Empty Object being passed to route

I am trying to work out why an empty object is being passed through my route. I have a user model

class User extends Model
{
    protected $table = 'users';
    protected $guarded = [];

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

And I have a UserObjectives model

class UserObjectives extends Model
{
    protected $table = 'user_objectives';
    protected $guarded = [];

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

I then have an index controller which displays the default page. The index function gets the logged in User and passes it to the view

public function index()
{
    $loggedInUser = Auth::user()->getFirstName() . ' '  . Auth::user()->getLastName();
    $user = User::where('userName', '=', $loggedInUser)->first();

    if($user) {
        return view('index', compact('user'));
    } else {
        return view('auth.login');
    }
}

I am doing it like the above because I am mapping users from Active Directory. Within my index view, if I do the following I can see the details for the logged in user.



Within the index view, I have a link to a route which I pass the user object

{!! link_to_route('users.userObjectives.index', 'My Info', array($user), array('class' => 'btn btn-info')) !!}

Now within the UserObjectives Controller I have

public function index(User $user)
{
    dd($user);
}

Now for some reason the above displays an empty User Object. If I change it to the following, without User, I get the id of the logged in user.

public function index($user)
{
    dd($user);
}

Why would this function display an empty User Object even though I can see within the view that the User object I am passing does have data?

Thanks



via Chebli Mohamed

Cannot login with custom authentication connecting to another api

We are working on two laravel projects one for front end laravel and for backend api. I followed tutorials on connecting this two projects but make use of guzzlehttp. However I am getting undefined index password. I already dd the user['data'] in getUsers method and gettign the correct password. Can any one help me on this.

ApiUserProvider

<?php

namespace App\Auth;

use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Http\Request;

use GuzzleHttp\Client;

class ApiUserProvider implements UserProvider
{

    public function retrieveByCredentials(array $credentials)
    {
        $user = $this->getUserByUsername($credentials['username']);

        return $this->getApiUser($user);
    }

    public function retrieveById($identifier)
    {
        $user = $this->getUserById($identifier);

        return $this->getApiUser($user);
    }

    public function validateCredentials(UserContract $user, array $credentials)
    {
        return $user->getAuthPassword() == bcrypt($credentials['password']);
    }

    protected function getApiUser($user)
    {
        if ($user !== null) {
            return new ApiUser($user);
        }
    }

    protected function getUsers()
    {
        $client = new Client(['base_uri' => 'http://ift.tt/294zhj7']);

        $response1 = $client->request('POST', 'oauth/access_token', [
            'form_params' => [
                'client_id' => 'id1',
                'client_secret' => 'secret1',
                'grant_type' => 'password',
                'username' => 'email@yahoo',
                'password' => 'password'
            ]
        ]);


        $location = json_decode($response1->getBody(), true);

        $token = $location['access_token'];

        // Send a request to http://ift.tt/295jtJe
        $response2 = $client->request('GET', 'users/self', [
            'headers' => [
                'Authorization' => 'Bearer '. $token
            ]
        ]);

        $user = json_decode($response2->getBody(), true);
        return $user['data'];
    }

    protected function getUserById($id)
    {
        $user = [];

        if($this->getUsers()['email'] == $id){
            $user['id'] = $id;
        }

        dd($user);
        return $user ?: null;
    }

    protected function getUserByUsername($username)
    {
         $user = [];


        if($this->getUsers()['email']  == $username){
            $user['email'] = $username; 
        }

        return $user ?: null;
    }

    // The methods below need to be defined because of the Authenticatable contract
    // but need no implementation for 'Auth::attempt' to work and can be implemented
    // if you need their functionality
    public function retrieveByToken($identifier, $token) { }
    public function updateRememberToken(UserContract $user, $token) { }

}

ApiUser

namespace App\Auth;

use Illuminate\Auth\GenericUser;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class ApiUser extends GenericUser implements UserContract
{


    public function getAuthIdentifier()
    {
        return $this->attributes['id'];
    }
}

UserController

public function login(Request $request)
{
    $email = $request->email;
    $password = bcrypt($request->password);

    if (Auth::attempt(['username' => $email, 'password' => $password])) {
        return "hello";
    } 
}



via Chebli Mohamed

mercredi 29 juin 2016

How to get the total number of updated fields in laravel 5.1?

I need to save the number of fields updated after an update operation is performed on a model and its related models.

Suppose I have a user profile edit form. On that form I allow the user to update its firtname, lastname, password.

The User model has email and password fields and few other fields as well.

The UserProfile model has firstname, last name and other fields as well.

The User model is associated with UserProfiles model with hasOne association.

There are some ManyToMany and hasMany associations as well.

If the user updates firstname and password I need to show user the "number of fields changed : 2".

Is there any Laravel 5 way or package to do so.

Thanks.



via Chebli Mohamed

Generic PHP method to compare two nested multidimensional arrays and return the fields whose values are changed or a new field is added

I am having two multidimensional arrays.

NOTE: I am using Laravel 5.1

I am working on developing a generic method, which can compare the two arrays passed to it and return the array elements whose value has changed or a new array element has been added or removed from it.

Suppose I have following two multi dimensional arrays:

Original array:

Array
(
    [id] => 1
    [age] => 27
    [height] => null
    [date_of_joining] => 2012-01-01 00:00:00

    [profile] => Array
    (
        [firstname] => Neelkanth
        [lastname] => Kaushik
    )

    [contact_details] => Array
    (
        ['address'] => Array
        (
            [present_address] => Street-1, XYZ/90
            [permanent_address] => Street-1, XYZ/90
        )
        ['phone'] => Array
        (
            ['office'] => 12344566
            ['home] => 567898765
        )
    )

    [friends] => Array() //Empty array
)

Modified array:

Array
(
    [id] => 1
    [age] => 25 //Changed
    [height] => 150 //changed
    [date_of_joining] => 2016-01-01 00:00:00 //Changed
    [weight] => 120 //New element

    [profile] => Array
    (
        [firstname] => Neelkanth
        //lastname removed
    )

    [contact_details] => Array
    (
        ['address'] => Array
        (
            [present_address] => Street-2, XYZ/90 //Changed
            [permanent_address] => Street-1, XYZ/90
        )
        ['phone'] => Array
        (
            ['office'] => 12344566
            //home removed
        )
    )
    [friends] => Array  //Changed
    (
        [0] => Array //New added
        (
            'friend_id' => 'f1'
        )
        [1] => Array //new added
        (
            'friend_id' => 'f2'
        )
    ) 
)

Final array would be like this:

Array
(
[0] => 'age'
[1] => 'date_of_joining',
[2] => 'weight'
[3] => 'lastname'
[4] => 'present_address',
[5] => 'home',
[6] => 'f1',
[7] => 'f2'
[8] => 'height'
)

I am working on the solution from past few days but can't get my head around this. I am able to make comparison on the outer array using simple loops but having a hard time doing same on the multilevel nested arrays.

Does any one having any idea or a working solution for this.

Please help.

Thanks.



via Chebli Mohamed

location.href in double quote : Laravel 5.2

My code for select is below

<select id="ddlLanguages" class="form-control">
    @foreach($Languages as $Language) 
        <option onchange="location.href = {!! URL('Tr/' . '/' . $Language->LID) !!}" 
              value="{!! $Language->LanguageID !!}">{!! $Language->Language !!}</option>
    @endforeach
</select>

This produces below html

<select id="ddlLanguages" class="form-control">
    <option onchange="location.href = http://localhost/Learning/public/Translation/1" 
                    value="1">English</option>
    <option onchange="location.href = http://localhost/Learning/public/Translation/2" 
                    value="2">French</option>
</select>

Problem is this part "location.href = http://localhost/Learning/public/Translation/1" I am missing some formatting in the URL.

Can you guide me the correct path?



via Chebli Mohamed

How to call controller method from view laravel?

$varbl = App::make("ControllerName")->FunctionName($params); to call a controller function from a my balde template(view page). Now i'm using Laravel 5.1 to do a new project and i tried this method to call a controller function from my blade template .But its not working and showing some errors. Is there any method to call a controller function from a view page in Laravel 5.1?



via Chebli Mohamed

How to get header values in laravel testing

This is how i get response in test Case

$response = $this->call('POST','/api/auth/login',['username'=>'xx','password'=>'xxx'], [/* cookies */], [/* files */], ['HTTP_ClientSecret' => 'xxxx']);

Then we can get response content by like this

$response->getContents()

i want to know how to get response header data ?



via Chebli Mohamed

Submit form using VueJs and AJAX in Laravel 5.1

I am trying to submit a form using AJAX and VueJs. But somehow I am failing to achieve that. I always end up getting an empty Illuminate\Http\Request object.

The blade file:

<body>
    <div class="container">
        <generate-admin></generate-admin>
    </div>

    <script src="https:http://ift.tt/IJSC3o"></script>
    <script src=""></script>
</body>

The component:

<template>
    <form id="createAdministrator" @submit.prevent="createAdministrator">

        <div class="form-group">

           <input type="text"
                  name="username"
                  id="txtUserName"
                  placeholder="Username"
                  autocomplete="off"
                  v-model="username"
           />

        </div>

        <input type="submit" value="Submit">

    </form>
</template>

<script>
    export default {
        data: function() {
            return {
                username: ''
            }
        },

        methods: {
            createAdministrator: function() {
                formContents = jQuery("#createAdministrator").serialize();

                this.$http.post('/admin', formContents).then(function(response, status, request) {
                    console.log(response);
                }, function() {
                    console.log('failed');
                });
            }
        }
    }
</script>

main.js

import Vue from 'vue';
import GenerateAdmin from './components/GenerateAdmin.vue';

var VueResource = require('vue-resource')
Vue.use(VueResource);

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
Vue.http.options.emulateJSON = true;

new Vue({
    el: 'body',

    components: { GenerateAdmin }
});

gulpfile.js

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

require('laravel-elixir-vueify');

elixir(function(mix) {
    mix.browserify('main.js');
});

routes.php

Route::get('/admin/create', function () {
    return view('admin.create');
});

Route::post('/admin', function(Request $request) {
    // returns an empty object.
    return response(['results' => $request]);
});

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

What I get in return is:

"{"results":{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}}"

When I check the Request Payload section of Network Tab in Chrome.. I do see that the form is getting submitted successfully with whatever data I write in the text box above.

Why is this happening ? Kindly guide me where I have made the mistake ?

P.S.: I have started learning VueJs Components recently.



via Chebli Mohamed

mardi 28 juin 2016

Issue with updating one to one model in Laravel 5.2

User Table:

 id
 name
 email
 etc.

Profile Table:

 user_id
 role
 address
 city
 state
 etc.

On tinker i do:

 $user = $this->$user->with('Profile')->find(3);

Output is:

 App\User {#756
 id: 3,
 name: "Alejandra Kerluke Jr.",
 email: "balistreri.laurel@example.com",
 deleted_at: null,
 created_at: "2016-06-23 05:12:03",
 updated_at: "2016-06-29 11:05:45",
 Profile: App\Profile {#768
   user_id: 3,
   role: "",
   address: """
     50111 Wendy Row Apt. 732\n
     Kingburgh, OR 42164-7189
     """,
   city: "Manteland",
   state: "Vermont",
   country: "Belgium",
   phone: "1-226-766-4182 x5574",
   fax: "1-507-985-3523 x708",
   zip: 48446,
   status: 0,
   deleted_at: null,
   created_at: "2016-06-23 05:12:03",
   updated_at: "2016-06-23 05:12:03",
 },

}

Now i did:

>>> $user->name="YYYYYY"
>>> $user->email='abc@example.com'
>>> $user->profile->role = 'XXXXX'
>>> $user->push();

This throws the error:

Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update `profiles` set `role` = inspector, `update

d_at= 2016-06-29 11:29:30 whereid` is null)'

I don't know what's wrong with this peace of code. I am new to Laravel and any kind of help will be appreciated.



via Chebli Mohamed

Laravel 5 "The page isn't redirecting properly" What is the reason for this route?

I got "The page isn't redirecting properly" problem when I use Route::controller('/', 'DashboardController'); In routs.php file. If I using Route::get('/', 'DashboardController@getIndex'); I don't have this problem.In my AuthController.php I use protected $redirectTo = '/'; for redirect. My Question is why I got this error?

routs.php

enter image description here

Route::group(['middleware' => 'auth'], function () {
Route::group(['prefix' => 'products'], function () {
        Route::controller('category', 'Products\ProductsCategoryController');
        Route::controller('manufacturer', 'Products\ProductsManufacturerController');
        Route::controller('/', 'Products\ProductsController');
    });

    Route::group(['prefix' => 'customer'], function () {
        Route::controller('category', 'Customer\CustomerCategoryController');
        Route::controller('/', 'Customer\CustomerController');
    });

    Route::group(['prefix' => 'reports'], function () {
        Route::controller('/', 'Reports\ReportsController');
    });

    Route::controller('/', 'DashboardController');
});

Route::auth();

Route::get('/home', 'HomeController@index');



via Chebli Mohamed

Laravel: Admins can see/edit/delete everything, but Authors can only their own

My app has two roles: admin & author (by the way, there are tables: roles, permissions, permission_role, role_user, there are Eloquent models Role.php, Permission.php... in model User.php there is a method called hasRole that checks whether the user has some role... and finally, in AuthServiceProvider.php there is:

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    foreach ($this->getPermissions() as $permission) {
        $gate->define($permission->name, function($user) use ($permission) {
            return $user->hasRole($permission->roles); 
        });
    }
}

protected function getPermissions()
{
    return Permission::with('roles')->get();
}

Anyway, I've created two roles: admin & author.

  • Admins should be able to see/edit/delete all articles. Also, admins should be able to create and edit/delete all registered users.
  • Author should be able to see/edit/delete only his own articles. Also, author should be able to edit only his own profile.

I'm not sure which is the best way to create this. Would it be a good idea to create the following permissions:

  • manage_users
  • edit_profile
  • manage_articles
  • edit_published_articles
  • delete_published_articles

and then admin role would have all of these permissions, while author would have only: edit_profile, edit_published_articles, delete_published_articles...

Then, in UsersController.php in each method I would check the permissions:

public function index()
{
    if (Auth::user()->can('edit_profile')) {
        if (Auth::user()->can('manage_users')) {
            $users = User::with('roles')->get();
            return view('backend.users.index', compact('users'));
        }
        $users = collect([Auth::user()]);
        return view('backend.users.index', compact('users'));
    }
    return redirect('backend');
}

public function create(User $user)
{
    if (Auth::user()->can('manage_users')) {
        $roles = Role::lists('label', 'name');
        return view('backend.users.form', compact('user', 'roles'));
    }
    return redirect('backend');
}

public function store(Requests\StoreUserRequest $request)
{
    if (Auth::user()->can('manage_users')) {
        $user = new User($request->only('name', 'email', 'password'));
        $user->save();

        $roleName = $request->input('role');
        $user->assignRole($roleName);

        session()->flash('status', 'User has been created.');
        return redirect(route('backend.users.index'));
    }
    return redirect('backend');
}

public function edit($id)
{
    if (Auth::user()->can('edit_profile')) {

        if (Auth::user()->can('manage_users')) { 
            $user = User::findOrFail($id);
            $roles = Role::lists('label', 'name');
            foreach ($user->roles as $role) {
                $roleName = $role->name;
            }
            return view('backend.users.form', compact('user', 'roles', 'roleName'));
        }

        $user = User::findOrFail($id);
        if ($user->id == Auth::user()->id) {  
            $roles = Role::lists('label', 'name');
            foreach ($user->roles as $role) {
                $roleName = $role->name;
            }
            return view('backend.users.form', compact('user', 'roles', 'roleName'));
        }
    }
    return redirect('backend');
}
// ... and so on...

BUT, I'm quite sure that this is not the best way. Maybe I do not need to have the permissions at all - instead of checking permissions in controller methods it would be better to ask whether the user has a specific role (if (Auth::user()->hasRole('admin'))), for example instead of:

public function index()
{
    if (Auth::user()->can('edit_profile')) {
        if (Auth::user()->can('manage_users')) {
            $users = User::with('roles')->get();
            return view('backend.users.index', compact('users'));
        }
        $users = collect([Auth::user()]);
        return view('backend.users.index', compact('users'));
    }
    return redirect('backend');
}

we would say:

public function index()
{
    if (Auth::user()->hasRole('admin')) {
            $users = User::with('roles')->get();
            return view('backend.users.index', compact('users'));
        }
        $users = collect([Auth::user()]);
        return view('backend.users.index', compact('users'));
}

... or maybe this isn't the good way too? How would you do? Is it enough just to check in controller methods, or maybe there should be some Middleware involved?


Since this is a long post, to summarize:

I've created two roles: admin & author and:

  • Admins should be able to see/edit/delete all articles. Also, admins should be able to create and edit/delete all registered users.
  • Author should be able to see/edit/delete only his own articles. Also, author should be able to edit only his own profile.

How would you do this?



via Chebli Mohamed

Laravel 5 Queue jobs are taking 400ms to run

I have implemented a Laravel 5.0 Queue (with a DB driver) in order to speed up the redirection speed on my website.

I wanted to speed up a process that takes about 400 ms.

However after implementing this Queue, it's still taking like 350-400ms.

Queue::push(function($job) use ($data)
{
    TestQueue::myFunc($data);

    $job->delete();
});

Am I doing anything wrong? Please let me know what else to provide in order for you to help me.



via Chebli Mohamed

PHP - Illegal offset type, after is_array and is_object

I have this method:

public function setVariable($variable, $value = null)
{
    $variables = json_decode($this->variables);

    if(is_array($variable) || is_object($variable))
        foreach($variable as $key => $value)
            if(in_array($key, $this->variableNames))
                $variables[$key] = $value;
    else
        $variables[$variable] = $value;

    $this->variables = json_encode($variables);
    $this->save();
}

But, if I call the method like this:

setVariable(['test' => 'test', 'bla' => 'bla'])

It return this error:

ErrorException in User.php line 60:
Illegal offset type

Line 60 is this line:

$variables[$variable] = $value;

But, why it return the error? I check if $variable is array or object, But it continues return this error. Why?



via Chebli Mohamed

Object not being passed to controller

I am struggling with something I am pretty sure I am doing incorrectly. I have a Departments model which has the following route

Route::resource('departments', 'DepartmentsController', ['except' => ['show', 'edit', 'create', 'delete', 'update', 'destroy']]);

It uses active directory to update the database, no user input is involved. I have now come to the point where a department can have many objectives. So I have created a DepartmentObjectives model and set the relationships. I then done the following in my routes file

Route::model('departmentObjectives', 'DepartmentObjectives');
Route::bind('departmentObjectives', function($value, $route) {
    return App\DepartmentObjectives::whereId($value)->first();
});
Route::resource('departmentObjectives', 'DepartmentObjectivesController', ['except' => ['show', 'store', 'delete', 'destroy']]);

Now on the index file for departments, I have the following

@foreach($departments as $department)
    <tr>
        <td>  </td>
        <td>  </td>
        <td>{!! link_to_route('departmentObjectives.create', 'Get Objectives', array($department->id), array('class' => 'btn btn-info')) !!}</td>
    </tr>
@endforeach

But within the DepartmentObjectives Controller, if I do the following it outputs an empty Department object

public function create(Department $department)
{
    dd($department);
    return view('departments.objectives', compact('department'));
}

What is the best way to link the department objective to the department?

Thanks



via Chebli Mohamed

Root directory of laravel project in Cloud9

now it's showing home page http://ift.tt/28ZPqC2

it's my site but i could not make root or homepage in softenum-softenum.c9users.io.

Every time I was trying to change DocumentRoot /home/ubuntu/workspace/ to DocumentRoot /home/ubuntu/workspace/public

But I was not saved by F2 pressing.

Please help me.



via Chebli Mohamed

Sending multiple request to server

My code is hosted on amazon web service server and I m using Hathway Internet Service Provider (India based ISP). Previously my code was working perfectly with Hathway ISP but from few days back my code is not working as expected. I tried to execute same code from another user of Hathway ISP there also I faced same issue. I thought there was something wrong with my code, after debugging I found everything was perfect, this I came to know when I executed my code with some other ISP. What is happening with Hathway ISP is, it's sending multiple request to server. Browser sending only one request to the server this I checked in browser Network tab but doesn't know what happening in the middle that server getting multiple request. Let me give some overview of my code,

  1. It is written in php
  2. Excel file is being downloaded
  3. Code has huge calculation so it takes 10 to 15 min for excel file to get downloaded

Thanks



via Chebli Mohamed

lundi 27 juin 2016

How to run "composer update" on test/production server?

I'm developing an application in laravel, I have completed it on localhost, but when I run it on test server it shows me error

Class 'Collective\Html\HtmlServiceProvider' not found

I think it need to update composer. But how do I do it on test server..!

Please help me I'm new to laravel and web hosting. Thank you.



via Chebli Mohamed

Passing query builder instances into function call with eloquent queries

An Employee has many employeeAreas, wanting to return any Employees who have at least one employeeArea that is within 12km of any of points in the $latLngCol collection.

Getting SQL syntax errors and I am not sure how to use the $ea query builder instance to project the latitude and longitude properties of employeeArea objects into the function call.

public static function findClosest($latLngCol) {

    $employees = Employee::where('employeeareas',function($query) use($latLngCol) {

        $query->where(function($ea) use($latLngCol)  { 

            $latLngCol->first(function($key, $val) use($ea) {


                 $m = DistanceCalculator::LatLngToLatLng($val['lat'],$val['lng'],$ea->select('latitude')->first(), $ea->select('longitude')->first());

                if($m <= 12000) return true;


        });  

        }

       )->first();
    }); 


    return $employees;


}



via Chebli Mohamed

Language implementation in Database: Laravel 5.2

What Am I doing?

I was using lang folder to maintain the translation for two languages. Now, as per the requirement, admin can also do the Language Key values changes. So, now I have moved it to database.

ok, Now my array is like below.

Collection {#191 ▼
  #items: array:6 [▼
    0 => TranslationModel {#192 ▼
      +table: "tbltranslation"
      +primaryKey: "TranslationID"
      +timestamps: true
      #connection: null
      #perPage: 15
      +incrementing: true
      #attributes: array:7 [▼
        "TranslationID" => 1
        "PageID" => 1
        "LanguageID" => 1
        "KeyID" => 1
        "Val" => "All Roles"
        "created_at" => "2016-06-27 21:37:06"
        "updated_at" => "2016-06-27 21:37:06"
      ]
      #original: array:7 [▶]
      #relations: []
      #guarded: array:1 [▶]
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
    1 => TranslationModel {#193 ▶}
    2 => TranslationModel {#194 ▶}
    3 => TranslationModel {#195 ▶}
    4 => TranslationModel {#196 ▶}
    5 => TranslationModel {#197 ▶}
  ]
}

There are 6 places in the blade where I have to show Translation from above array. I am thinking to write below code at each place inside blade.

Below is for first place.

$Translation_Dictionary->where('KeyID', 1)->first()

Am I doing it correctly?



via Chebli Mohamed

Unable to send emails in laravel 5 app

Hello I have a laravel 5 app which is working perfectly in local environment. But in production emails are not getting sent instead I get the exception below:

1/1 FatalErrorException in AstAnalyzer.php line 125:
    Cannot instantiate interface PhpParser\Parser

Path to file: /vendor/jeremeamia/SuperClosure/src/Analyzer/AstAnalyzer.php line 125

I don't get it because right now I am testing same function in local and is working. Every other path of the app is working except this one.



via Chebli Mohamed

Pass in function which returns true or false into eloquent query context on a related property

There's an Employee model and many coveredArea models that belong to Employee.

Employee

int id
string name

CoveredArea

int id
int employee_id
decimal lat
decimal lng

I need to check if any of the coveredArea belonging to Employees are within 12km of latitude and longitude points contained in a collection of arrays called JobLocations and return these Employees.

public static function findClosest($jobLocations) {


    Employee::where('coveredareas',function($query) {

        $query->where(function($ca) { 

            $jobLocations->first(function($key, $val) {


                $m = DistanceCalculator::LatLngToLatLng($val['lat'],$val['lng'],$ca->lat, $ca->lng);
                  if($m <= 12000) return true;



        });  

        }

       )->first();
    }); 


}

I am unsure how to properly pass the LatLngToLatLng() function and lat and lng variables on the coveredAreas object that I presume should be on the $ca variable.



via Chebli Mohamed

EC2 Database through Larval Forge has stopped being accessable

I've been running an instance EC2 through Laravel forge for about 2000 hours and this morning got this error while trying to reach it:

SQLSTATE[08006] [7] could not connect to server: Connection refused Is the server running on host "172...***" and accepting TCP/IP connections on port 5432?

After SSHing into the server I've getting a similar error when trying to run a command. I've dug through AWS but don't see any errors being throw. I double checked the ip address for the instance to make sure the IP hadn't changed for any reason. Of course I'm a little behind on my backups for the application so I'm hoping someone might have some ideas why else I can do to try and access this data. I haven't made any changes to the app in about 10 days, but found the error while I was pushing an update. I have six other instances of the same app that weren't affected (thankfully) but makes me even more confused with the cause of the issue.



via Chebli Mohamed

Using ElasticSearch on Host

i'm newbie in elasticsearch. i have a stupid question!!

i'm using Elasticsearch in laravel 5.2, and i want to upload my site on a cpanel hosting...

how i can use the elasticsearch in cpanel?

i can work with elasticsearch in localhost but i want to know if i upload my site to a cpanel host, how i can use elastic search?

Any information you can provide me would be greatly appreciated



via Chebli Mohamed

Query data based on pivot table

I have a database design which essentially takes the following form (I have removed a lot of fields as they are not really needed for demonstration purposes). I have a users table

users
+----+---------------+-----------------+
| id | name          | email           | 
+----+---------------+-----------------+
| 1  | ProjectA      | Something       |    
+----+---------------+-----------------+

A user can have many projects

projects
+----+---------------+-----------------+-----------------+
| id | name          | description     | user_id         |
+----+---------------+-----------------+-----------------+
| 1  | ProjectA      | Something       | 1               | 
+----+---------------+-----------------+-----------------+

So that is straight forward enough and very easy to query. If I want all projects for the logged in user I can do

$loggedInUser = Auth::user()->getFirstName() . ' '  . Auth::user()->getLastName();
$loggedInUserId = User::where('userName', '=', $loggedInUser)->first();

$projectss = Project::all()->where('user_id', $loggedInUserId);

This is where things get a little more tricky. I have a pivot table for a users groups. It is essentially this

users_user_groups
+----+---------------+-----------------+
| id | user_id       | group_id        | 
+----+---------------+-----------------+
| 1  | 1             | 2               |    
+----+---------------+-----------------+

I then have a user_groups table

user_groups
+----+---------------+
| id | group_name    |             
+----+---------------+
| 1  | Group A       | 
+----+---------------+

If I want to find what groups a user is a part of I can do

$userGroups = Auth::user()->getGroups();

My question is this. Above, I demonstrate how I can get all projects for a user. Now I know there is a user_group called Group A. What I essentially want to do is get all projects where the user is apart of Group A. So if 5 users create a project and they are all in Group A, then I should be returned 5 projects.

How would I go about doing something like this?

Thanks



via Chebli Mohamed

HTTPS works only in index page

We have enable https our website after migrating from different domain. But somehow https works only for the index page, when we go to an another page it will shows request URL not found in this server ERROR. and also http is also not working in inner pages.

What could be the the reason and how can we solve this?



via Chebli Mohamed

dimanche 26 juin 2016

How to retrieve html from view object without rendering to the browse

I have 2 separate partials views, I want to get the html with the given data from those partials views and has to send a json resonse from controller

// here is the sudo code

public function myControllerFunction(){

 $response['products'] = view('search._partials.product_box')->with('data', $data['products]);
 $response['filters'] = view('search._partials.facet_filters')->with('data', $data['filters]);
return $response;

}

I want to achieve some thing like this, It is possible with plain php code but with this framework is there any way to achieve this



via Chebli Mohamed

How to put storage file download excel for laravel 5.1

I want to put location storage in my apps, when download file in the folder privacy me. Any idea?

public function getExport(){
                $user = Members::all();
                Excel::create('Export Data',function($excel) use($user){
                        $excel->sheet('Sheet 1',function($sheet) use($user){
                                $sheet->fromArray($user);
                        });
                })->export('xlsx');
        }


via Chebli Mohamed

Issue when trying to show exception: Laravel 5.2.37

I have below code

try {
    $Role = $this->Get($obj->RoleID);
    if($Role == null) {
        return trans('Role.RoleNotFound');
    }
    $Role->Role = $obj->Role;
    $Role->save();
} catch (Exception $ex) {
    dd($ex);
    return $ex;
}

I am passing below data to this function

{#157 ▼
  +"Role": "wsedde"
  +"RoleID": "31"
}

What's the problem?

As per the schema Role column has length = 2 and I by mistake passed length greater then 2. I have try catch applied but exception is not showing.

Can you tell why it does not go inside catch block?



via Chebli Mohamed

Trying to send multiple Key value inside with function for a Route: Laravel 5.2

I am using the below function to send the key value to show a message based on database operation.

return redirect()->route("Roles")->with("UpdateRole", "updated");

Now, I am looking to send a status code key also but as per the doc for with function, we can send one key and it's corresponding value.

Is there any way to send multiple Keys and their corresponding values?



via Chebli Mohamed

No alive nodes found in your cluster - ElasticSearch

i'm using this package on laravel 5.1

but i see this error alltimes:

NoNodesAvailableException in

C:\xampp...\vendor\elasticsearch\elasticsearch\src\Elasticsearch\ConnectionPool\StaticNoPingConnectionPool.php line 51:

No alive nodes found in your cluster

'hosts' => ['127.0.0.1:9200']

can you help me?

i'm newbie in elasticsearch



via Chebli Mohamed

Trying to set custom constraint name for default key in Schema Builder: Laravel 5.2

In schema builder we can use the below code to define our own name for the constraint. Below code is for Unique key

$table->unique('Column Name', 'Constraint Name');

Can I do something similar for the default key?

I tried below and did not work

$table->default('Column Name', 'Constraint Name');

I know we can write the below code to define the default constraint but that will not give custom constraint name

$table->boolean('IsPredefined')->default(false);



via Chebli Mohamed

How to fetch groupBy using eloquent Laravel

I want to fetch all subjects that belongs to each semester. However I cannot find ways to do that. For example in my view I want to fetch subjects that are offered in fist first-sem. Also display below subjects offered in first second-sem. Here is my code.

StudentCourseController

public function show($studentId, $courseId)
{
    $student = Student::findOrFail($studentId);
    $course = Course::with(['curriculum.subjects' => function($query){
        $query->get()->groupBy('sem_offered')->toArray();
    }])->findOrFail($courseId);

    return view('students.show',compact('student','course'));
}

Curriculum Model

class Curriculum extends Model
{
    protected $fillable = ['name', 'description'];

    public function course()
    {
        return $this->hasOne(Course::class);
    }

    public function subjects()
    {
        return $this->belongsToMany(Subject::class)->withPivot('sem_offered','grade','prerequisite');
    }
}

Subject Model

class Subject extends Model
{

    public function curricula()
    {
        return $this->belongsToMany(Curriculum::class)->withPivot('sem_offered','grade');
    }
}

Course Model

   class Course extends Model
  {
    protected $fillable = ['curriculum_id', 'name' ,'description'];

    public function curriculum()
    {
        return $this->belongsTo(Curriculum::class);
    }

}

Here is my view

        @foreach($course->curriculum->subjects as $subject)

    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>

@endforeach



via Chebli Mohamed

Laravel ModelFactory Seeding Pivot Table

I'm using Laravel ModelFactory too seed my database but I'm having problem seeding a pivot table when using model factory

[Symfony\Component\Debug\Exception\FatalThrowableError]

Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, boolean given, called in ............\Cashier\database\seeds\DatabaseSeeder.php on line 27

ModelFactory

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->safeEmail,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Product::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->unique->randomElement([
            'Item 100',
            'Item 200',
            'Item 300',
            'Item 500',
            'Item 600',
            'Item 700',
            'Item 900',
            'Item 150',
            'Item 250',
            'Item 350',
        ]),
        'price' => $faker->randomFloat(2, 100, 500),
        'image' => $faker->imageUrl(640, 480),
    ];
});

$factory->define(App\Cart::class, function (Faker\Generator $faker) {
    return [
        'quantity' => $faker->numberBetween(1, 10)
    ];
});

DatabaseSeeder

factory(App\Product::class, 10)->create();

factory(App\User::class, 5)->create()->each(function($user)
{
    $user->cart()->save(factory(App\Cart::class)->create()->each(function($cart)
    {
        $cart->products()->attach(App\Product::lists('id')->random());
    }));
});

User Model

public function cart()
{
    return $this->hasOne(Cart::class);
}

Cart Model

public function user()
{
    return $this->belongsTo(User::class);
}

public function products()
{
    return $this->belongsToMany(Product::class);
}



via Chebli Mohamed

User, Cart and Products Eloquent Relationship

I would like to ask about the User, Cart and Product eloquent relationships. The User hasOne Cart and the Cart can have many Product.

class User {

    public function cart()
    {
        return $this->hasOne(App\Cart::class);
    }
}



class Cart {

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

    public function products()
    {
        return $this->hasMany(App\Product::class);
    }
}



class Product {

    //
}

I have database table structured like:

users

- id
- email
- username
- password

carts

- id
- user_id
- product_id
- quantity

products

- id
- name
- price

Is this correct?



via Chebli Mohamed

samedi 25 juin 2016

Laravel Method Does not Exist

I can't echo the getTotal in the Cart Model

http://ift.tt/28TQQSR



via Chebli Mohamed

Laravel 5.2 ModelFactory Unexpected Result

I am using Laravel ModelFactory to automatically generate dummy data to be inserted to my database but I notice some unexpected result. Here is my pastebin of my ModelFactory and the result.

And this is my pastebin of expected result.



via Chebli Mohamed

In Laravel Which middleware fires first CSRF or AUTH

According to the Laravel Website

Laravel will first authenticate the USER that is fire the

Auth middleware and then fire CSRF middleware.

But What if the Login page is a a fishing page and isn't it the more natural to first check if the request is from our own website and then Check if the user authentication ??.

Can some one throw some light on the same .

Thanks

Any help would be appreciated



via Chebli Mohamed

Count in laravel by data

Here I want to add the data I have based id_data kos, so whenever I add data will auto count by id_data_kos.

here my controller :

$limit = 10;
        $result = DB::table('residents')
        ->join("data_kos","data_kos.id","=","residents.id_data_kos")
        ->select("residents.*","data_kos.title as data_title")
        ->groupBy('id_data_kos')
        ->orderBy('residents.id', 'asc');

$data['posts'] = $result->paginate($limit);

and this my view :

@foreach($posts as $row)
<td></td>
<td>here i want to count</td>
@endforeach

this my table :

this



via Chebli Mohamed

vendredi 24 juin 2016

How to make hash password if import excel laravel 5.1

How to make hash password in the model laravel 5.1? any idea?

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Members extends Model {

        //
        protected $fillable =  ['id', 'email', 'password', 'name', 'status_members'];
        protected $table = 'members';
}


via Chebli Mohamed

Invoice Template Builder

I have a simple invoice e.g.

 __________________________________________
|                                          |
| LOGO                        INVOICE      |
|__________________________________________|
|                                          |
| Name                        INV ID:0012  |
| Address                     DATE: 12/02  |
|__________________________________________|
|                                          |
|  ______________________________________  |
| | #  |  ITEM          |Qty|Price|Amount| |
| | 1  |  Item 1        | 2 |10.00| 20.00| |
| | 2  |  Item 2        | 1 | 2.00|  2.00| |
| |____|________________|___|_____|______| |
|                       | Total   | 22.00| |
|                       |_________|______| |
|                                          |
|__________________________________________|

This is very plane. I want my website user to be able to customize there Invoice as per there need.

  1. They can easily move the logo, Name, Address where they want.
  2. They can Add extra Form Fields anywhere in page (From a limited set of fields available to them)
  3. They can add Extra Text any where on the page.
  4. They can change the colors.
  5. They can also select from predefined designs. etc etc...

Now the question is, Is there any php, jquery/js laravel library that I can use to achieve this.

I install few wysiwyg editors (TinyMCE and CKEditor) but i was not able to restrict to to add elements from my limited list, also, I wasn't able to figure out how to save the design such that I can use that when user created a new Invoice from the template. Also adding form element was not a choice in those editors.

Please let me know if any part of my question does not make sense, I will try my best to elaborate.

Thanks



via Chebli Mohamed

laravel 5.1 error controller Missing argument 1

i have a foreach with my list of products in my index.blade.php, it work well, now i'm tryng to filter, i done my menu with my categories and genders.

I would like show products with category = "t-shirt" and gender= "woman" but i have this error:

ErrorException in StoreController.php line 36: Missing argument 1 for dixard\Http\Controllers\StoreController::products()

i'm using this link:

<a href="" title="">
     <span>Woman</span>
</a>

my route:

Route::get('shop', 'StoreController@index');
Route::get('shop/{category}/{gender}','StoreController@products');

My controller

public function products($category, $gender)
    {


            $gender_id= Gender::where('gender', $gender )->first();
            $category_id= Category::where('name', $category)->first();
            $filter = ['gender_id' => $gender_id->id, 'category_id' => $category_id->id];
            $products = Product::where($filter)->orderBy('id', 'asc')->get();
            $categories = Category::all();
            return view('store.index', compact('products','categories'));   


    }



via Chebli Mohamed

My alert is not showing in laravel 5

this is my PostController.php,

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    public function createPost(Request $request)
    {

        $depress = new Depress();
        $depress->depression = $request['depression'];
        if($request['name'])
            $depress->name = $request['name'];
        else
            $depress->name = "Depressed Anonymous";
        $depress->save();
        \Session::flash('info','Success');
        return redirect()->route('home');

    }
}

And This is my alert.blade.php,

@if(Session::has('info'))
    <div class="alert alert-success alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        
    </div>
    <br>
@endif

And, I have included it in my layout.blade.php

But, no alert shows up...

thanks in advance



via Chebli Mohamed

My alert doesn't show up in laravel 5

This is my alert.blade.php,

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

And this is my welcome.blade.php,

<!DOCTYPE html>
<html>
    <head>
        <title>Laravel</title>

        <link rel="stylesheet" href="http://ift.tt/1jAc5cP"     integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"     crossorigin="anonymous">

    </head>
    <body>
        @include('alert')
    </body>
</html>

And, here's my routes.php,

Route::get('/', function () {
    return view('welcome')->with('info','Hello World');
});

Any help will be really appreciated Thanks in advance



via Chebli Mohamed

Installing newrelic with Dokku

I have dokku installed with a laravel application deployed on it with Apache configuration. I Googled how to install newrelic on dokku but did not find any reliable source.

Please share your experience installing newrelic with PHP agent on dokku



via Chebli Mohamed

jeudi 23 juin 2016

Undfined variable 'posts' - Laravel 5

In my ShowController, I returned a view with variable posts, like

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Depress;
use DB;
use App\Http\Requests;

class ShowController extends Controller
{
    public function showPost(Request $request)
    {
        $posts = Depress::all();
        return view('homeview')->with('posts', $posts);
    }
}

And in my, homeview.blade.php ,

 @foreach($posts as $post)
        <div class="panel panel-default">
            <div class="panel-heading"></div>
            <div class="panel-body">
                
            </div>
        </div>
 @endforeach

But, it's showing, Undfined Variable: posts

Can anyone please help ?



via Chebli Mohamed

Class Memcached not found when deploying on sub domain in GoDaddy : Laravel 5.2.37

I got this error:

[2016-06-24 00:48:52] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Memcached' not found' in /home/Myserver/public_html/Laravel/vendor/laravel/framework/src/Illuminate/Cache‌​/MemcachedConnector.php:51 Stack trace: #0 {main}

There is no problem when the deployment is done on root. This issue comes only and only when being deployed on sub domain on GoDaddy.

Anybody faced this kind of issue on sub domain on Godaddy?



via Chebli Mohamed

Deploying Laravel 5.2.37 on Godaddy subdomain

Initially, It was deployed on root and everything was working fine. Let me explain Sub domain directory structure now.

After creating the subdomain, a new folder was created inside public_html. Sub folder name is Laravel. So it is like this public_html/Laravel

Below are the steps that I performed while moving files from Root to Sub Domain

  1. Moved all files in public_html/Laravel
  2. Created a New folder called public inside Laravel folder. So it is like this public_html/Laravel/public
  3. Moved all files from public_html to public_html/Laravel/public

Finally I checked the sub domain and got the below error.

Whoops, looks like something went wrong.

Am I missing something?



via Chebli Mohamed

Shpinx results not returning matches after spaces

When trying to do a search for bmw motorrad or partials of it.

bmw is ok

bmw m or any characters after return no results

bmw motorrad returns the company

We finally got a chance to move our servers from managed to self managed. in the process we upgraded mysql from 5.0.37 to 5.5.28.

We also upgraded sphinx from 0.9.9 to 2.2.10 with Sphinx as a mysql engine. We are using Laravel 5.1 and using a package sngrl\SphinxSearch to connect to sphinx.

Shpinx Conf:

Start Company Quick Search

source companyqs
{
        type                    =       mysql
        sql_query_pre           =       SET NAMES utf8
        sql_query               =       SELECT c.companyID, c.companyID AS priID , TRIM(REPLACE(c.coName, SUBSTRING(c.coName,LOCATE('[',c.coName), (LOCATE(']',c.coName)) - LOCATE('[',c.coName)+1), '')) AS companyName FROM company c WHERE c.coType = "Corporate" AND companyID >= $start AND companyID <= $end

        sql_attr_uint           =       priID
        sql_field_string        =       companyName
        sql_attr_string         =       cityState
        sql_attr_string         =       locationType
        sql_attr_string         =       cWebDisplay

}

index companyqs
{
        source                  =       companyqs
        path                    =       /usr/local/sphinx/var/data/companyqs
        min_word_len            =       2
        min_infix_len           =       1
}

config for sngrl\SphinxSearch

return array (
'host'    => env('SPHINX_DEV_HOST'),
'port'    => 9312,
'indexes' => array (
    'companyqs' => array ( 'table' => 'company', 'column' => 'companyID' ),
)

);

sphinxSearch search query

public function getQSAdvertiser($keyword){
    $sphinx = new SphinxSearch();
    $results = $sphinx
        ->search($keyword, 'companyqs')
        ->limit(10000)
        ->setMatchMode(\Sphinx\SphinxClient::SPH_MATCH_EXTENDED2)
        ->setRankingMode(\Sphinx\SphinxClient::SPH_RANK_MATCHANY)
        ->query();

    return $results;
}

Thanks for looking and appreciate any help.



via Chebli Mohamed

Adding a Value to Collection Items

I want to load data from many files. Each file is named with a date and I need to inject this date to each of the fetched Entries of my file. I know I could do this with an foreach - loop before inserting the data into the collection, but I think there should be a better solution.

Content of one file

[{"price":"95,34","isin":"FR0000120073"},{"price":"113,475","isin":"CA13645T1003"}]

The Code I use to move the data into a collection.

$collection= collect(json_decode(File::get($file)));

I tried for example the "map" method, however I don't know how to pass an additional variable to the anonymous function.

The content of my collection should look like this:

[{"price":"95,34","isin":"FR0000120073","date":"2016-06-23"},{"price":"113,475","isin":"CA13645T1003","date":"2016-06-23"}]

Is there any simple solution using the collections or do I have to use a foreach-loop?



via Chebli Mohamed

Laravel5 logs analysis of dokku

I have dokku running laravel5, I am challenged to analyze the logs since I can't use the log config daily. It must be configured as syslog.

Is there a tool like papertail that works for dokku

I want to analyze issues, the way I do it now is downloading the logs and analyze them manually

Looking for a better approach



via Chebli Mohamed

Change root to public inside sub-folder

I work in an agency and I created a subdomain in order to show our customers some code examples we can provide, all my applications are made in Laravel 5.1, and each application is being placed in a sub-directory, like this:

scripts.domain.com
   /image-filter
      /public
   /facebook-image-app
      /public
   /twitter-integration
      /public
   /instagram-wall
      /public

I need to point the root into the public folder...

I've tried this, but it didn't work as expected:

RewriteEngine on
RewriteCond %{REQUEST_URI} !public/
RewriteCond %{HTTP_HOST} ^http://ift.tt/28Qplr6 [NC,OR]
RewriteCond %{HTTP_HOST} ^http://ift.tt/28SrHbJ
RewriteRule (.*) /public/$1 [L]

Any idea on this?



via Chebli Mohamed

Laravel - Keep watching Table Column

I am creating an application and when the user registers the value 0 is assigned to the role column, however as it will using the application, this value can be changed. Is there any method of watching the change of that column? I would like to send an email to the user if this value change to 1.



via Chebli Mohamed

How to automate Google SiteVerification Service using laravel in back-end and angularjs in front-end?

I have created the api for the execution of a process triggered from the front-end performing other functionalities (suppose function site(param1, param2) : param1-> {id} , param2->Request object). Then in that function site() , I have called the function of same controller for the google services (suppose function google(param1): param1->Request object) in that I have called the custom service designed to perform google Site Verification. Given the redirect uri in google client json is of function google().

Problem I am facing from calling function site() from front-end is that it is unable to perform google services.



via Chebli Mohamed

Laravel 5.1 using morph relation with global scope

I have global scope on my Product model and method withChildren to get data over scope. All was ok, until i tried use it with morph relation.

Code

Scope code

public function apply(Builder $builder, Model $model)
{
    return $builder->whereNull('parent_id');
}

/**
 * Remove the scope from the given Eloquent query builder.
 *
 * @param  \Illuminate\Database\Eloquent\Builder  $builder
 * @param  \Illuminate\Database\Eloquent\Model  $model
 * @return void
 */
public function remove(Builder $builder, Model $model)
{
    $query = $builder->getQuery();
    foreach ((array) $query->wheres as $key => $where)
    {
        if($where['column'] === 'parent_id')
        {
            unset($query->wheres[$key]);
            $query->wheres = array_values($query->wheres);
        }
    }
}

withChildren method

public function scopeWithChildren()
{
    return with(new static)->newQueryWithoutScope(new ParentScope);
}

Scope injected in model through boot method, like so

protected static function boot()
{
    parent::boot();
    //exclude children products from all results by default
    Product::addGlobalScope(new ParentScope);
}

Problem

Relation returns null before i can implement my withChildren method. Invoice and Product have simple plymorphic relation.

$products = $invoice->products; //products is null, because of global scope

Tried

$invoice->products()->withChildren()->get() //500 error without any description
$invoice->with('products', function($q) {$e->withChildren();})->get(); //explode() expects parameter 2 to be string, object given



via Chebli Mohamed

Send email when make new post in laravel

I want to make in my app subscription feature, so here I want to make a new post it will automatically send an email to the email who on my list subscription.

well, I'm here already have the data which it contain the subscription emails. (Table name: subs)

here my controller:

public function postAddSave() {
        $simpan= array();
        $simpan['title']=Request::input('title');
        $simpan['stock_room']=Request::input('stock_room');
        $simpan['kamar']=Request::input('kamar');
        $simpan['mandi']=Request::input('mandi');
        $simpan['sex']=Request::input('sex');
        $simpan['address']=Request::input('address');
        $simpan['description']=Request::input('description');
        $facilities = implode(',',Request::get('facilities'));
        $simpan['price']=Request::input('price');
        $simpan['coordinate']=Request::input('coordinate');

        DB::table('data_kos')->insert($simpan);
        Session::flash('success', 'Data has been created');
        return Redirect::to('home');
    }

and here my view :

<form method='post' action='' enctype="multipart/form-data">
                <input type="hidden" name="_token" value="">
                <div class="box-body">
                    <div class="box-body">
                    <div class='form-group col-sm-6'>
                        <label>Title</label>
                        <input type='text' class='form-control' name='title' value='' required/>
                    </div>
                    <div class='form-group col-sm-2'>
                        <label>Stock room</label>
                        <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-bed" aria-hidden="true"></i></span>
                    <input type="text" class="form-control" name="stock_room" required>
                    </div>
                    </div>
                    <div class='form-group col-sm-2'>
                        <label>Room Used</label>
                    <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-bed" aria-hidden="true"></i></span>
                    <input type="text" class="form-control" name="kamar" required>
                    </div>
                    </div>
                    <div class='form-group col-sm-2'>
                        <label>bathroom</label>
                    <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-child" aria-hidden="true"></i></span>
                    <input type="text" class="form-control" name="mandi" required>
                    </div>
                    </div>
                    <div class='form-group col-sm-5'>
                        <label>Address</label>
                        <input type='text' class='form-control' name='address' value='' required/>
                    </div>
                    <div class='form-group col-sm-3'>
                        <label>Price/month</label>
                    <div class="input-group">
                    <span class="input-group-addon">Rp.</span>
                    <input type="text" class="form-control" name="price" required>
                    </div>
                    </div>
                    <div class='form-group col-sm-4'>
                        <label>Category</label><br>
                        <input type="radio" name="sex" value="Wanita">Wanita</input>&nbsp;&nbsp;&nbsp;
                        <input type="radio" name="sex" value="Laki-Laki">Laki-laki</input>&nbsp;&nbsp;&nbsp;
                        <!-- <input type="radio" name="sex" value="Wanita/Laki-laki">Wanita/Laki-laki</input> -->
                    </div>
                    <div class='form-group col-sm-12'>
                        <label>Description</label>
                    <textarea class="ckeditor" placeholder="Place some text here" name="description"></textarea>
                    </div>
                    <div class='form-group col-sm-12'>
                        <label>Facilities</label>
                        <div class="checkbox">
                        @foreach ($facilities as $rows)
                        <label>
                            <input type="checkbox" value="" name="facilities[]">
                              
                        </label>
                        @endforeach  
                        </div>
                    </div>
                    <div class='form-group col-sm-12'>
                        <label>Coordinate</label>
                        <input type='text' class='form-control' name='coordinate' value='' required/>
                    </div>
                    <div class='form-group col-sm-12'>
                        <button type='submit' class='btn btn-primary'><i class='fa fa-save'></i> Simpan</button>
                    </div>
            </div><!-- /.box -->
            </form>

NB : list email to i get from table subs

so, have someone help me what improvements do i have to make to the code to achieve my goal?



via Chebli Mohamed

mercredi 22 juin 2016

Cannot upload file using guzzle and send to laravel API

I have two laravel projects, one for API and one for front end. What I want to achieve is to send the uploaded file on my front end and send it to my API using guzzlehttp6. Here's my code.

FrontEnd Laravel:

public function store(Request $request, $module_id)
{
    $videos = $request->file('file');
    // $name = time().$videos->getClientOriginalName();
    // $path = ('videos');
    // $videoFinal = $videos->move($path, $name);

    $file_name = fopen($videos, 'r');
    $client = new Client(['base_uri' => 'http://localhost/api.kourse/public/api/v1/']);

    try{
        $response = $client->request('POST', 'modules/'.$module_id.'/videos',[

            'fie_name' => $file_name

        ]);

    }catch(ClientException $e){
        return $e->getResponse();
    }


}

When returning the $videos im getting the path of the file.

Here's my API

public function store(VideoRequest $request, $moduleId)
{

    $module = Module::find($moduleId);

    if( !$module )
    {
        return response()->json([

            'message'   => 'Module does not exist',
            'code'      => 404
        ],404);
    }

    $file = $request->file('file_name');
    $name = time(). $file->getClientOriginalName();
    $path = '/videos';
    $file->move(public_path().$path, $name);
    Video::create([

        'file_name' => $name,
        'file_path' => $path.$name,
        'module_id' => $module->id
    ]);

    return response()->json([

        'message'   => 'Successfully created and assgin video to this module'
    ],200);
}

What Iam getting is that :

{message: {file_name: ["The file name field is required."]}, code: 422}
code
:
422

as defined in my VideoRequest.

Can anyone help me on this.



via Chebli Mohamed

Issue when fetching the Query String : Laravel 5.2.37

In my request class I have below code.

protected function getValidatorInstance()
{
    $instance = parent::getValidatorInstance();
    $instance->after(function ($validator) {
        $this->CheckRoleExists($validator);
    });
    return $instance;
}

public function CheckRoleExists($validator)
{
    dd($_SERVER);
}

I am trying to print the Query string and I am getting below.

"QUERY_STRING" => ""

and Url is below.

"REQUEST_URI" => "/Learning/public/UpdateRole/1"

My Route is below

Route::put('/UpdateRole/{RoleID}',array('uses' => 'Role@update', 'as' => 'UpdateRole'));

In the above Request Url: 1 is Query String. As we can see Query String value is showing null when I check it like this dd($_SERVER);

Please guide me to get the Query string correctly



via Chebli Mohamed

Send info from One browser to another in Laravel 5.2.37

I have a page where user can Add/Update records. Code is written in Laravel 5.2

Let's say I opened the that add/update page in chrome and same url in FireFox. So, if user create a new record in Chrome browser, info should be received immediately to Firefox. So, that I don't need to send ajax based reqeust to server to show complete list.

My question is, where should I start for this? Is there any blog that I can go through step by step ?



via Chebli Mohamed

Laravel 5.1 Php artisan commands not working after composer update

here is my composer.json require snippet.

"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.1.35",
    "aws/aws-sdk-php-laravel": "~3.0",
    "lucadegasperi/oauth2-server-laravel": "5.1.*",
    "bosnadev/repositories": " 0.*",
    "laravelcollective/html": "5.1.*",
    "cartalyst/stripe-laravel": "3.0.*"
},

I ran composer update in order to add new AWS services. but then I noted that all the vendor files are updated because of composer update command. now I'm getting error when I ran php artisan commands.

This is the error message:-

PHP Catchable fatal error:  Argument 2 passed to Illuminate\Routing\UrlGenerator
::__construct() must be an instance of Illuminate\Http\Request, null given, call
ed in C:\Users\User\projects\projectxyz\projectxyzweb\vendor\laravel\framework\
src\Illuminate\Routing\RoutingServiceProvider.php on line 62 and defined in C:\U
sers\User\projects\projectxyz\projectxyzweb\vendor\laravel\framework\src\Illumi
nate\Routing\UrlGenerator.php on line 102

How can I resolve this issue? is there any wayto revert composer update without loosing my code?



via Chebli Mohamed

How to add custom variable in form tag in twig(Laravel)?

How to add custom variable in form tag in twig(Laravel)? For example:

{!! Form::select('slt-mv-driver-name-****[]', $a_slt_user, Input::old('slt-mv-driver-name-1', isset($s_unique_id) ? $a_details_result->data->a_drivers : '') , array('class'=>'form-control multiselect slt-mv-driver-name','id'=>'slt-mv-driver-name-1', 'multiple' => 'multiple')) !!}

In above tag I want to put the value of $abcd dynamically. How can I do that?



via Chebli Mohamed

The requested URL /laravel-filemanager was not found on this server in UniSharp/laravel-filemanager

I am using UniSharp/laravel-filemanager and I've done all steps to install it , but when I want to use it i face this error :

I am using laravel 5.1 on wamp server

Not Found

The requested URL /laravel-filemanager was not found on this server.

Apache/2.4.9 (Win64) PHP/5.5.12 Server at localhost Port 80



via Chebli Mohamed

How can i rename directory in Laravel5.1

How can I rename directory on public , In my controller ? I read Laravel document but File class doesn't have rename .

File::move();

I just need rename , I cant move my files to an other Folder



via Chebli Mohamed

mardi 21 juin 2016

Laravel 5.1: Query Builder Select Multi table and SUM result

My code

DB::table('users_tb')->leftjoin('device_tb', 'device_tb.user_id', '=', 'users_tb.user_id')
->leftjoin('part_tb', 'device_tb.device_id', '=', 'part_tb.device_id')
->select('users_tb.user_name', DB::raw("(SELECT COUNT(part_tb.id) FROM part_tb) AS counter"))
->where('users_tb.level', '>', 7)
->havingRaw("(SELECT COUNT(part_tb.id) FROM part_tb) > 0")
->groupBy('device_tb.device_id')
->orderBy('users_tb.user_name')
->get()->toArray();

My result:

Name1 - 3
Name1 - 4
Name1 - 3
Name2 - 11
Name2 - 2

How i can SUM counter? Example:

Name1 - 10 (3+4+3)
Name2 - 13 (11 + 2)

Somebody help me, please!!



via Chebli Mohamed

how to validate nested json using request file in laravel 5.1

This is my form post data ,I want to validate this post data using custom validation request class.I am able to check all the validation rules against normal data but unable to check the same kind of rules to secondatry_users.I need my request files also apply rules on secondary_users data defined in the rules method

[
  "first_name" => "Shubham"
  "last_name" => "Jolly"
  "email" => "sachinu.meta@gmail.com"
  "mobile" => ""
  "status" => "1"
  "role" => "7"
  "trial" => ""
  "password" => "HQfZ6$px"
  "autogenerate" => "1"
  "secondary_users" => "{
            "1":{
            "recordID":1,
            "secondaryUserFirstName":"shubhamiii",
            "secondaryUserLastName":"s",
            "secondaryUserEmail":"shubha.jolly@daffodilsw.com",
            "secondaryUserMoble":"",
            "secondaryUserStatus":"1",
            "secondaryUserTrial":"",
            "secondaryUserPassword":"SyEsM#w2",
            "tag":""
            },
            "2":{
            "recordID":2,
            "secondaryUserFirstName":"shubha",
            "secondaryUserLastName":"jolly",
            "secondaryUserEmail":"shubham.jolly@daffodilsw.com",
            "secondaryUserMoble":"9896156667",
            "secondaryUserStatus":"1",
            "secondaryUserTrial":"2",
            "secondaryUserPassword":"aasM#w2",
            "tag":""
            }
        }"
]

How to validate this data i have created rules but its not working for the secondary_users input.

public function rules() {                 
     // Basic Property Validation  
    $rules = [
    'first_name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users',
    'role' => 'required',
    'status' => 'required',
    'password' => 'required|min:8|max:30|http://regex:/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()+]+.*)[0-9a-zA-Z\w!@#$%^&*()+]{8,}$/',
     'trial' => 'numeric',
     ];
      //secondary users validation
    if (isset($secondaryUser) && !empty(json_decode($secondaryUser))) {
         $usersArray = json_decode($secondaryUser);
             foreach ($usersArray as $key => $value) {
                   $rules['secondary_users.' . $key . '.secondaryUserFirstName'] = 'required|max:255';
                   $rules['secondary_users.' . $key . '.secondaryUserEmail'] = 'required|email|max:255|unique:users';
                   $rules['secondary_users.' . $key . '.secondaryUserStatus'] = 'required';
                   $rules['secondary_users.' . $key . '.secondaryUserTrial'] = 'numeric';
                   $rules['secondary_users.' . $key . '.secondaryUserPassword'] = 'required|min:8|max:30|http://regex:/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()+]+.*)[0-9a-zA-Z\w!@#$%^&*()+]{8,}$/';

                }
            }
        return rules;
        }



via Chebli Mohamed

Export data to Excel in Laravel

I want to make export data into excel in my project, i have made it, but after I check the results, the results doesnt like what I want. here I would like to make a result there is a title table.

This code my controller:

public function getExport(){
        Excel::create('Export data', function($excel) {

        $excel->sheet('Sheet 1', function($sheet) {

            $products=DB::table('log_patrols')
            ->join("cms_companies","cms_companies.id","=","log_patrols.id_cms_companies")
            ->join("securities","securities.id","=","log_patrols.id_securities")
            ->select("log_patrols.*","cms_companies.name as nama_companies","securities.name as nama_security")
            ->get();
                foreach($products as $product) {
                 $data[] = array(
                    $product->date_start,
                    $product->date_end,
                    $product->condition_status,
                    $product->nama_security,
                    $product->nama_companies,
                );
            }
            $sheet->fromArray($data);
        });
    })->export('xls');
    }

this my problem result : result

and it should be :

should

my problem is how to change the number into text what i want in the header table.

what improvements do i have to make to the code to achieve my goal?

NB : i use maatwebsite/excel



via Chebli Mohamed

Randomize order of divs in a form

I have looked around at the numerous questions regarding randomizing divs and have tweaked some code that does the job almost perfectly.

I have a form that contains 10 multichoice questions, on the page load I am wanting to randomize the order that they appear in; but using the code below they end up in a random order, with the submit button of the form above them.

HTML

<form method="POST" action="http://ift.tt/28MEqsv" accept-charset="UTF-8">    

    <div class="form-group">
        <h3>Multiple Choice</h3>
    </div>

    <div class='form-group question'>
        <label for="multi1">1) What is our server&#039;s genre?</label>
        <div class='radio'><label><input name="multi1" type="radio" value="a" id="multi1"> Light Roleplay</label></div>
        <div class='radio'><label><input name="multi1" type="radio" value="b" id="multi1"> Deathmatch/Freeroam</label></div>
        <div class='radio'><label><input name="multi1" type="radio" value="c" id="multi1"> Heavy Roleplay</label></div>
        <div class='radio'><label><input name="multi1" type="radio" value="d" id="multi1"> Drifting</label></div>
    </div>

    <div class='form-group question'>
        <label for="multi2">2) An advanced knowledge of which of the following languages is required on our server?</label>
        <div class='radio'><label><input name="multi2" type="radio" value="a" id="multi2"> Russian</label></div>
        <div class='radio'><label><input name="multi2" type="radio" value="b" id="multi2"> English</label></div>
        <div class='radio'><label><input name="multi2" type="radio" value="c" id="multi2"> Latvian</label></div>
        <div class='radio'><label><input name="multi2" type="radio" value="d" id="multi2"> All languages are acceptable</label></div>
    </div>

    <div class='form-group question'>
        <label for="multi3">3) Which of the following activities are controlled because of Rule 6?</label>
        <div class='radio'><label><input name="multi3" type="radio" value="a" id="multi3"> Torturing a character</label></div>
        <div class='radio'><label><input name="multi3" type="radio" value="b" id="multi3"> Character killing another player's character</label></div>
        <div class='radio'><label><input name="multi3" type="radio" value="c" id="multi3"> Disregarding another player's out-of-character communication</label></div>
        <div class='radio'><label><input name="multi3" type="radio" value="d" id="multi3"> Ignoring an administrator's ruling</label></div>
    </div>

    <div class='form-group question'>
        <label for="multi4">4) If you wish to steal a property from another player, which of the following is the correct way to do so?</label>
        <div class='radio'><label><input name="multi4" type="radio" value="a" id="multi4"> Obtain administrator permission beforehand by using the report system in-game</label></div>
        <div class='radio'><label><input name="multi4" type="radio" value="b" id="multi4"> Roleplay it first, then ask for an administrator to transfer the property</label></div>
        <div class='radio'><label><input name="multi4" type="radio" value="c" id="multi4"> Have the stolen property transferred by filling out the application</label></div>
        <div class='radio'><label><input name="multi4" type="radio" value="d" id="multi4"> None of the above</label></div>
    </div>

    <div class='form-group question'>
        <label for="multi5">5) Which of the following activities is against the rules?</label>
        <div class='radio'><label><input name="multi5" type="radio" value="a" id="multi5"> Killing several gang members in a drive-by without having interacted with them at all beforehand</label></div>
        <div class='radio'><label><input name="multi5" type="radio" value="b" id="multi5"> Requiring that anyone who joins your organization agrees to a CK contract</label></div>
        <div class='radio'><label><input name="multi5" type="radio" value="c" id="multi5"> Demanding a reason for being killed from your killer through out-of-character communication</label></div>
        <div class='radio'><label><input name="multi5" type="radio" value="d" id="multi5"> Robbing someone's character near the boardwalk</label></div>
    </div>

    <div class='form-group question'>
        <label for="multi6">6) Which of the following player names would be acceptable?</label>
        <div class='radio'><label><input name="multi6" type="radio" value="a" id="multi6"> Wei Jiang</label></div>
        <div class='radio'><label><input name="multi6" type="radio" value="b" id="multi6"> Asuka Kasen</label></div>
        <div class='radio'><label><input name="multi6" type="radio" value="c" id="multi6"> Cristiano Ronaldo</label></div>
        <div class='radio'><label><input name="multi6" type="radio" value="d" id="multi6"> Raimonds Vejonis</label></div>
    </div>

    <div class='form-group question'>
        <label for="multi7">7) When is it acceptable to completely ignore another player&#039;s out-of-character communication?</label>
        <div class='radio'><label><input name="multi7" type="radio" value="a" id="multi7"> Always</label></div>
        <div class='radio'><label><input name="multi7" type="radio" value="b" id="multi7"> If they are breaking server rules or encouraging the breaking of server rules</label></div>
        <div class='radio'><label><input name="multi7" type="radio" value="c" id="multi7"> Anytime, as long as it isn't to tell a player why you killed them</label></div>
        <div class='radio'><label><input name="multi7" type="radio" value="d" id="multi7"> Never</label></div>
    </div>

    <div class='form-group question'>
        <label for="multi8">8) You are killed. You see your killer later, yell out to them your reasoning for killing them, and kill them to take revenge. Is that acceptable?</label>
        <div class='radio'><label><input name="multi8" type="radio" value="a" id="multi8"> No, because you did not roleplay with them sufficiently beforehand, so you are guilty of deathmatching</label></div>
        <div class='radio'><label><input name="multi8" type="radio" value="b" id="multi8"> Yes, because you had a solid reason for killing them</label></div>
        <div class='radio'><label><input name="multi8" type="radio" value="c" id="multi8"> No, because killing another player just for killing you is not allowed</label></div>
        <div class='radio'><label><input name="multi8" type="radio" value="d" id="multi8"> Yes, as long as you interacted with them before killing them</label></div>
    </div>

    <div class='form-group question'>
        <label for="multi9">9) Which of the following could be classified as powergaming?</label>
        <div class='radio'><label><input name="multi9" type="radio" value="a" id="multi9"> Killing another player as part of a contract killing</label></div>
        <div class='radio'><label><input name="multi9" type="radio" value="b" id="multi9"> Roleplaying acting on instructions from an NPC of your own creation</label></div>
        <div class='radio'><label><input name="multi9" type="radio" value="c" id="multi9"> Helping a friend evade police who asked for your help over an out-of-character form of communication</label></div>
        <div class='radio'><label><input name="multi9" type="radio" value="d" id="multi9"> Committing a crime in an unrealistic area</label></div>
    </div>

    <div class='form-group question'>
        <label for="multi10">10) Which of the following could be classified as metagaming?</label>
        <div class='radio'><label><input name="multi10" type="radio" value="a" id="multi10"> Assuming a character's gang affiliations by their clothing</label></div>
        <div class='radio'><label><input name="multi10" type="radio" value="b" id="multi10"> Identifying an organization in-game based on publicly available information in an in-character section of the forums</label></div>
        <div class='radio'><label><input name="multi10" type="radio" value="c" id="multi10"> Sharing potentially sensitive in-character information about an organization out of character</label></div>
        <div class='radio'><label><input name="multi10" type="radio" value="d" id="multi10"> Accepting money in-game to kill a target</label></div>
    </div>

    <div class='form-group'>
        <input class="btn btn-primary" type="submit" value="Submit">
    </div>

    </form>

jQuery that I am using to randomize them

$.fn.randomize = function(selector){
    (selector ? this.find(selector) : this).parent().each(function(){
        $(this).children(selector).sort(function(){
            return Math.random() - 0.5;
        }).detach().appendTo(this);
    });

    return this;
};

$('form').randomize('.question');
$('.question').randomize('.radio');

As per the screenshot below, you can see what I mean regarding the submit button:

Submit button above the questions

How can I get the questions randomized like I have done, without the submit button moving up to the top too?



via Chebli Mohamed