mardi 23 février 2016

laravel eloquent peform wherehas

I'm trying to build a filtersystem on my company's page. I have a page that loads the company's, but now the query excutes on page load and loads the values to search for or sort by. Now is my question how do I execute the wherehas on form submit on the same page? This is what I have for now.

$companys = Company::wherehas('reviews', function($query) use($Rstars){
            $query->where('stars', '=', $Rstars);
        })->orderBy('created_at', $request->cdate)->paginate(15);



via Chebli Mohamed

How to run a method of a class as a cron task in laravel 5.1

Look I have a class that looks like this, i want to cache some info every day in a cron job with this method cacheTopFilters in laravel 5.1

   <?php
namespace namescape/of/the/class;

class FilterTypeCacheService extends BaseService implements IFilterTypeCacheService
{

private $searchFilterService;
private $filterCacheHandler;

function __construct(SearchFilterService $searchFilterService, IFilterTypeCacheHandler $filterCacheHandler){
    $this->searchFilterService = $searchFilterService;
    $this->filterCacheHandler = $filterCacheHandler;
}

public function cacheTopFilters($type,$keyValuePair,$limit){
    $filters = $this->searchFilterService->getAllFilters($type,$keyValuePair);
    $this->filterCacheHandler->deleteFiltersBulkFromCache();
    $this->filterCacheHandler->SaveFiltersBulk($filters,$type);
}

public function getTopFilters(){
    $topFilters = $this->filterCacheHandler->getCachedTopFilters();
    return $topFilters;
}
}

As they have dependency injection how can i accomplished to called that method on the app/console/kernel on the schedule method?



via Chebli Mohamed

Laravel 5 - Issue with design and data in edit page

I am having issues with one of my edit pages, and I am not too sure if it is down to my database design. I have set up the following JSFiddle which demonstrates my create form

Now my first schema captures the simple information from that page, basically just the value of the radio button choice and the date input.

Schema::create('campaign_creatives', function(Blueprint $table)
{
    $table->increments('id');
    $table->string('templateOptions')->default('')->nullable();
    $table->date('arrival')->nullable();
    $table->timestamps();
});

Now if you select a number from one of the select boxes, you will see that number of text inputs appear. It is the data within this I am interested in. Additionally, if you select the Dynamic radio button, additional inputs appear. Furthermore, if you select Other, a text area appears to provide further details. SO I wanted a way to capture all this information, and I created the following table

Schema::create('campaign_creatives_data', function(Blueprint $table)
{
    $table->increments('id');
    $table->string('name')->default('')->nullable();
    $table->string('label')->default('')->nullable();
    $table->longText('value')->default('')->nullable();
    $table->integer('campaignCreativesId')->unsigned()->default(0);
    $table->foreign('campaignCreativesId')->references('id')->on('campaign_creatives')->onDelete('cascade');
    $table->timestamps();
});

The name would represent the thing I am capturing, while the label and value represents the input label and value. After all this, when I save data, it looks a bit like the following

campaign_creatives
+----+--------------+-----------------+------------+---------------------+---------------------+
| id | campaignType | creativeArrival | campaignId | created_at          | updated_at          |
+----+--------------+-----------------+------------+---------------------+---------------------+
| 14 | Dynamic      | 2016-02-25      |          2 | 2016-02-23 15:56:43 | 2016-02-23 15:56:43 |
+----+--------------+-----------------+------------+---------------------+---------------------+

campaign_creatives_data
+----+----------------+-------------------+--------------+---------------------+---------------------+---------------------+
| id | name           | label             | value        | campaignCreativesId | created_at          | updated_at          |
+----+----------------+-------------------+--------------+---------------------+---------------------+---------------------+
| 62 | creativeOption | Other             | dfsdfsdfsdf  |                  14 | 2016-02-23 16:00:01 | 2016-02-23 16:00:01 |
| 60 | creativeOption | checkboxSelection | Pizza        |                  14 | 2016-02-23 16:00:01 | 2016-02-23 16:00:01 |
| 61 | creativeOption | checkboxSelection | Lemondade    |                  14 | 2016-02-23 16:00:01 | 2016-02-23 16:00:01 |
| 59 | creativeNumber | Food2             |              |                  14 | 2016-02-23 16:00:01 | 2016-02-23 16:00:01 |
| 57 | creativeNumber | Drink2            | Some input   |                  14 | 2016-02-23 16:00:01 | 2016-02-23 16:00:01 |
| 58 | creativeNumber | Food1             | Some input   |                  14 | 2016-02-23 16:00:01 | 2016-02-23 16:00:01 |
| 56 | creativeNumber | Drink1            | Some input   |                  14 | 2016-02-23 16:00:01 | 2016-02-23 16:00:01 |
+----+----------------+-------------------+--------------+---------------------+---------------------+---------------------+

creativeOption represents the checkboxes, creativeNumber represents the data relating to Number of Choices. So to produce the above in the FIddle, I would choose 2 for Food and Drink and in the text boxes that appear enter Some input (apart from one which is left empty). I would choose Dynamic and select the Pizza, Lemonade and Other checkboxes. In the textarea for the Other checkbox, I entered dfsdfsdfsdf (so for the other checkbox, I am interested in the textbox data rather than the checkbox value).

In regards to my Models, a CampaignCreatives can have many CampaignCreativesData. So everything for the creating side of things works great. The issue comes with the edit page, seeing that a lot of the display is dynamic. I pass the view this

$campaignCreative = CampaignCreatives::where('campaignId', '=', $campaign->id)->first();

I use first because there can only be one CampaignCreatives. Within my view, I now have access to all that data displayed above. Here is an example. On my edit page, I have the following which represents the Number of Options select boxes.

<div class="form-group">
    <div class="row">
        <div class="col-md-12">
            <h3>Number of Options</h3>
            <div class="col-md-3 noPadding">
                {!! Form::label('cFood', 'Food:', array('class' => '')) !!}
                {!! Form::select('cFood', ['0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7'], null, ['class' => 'cSelectType']) !!}
            </div>
            <div class="col-md-3">
                {!! Form::label('cDrink', 'Drink:', array('class' => '')) !!}
                {!! Form::select('cDrink', ['0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7'], null, ['class' => 'cSelectType']) !!}
            </div>
            <div class="col-md-3">
                {!! Form::label('cOther', 'Other:', array('class' => '')) !!}
                {!! Form::select('cOther', ['0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7'], null, ['class' => 'cSelectType']) !!}
            </div>
        </div>
    </div>
</div>

From the above data, I know that there are 4 creativeNumber data, 2 for Food and 2 for Drink. Therefore, I need the text inputs displayed for these with their value. How would I go about doing something like this?

I know this is a lot of information, I would be so greatful if someone could guide me in the correct direction.

Many thanks



via Chebli Mohamed

Creating private channel for user on login with pusher

I am attempting to implement pusher into a laravel aplication. Specifically I want to create a private channel when the user logs in.

I have a public channel "login" that has an event called "login-event" that gets triggered every time someone logs in.

The issue I am having is that the trigger that is supposed to create and subscribe to the private channel only fires for the users already logged in. not for the user that just logged in, which is the only user I actually need it to run for.

Pusher.js

$(function () {

  var pusher = new Pusher('XXXXXXXXXX');
  var channel = pusher.subscribe('login-channel');

  channel.bind('login-event', function(data) {


 // NOT RUNNING FOR USER WHO JUST LOGGED IN BUT RUNS FOR EVERYONE ELSE

  var user = data.content.userID;

  var newpusher = new Pusher('XXXXXXXXXXX', {
    userid: $('meta[name="user"]').attr('content'),
    authEndpoint: '/pusher/auth',
    auth: {
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    }
});

  var newchannel = newpusher.subscribe('private-channel-for-'+user+'');

  console.log('Setting up a channel for user '+user+'.');

});

I need to "login-event' in the code above to also run for the user that just logged in.

I have looked over the docs about as much as I can take, if the answer is clearly in there feel free to provide a link but it would be great if I could get a suggestion in code.



via Chebli Mohamed

Using Structured Page Fragments and Laravel, How do I handle views?

I want to use structured page fragments in this project that I'm working on. I am developing in the Laravel 5.1 framework.

I'm still very new to SPF, but I seem to have a grasp of it at a basic level, but I'm not sure to handle my views.

When I return content to a view, should I just form an array in my controller containing all of my data, and just return that array as such:

        $obj = [
        'title' => 'Title',
        'head' => '<style>CSS Text</style>',
        'body' => ['something' => "HTML Text..."],
        'foot' => '<h1>Footer</h1>'
    ];
return $obj;

Rather than returning a view? Or is there some way to store the data in a blade file, and return that? Do I just disregard views entirely when it comes to returning fragments? Can page fragments not be stored in view files?



via Chebli Mohamed

Laravel 5 - relationships between models

I have a database structure as follows.

campaign

id    | name         | ...
----------------------
5     | something    | ...
----------------------

campaign_creatives

id    | type         | campaignId
---------------------------------
1     | something    | 5
---------------------------------

campaign_creatives_data

id | name       | campaignCreativesId
--------------------------------------------
1  | something  | 1
--------------------------------------------
2  | something  | 1
--------------------------------------------
3  | something  | 1
--------------------------------------------

Within my Campaign Model, I have

public function campaignCreatives()
{
    return $this->hasOne('App\CampaignCreatives', 'campaignId');
}

Within CampaignCreatives I have

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

public function campaignCreativesData()
{
    return $this->hasMany('App\CampaignCreativesData', 'campaignCreativesId');
}

And within CampaignCreativesData

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

The theory behind this is a Campaign can have One CampaignCreatives. A CampaignCreatives can have one or more CampaignCreativesData.

I am not too sure if my Models are correct for this? I have a feeling it is not. Reason I say this is that within one of my views, if I do

{{ dd($campaignCreative) }}

I can see the information relating to the campaignCreative. However, if I do

{{ dd($campaignCreative->campaignCreativesData) }}

I get the warning

Undefined property: Illuminate\Database\Eloquent\Collection::$campaignCreativesData

Are my relationships set up appropriately, or am I doing something wrong with the foreign keys?

Thanks



via Chebli Mohamed

Catch mysql *warning* (not exception) while using Laravel DB Builder?

I have a BIGINT field, and for testing I maxxed out the field and then tried to add even more. The following code returns successful without throwing an \Exception, but it is throwing a warning in an sql query and, obviously, not updating the field. How can I catch a warning and return the warning message that the field is at its maximum? (As you can see I have tried both a DB::transaction and a try/catch without success).

        try {
            DB::transaction(function () use ($data, $quantity) {
                $query = 'INSERT INTO item_user (user_id, item_id, quantity) VALUES '.substr($data,0,-2).' ON DUPLICATE KEY UPDATE quantity = GREATEST(`quantity` + '.$quantity.',0)';
                DB::statement($query);

                // subquery to delete any rows left with zero
                DB::table('item_user')->where('quantity',0)->delete();
            });

            return redirect()->route('index')
                ->with( ['flash' => ['message' =>"<i class='fa fa-check-square-o fa-1x'></i> Success! Item totals updated.", 'level' =>  "success"] ] );

        } catch (\Exception $e) {

            return redirect()->back()->withErrors( $e->getMessage() )->withInput();
        }

This returns successful on the page but capturing and running the query directly on SQL gets me the warning and number :

Warning Code : 1264
Out of range value for column 'quantity' at row 1

Thanks.



via Chebli Mohamed