samedi 28 mai 2016

Sort by average value of a one to many related table column

I have 2 models; Post and Rating

The Rating model contains an amount column which specifies how high something has been rated. This is based on 5 star rating so the amount can be a value from 1-5

The Post model has a one to many relation with the rating model and function called Ratings that returns the hasMany.

I'd like to get the 5 latest posts based on the average rating. For the average rating I've created a function that can be seen below

Note: the plural(Ratings) returns the hasMany relation where as the singular(Rating) returns a value which is the average rating

public function Rating(){
    return floor($this->Ratings()->avg('rating'));
}

Is it possible to retrieve posts ordered by the avg rating using the Eloquent QueryBuilder?

Currently I'm retrieving all posts and then using the sortBy method on the collection object in order get the ones with the highest average rating. The way I'm doing this can be seen below.

$posts = Post::all();

$posts = $posts->sortByDesc(function ($post, $key) {
    return $post->Rating();
});

Now if I'd only want to show 5 I still have to retrieve and sort everything which doesn't seem very resource friendly(In my eyes. I don't have any proof of this or say it is true).

So my question is the following: Is this doable using Eloquent instead of sorting the FULL collection.

Sub question: Will doing this with Eloquent instead of sorting the collection have any impact on efficiency?



via Chebli Mohamed

Query chaining without using QueryScopes in Laravel

I'm building an analytics dashboard for a large laravel app that contains many complex queries. Often I want to chain queries together, as otherwise I'm duplicating code all over the place, to write something like this:

$query_result = $this->customers
    ->whereActiveBetween($dates)
    ->withOrdersizeGreaterThan($amount)
    ->get();

Because they are very specific, long, and not used in other parts of the app, I want to avoid polluting my already complex models with query scopes that are only going to be used by the analytics repository. So, what is the best way to achieve this, both keeping code readable, and making the code reusable?



via Chebli Mohamed

Is there anyway to code such that I can define or condition in middleware?

I have three roles in my application. I have a condition in which two roles can access same page. For that I write below code.

in below code, sub plan1 and sub plan 2 are roles.

Route::group(['middleware' => ['web', 'auth', 'SubPlan1', 'SubPlan2']], function () {
    Route::get('/Parent-1-Info', '\ContactInfoController@Parent1Info'));
});

if sub plan1, tries to access the page, I get 404 error because i mentioned both middleware in same group.

Is there anyway to code such that I can define or condition in middleware?



via Chebli Mohamed

Pass variable from one function to another inside a single controller

I'm trying to pass a variable within a function to the next function which is called but I can an error to say the variable isn't defined.

public function postPayment(Request $request) {

//Fetch package name
$package = $request->input('package');

//Record order
return $this->recordOrder()->with('package', $package);

}

   public function recordOrder($package){

    $stripe_trans = User::where('id', Auth::user()->id)->pluck('stripe_id');

    $order = new Orders;
    $order->user_id = Auth::user()->id;
    $order->order_id = $stripe_trans;
    $order->status = 'Pending';

    $order->save();

    return redirect()->back();
}



via Chebli Mohamed

Laravel 5 Route::group with public variable

I have some code like this:

Route::group(['prefix'=>'dashboard'],function(){        
    Route::get('addnew',function(){
        $user = DB::table('users')->where('username','=',session('username'))->first();
        $data = array('level' => $user->level, 'name' => $user->name,'email' => $user->email);
        return view('layout.addnew')->with($data);
    });
    Route::get('load',function(){
        $user = DB::table('users')->where('username','=',session('username'))->first();
        $data = array('level' => $user->level, 'name' => $user->name,'email' => $user->email);
        return view('layout.load')->with($data);
    });
});

But it don't work when i use public variable like this:

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

    $user = DB::table('users')->where('username','=',session('username'))->first();
    $data = array('level' => $user->level, 'name' => $user->name,'email' => $user->email);

    Route::get('addnew',function(){        
        return view('layout.addnew')->with($data);
    });
    Route::get('load',function(){        
        return view('layout.load')->with($data);
    });
});

Help me please!



via Chebli Mohamed

getTokenForRequest always returns null in Laravel 5.2.31

I am working on API in Laravel. My route is below.

Route::group(['prefix' => 'api/v1', 'middleware' => 'auth.api'], function () {
    Route::get('/DownloadMedia/{MediaID}', 'MediaController@DownloadMedia');
});

In below file

\vendor\laravel\framework\src\Illuminate\Auth\TokenGuard.php

Method: getTokenForRequest() always returns Token value = null

when I started the debugging and printed the value of dd($this->request);

I get below values.

enter image description here

Here is problem is why getTokenForRequest() is always null?

bearerToken() and $this->request->input($this->inputKey) and $this->request->getPassword() all are null

Can you explain why this is null?

My Url is below

http://ift.tt/1TLmdxo



via Chebli Mohamed

Vue js fetching checkbox

I am new to vuejs. i would like to check the checkbox based on data fetched from database. I would also like the change the checkbox value and update. How do i do that with vuejs?. This is how i am trying to do in laravel blade template:

<div class="well well-lg">
                            <div class="checkbox" v-for="action in ActionList">
                                <label><input type="checkbox"
                                              v-model="newActionAdminRole.ActionAdminRole"
                                              v-bind:checked="ActionChecked(action.actionID)"
                                              value="@"
                                              name="ActionCheckbox">@</label>
                            </div>
                        </div>
                        <button type="submit" style="float:right;"
                                v-bind:class="['btn', newActionAdminRole.ActionAdminRole.length == 0 ? 'btn-default' : 'btn-primary']"
                                v-on:click.prevent="saveActionAdminRole">
                            Save
                        </button>
                        <input type="hidden" value="" name="_token">
                    </form>

Here is my vuejs:

data: {
        newActionAdminRole: {
            selected: [],
            ActionAdminRole: []
        },

        adminroles: [],

        permissions: [],
        ActionList: '',
        roles: '',
    },



     methods: {
///this fetches the action details assigned to the role from the database
    fetchActionDetail: function (id) {
                NProgress.start();
                this.newActionAdminRole.ActionAdminRole = [];

                var self = this;
                this.$http.get('/cimsm/public/api/getActionAdminRole/' + this.newActionAdminRole.selected).then(function (response) {

                    var data = response.data;

                    self.$set('permissions', data);


                });

                NProgress.done();

            },
    ActionChecked: function(val){
                this.permissions.forEach(function(perm){
                    if(perm.actionID==val)
                    {
                        return true;
                    }


                })

am i doing it wrong?



via Chebli Mohamed