samedi 2 juillet 2016

Laravel recursive relations with filter

I have following tables:

  1. organizations table which represents hierarchy (contains id and parent_id)
  2. budget_user_limits - organization_id (FK), limit_amount and budget_id (should filter by this column)

I have managed to create a function (currentUserOrganizationTree, code below) to retrieve hierarchy starting from $root. And I filtered limits by budget_id=1. Yet, I have two challenges:

  1. I don't know how to make this filter dynamic in terms that I need to use parameter from currentUserOrganizationTree($budget_id)
  2. root element does not get limits loaded -> this one should be easy but I don't know how to solve it elegantly

What I tried so far:

  1. passing filter value as parameter to all functions but with relations do not accept parameters. ->with('allChildren') dont know how to pass parameter to allChildren function
  2. creating instance level property and assign it budget_id so it can be used by subsequent executions of limits function. Yet it is instance level property and descendant Organization objects will not have it
  3. decided not to go with static property (as in previous item) since I believe it will not work properly in multiuser concurrent environment

Code (this is in Organization model):

public function childrenWithLimits()
{
    return $this->hasMany('App\Organization', 'parent_id', 'id')->orderBy('code');
}

public function allChildrenWithLimits()
{
    return $this->childrenWithLimits()->with('allChildrenWithLimits', 'limits');
}

public function limits()
{
    return $this->hasMany('App\BudgetUserLimit', 'organization_id', 'id')->where('budget_id', 1); // dynamic filter ($budget_id) should be used, not hardcoded
}

public static function currentUserOrganizationTree($budget_id)
{
    ... // logic to get $root is omitted
    $root = $root->get()->first(); // this one does not get limits loaded
    $root['all_children'] = $root->allChildrenWithLimits()->get();
    $arr = [$root];
    return $arr;
}



via Chebli Mohamed

Display month along with its year

I have an array like so:

1 => array:7 [▼
  "id" => "4"
  "order_code" => "BS-ORD-000000004"
  "order_type" => "Mixed - Subscription"
  "subscription_months" => "4"
  "subscription_start_month" => Carbon {#714 ▼
    +"date": "2016-11-05 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "subscription_end_month" => Carbon {#723 ▼
    +"date": "2017-03-04 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "monthName" => "November"
]
2 => array:7 [▼
  "id" => "4"
  "order_code" => "BS-ORD-000000004"
  "order_type" => "Mixed - Subscription"
  "subscription_months" => "4"
  "subscription_start_month" => Carbon {#721 ▼
    +"date": "2016-11-05 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "subscription_end_month" => Carbon {#717 ▼
    +"date": "2017-03-04 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "monthName" => "December"
]
3 => array:7 [▼
  "id" => "4"
  "order_code" => "BS-ORD-000000004"
  "order_type" => "Mixed - Subscription"
  "subscription_months" => "4"
  "subscription_start_month" => Carbon {#729 ▼
    +"date": "2016-11-05 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "subscription_end_month" => Carbon {#730 ▼
    +"date": "2017-03-04 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "monthName" => "January"
]
4 => array:7 [▼
  "id" => "4"
  "order_code" => "BS-ORD-000000004"
  "order_type" => "Mixed - Subscription"
  "subscription_months" => "4"
  "subscription_start_month" => Carbon {#732 ▼
    +"date": "2016-11-05 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "subscription_end_month" => Carbon {#733 ▼
    +"date": "2017-03-04 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "monthName" => "February"
]

Now what I want is to append a year to the monthName key after adding the months from subscription_start_month key.

Example of what I want:

2 => array:7 [▼
  "id" => "4"
  "order_code" => "BS-ORD-000000004"
  "order_type" => "Mixed - Subscription"
  "subscription_months" => "4"
  "subscription_start_month" => Carbon {#721 ▼
    +"date": "2016-11-05 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "subscription_end_month" => Carbon {#717 ▼
    +"date": "2017-03-04 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "monthName" => "December, 2016" // <-- The current year
]
3 => array:7 [▼
  "id" => "4"
  "order_code" => "BS-ORD-000000004"
  "order_type" => "Mixed - Subscription"
  "subscription_months" => "4"
  "subscription_start_month" => Carbon {#729 ▼
    +"date": "2016-11-05 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "subscription_end_month" => Carbon {#730 ▼
    +"date": "2017-03-04 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "UTC"
  }
  "monthName" => "January, 2017" // <-- The next year
]

I have the tried the following code, but it does not work as expected.

$startMonthForMixed = $invoice->subscription_start_date->month;

for($i = 0; $i < $invoice->subscription_months; $i++) {
    $convertedInvoices[] = [
        'id' => $invoice->id,
        'order_code'               => $invoice->order_code,
        'order_type'               => 'Mixed - Subscription',
        'subscription_months'      => $invoice->subscription_months,
        'subscription_start_month' => $invoice->subscription_start_date,
        'subscription_end_month'   => $invoice->subscription_end_date,
        'monthName'                => date("F", mktime(0, 0, 0, $startMonthForMixed, 01)) . ", " . Carbon::now()->addYear()
     ];
     $startMonthForMixed++;
 }

How can I achieve that ? Kindly help me out..



via Chebli Mohamed

Laravel Category Filter

I have a laravel application which allows users to sign up and add all their workshops, each of the users can add members of their team and once checked the team member is verified.

When a visitor to my application views a category of workshops at the moment gets displayed all workshops in that category, I now want to add an additional feature which allows the visitor to filter the workshops in that category to only show verified workshops.

I have a the following tables

Users Companies Team Members Workshops Categories

I've created all the relationship tables and it all works fine, I just can't apply the filter.

For example when a visitor loads the following url, they shown workshops in that category:

http://ift.tt/29ce1GF

Heres the query I've wrote which should return only verified workshops in the category visited.

$verified = Req::get('verified');
        $preferred = Req::get('preferred');

        $category = Workshopcategory::where('slug',$id)->first();  

        if($verified == 'true'){
            return Workshop::whereHas('people', function ($query) {
                $query->where('verified', '=', true);
            })->where('categories',function ($query) use ($category) {
                $query->where('type_id','=', $category->id);
            })->get();
        };

        return view('site/category',compact('category'));

usually on the category without the filter I would use a foreach on the category variable as I have relationship defined but that doesn't contain the verified workshops. For testing if the url had the GET variable verified then I return the query above.

error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories' in 'where clause' (SQL: select * from `workshops` where (select count(*) from `team_members` where `team_members`.`company_id` = `workshops`.`comp_id` and `verified` = 1) >= 1 and `categories` = (select * where `type_id` = 1))



via Chebli Mohamed

vendredi 1 juillet 2016

Session doesn't persist in laravel 5.1

Here's my AuthController@authentication

Session::put('active_user','USER_INFO');
Session::save();

When I am trying to access session in middleware Authenticate.php

Log::info(Session::get('active_user'));

i got nothing.

I used

Illuminate\Support\Facades\Session

Here's my route.php

Route::post('/login','AuthController@authenticate');

Thanks in advance.



via Chebli Mohamed

Select query not working on Server: Laravel 5.2

Enumeration

class RoleListKeyEnum {
    const Role_List_Page_Title = 1;
}

My code is below

$Translation_Dictionary->where('KeyID', KeyEnum::Role_List_Page_Title)->first()

Above Code works perfectly on localhost and gives a record.

same code does not work on server but surprisingly work if I write below code.

$Translation_Dictionary->where('KeyID', strval(KeyEnum::Role_List_Page_Title))->first()

KeyID is integer in database

Can somebody tell why do I need to convert it into String to get the results on server?



via Chebli Mohamed

Relationships and querying related models

I am trying to work out if I have done something correctly. I have a Department Model. A Department can have many DepartmentObjectives. I have also set up the inverse. So this relationship is fine.

I then have a User Model. A User can have many User Objectives, this is set up fine. In my user_objectives table however, there is a link to a department Objective

$table->integer('department_objectives_id')->unsigned()->default(0);
$table->foreign('department_objectives_id')->references('id')->on('department_objectives')->onDelete('cascade');

So a user objective is linked to a department objective. Is this something I need to specify within my models? So should my UserObjectives model have

class UserObjectives extends Model
{
    use SoftDeletes;

    protected $table = 'user_objectives';
    protected $guarded = [];

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

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

For some reason it seems a bit strange doing this. Anyways, when I create a user objective currently, a department objective is selected and I store the id to the department objective. So within my view I can do something like this



And that will display the id of the department objective it is related too. How can I get the name of the department objective?

Any adivce appreciated

Thanks



via Chebli Mohamed

Laravel restrict input field for time index

How can I restrict the user in Laravel to write only a time index in an input field.

E.g.

01:15:00

I am using Laravel 5.1



via Chebli Mohamed