polarcubs

Experience

74,360

4 Best Reply Awards

  • Member Since 2 Years Ago
  • 605 Lessons Completed
  • 19 Favorites

20th October, 2017

polarcubs started a new conversation Given Table Name, Get The Associated Model • 1 month ago

Is there an easy way where given the string 'users' (or any other string), returns the Model associated with that table name?

Something like model_from_table_name('products') and it returns App\Product

13th October, 2017

polarcubs left a reply on What's The Use Of Route::domain Or Route::group(['domain' => 'xyz.com']) • 1 month ago

Yep read that before I post here. It wasn't clear enough to me.

polarcubs started a new conversation What's The Use Of Route::domain Or Route::group(['domain' => 'xyz.com']) • 1 month ago

What's the use of Route::domain or Route::group(['domain' => 'xyz.com'])?

A code base I inherited uses it in their routes file all over the place.

The official documentation doesn't explain much.

8th October, 2017

polarcubs left a reply on Joining 2 Tables With BelongsToMany Where 1 Table Field Need Some Str_replace • 1 month ago

Sadly I'm not allowed to alter the table to add or any fields. nor do str_replace on \40 to @

What is \27 I'm not sure too.

polarcubs started a new conversation Joining 2 Tables With BelongsToMany Where 1 Table Field Need Some Str_replace • 1 month ago

Table 1 username field is like 'hooray\40welcome.com'

Table 2 username field is like '[email protected]'

using belongs to many or table joins give me problem because obviously hooray\40welcome.com & [email protected] don't matches. How do I do str_replace on an sql join/belongs To many?

for belongsTo or hasOne, I can avoid mitigate the issue with setBindings(). But not this.

7th October, 2017

polarcubs left a reply on Eloquent Relationship And GetPrimaryKeyAttribute Conflict. • 1 month ago

Hey guys this is the cleanest solution I found so far! I will pick this as the answer unless someone find a better way.

return $this->belongsTo(User::class, 'username', 'username')->setBindings(['right-format-username'])

or 

return $this->HasOne(Phone::class, 'username', 'username')->setBindings(['right-format-username'])

However I can't get it to work for belongsToMany or morphToMany yet. $user->items() work fine.

But $item->users() do not work as it attempts to join the tables and the emails format don't match.

4th October, 2017

polarcubs started a new conversation What Exactly Does SetRelation Do? Examples? • 1 month ago

What exactly does setRelation do? Examples?

3rd October, 2017

polarcubs left a reply on Eloquent Relationship And GetPrimaryKeyAttribute Conflict. • 1 month ago

I wouldn't call him a lost cause, he came from the academia where he is previously a pretty well-known security researcher at an ivy league university. So in terms of academic credentials, he definitely beat me hands down as I am just a fresh graduate.

I would just say he likes playing it safe and I hope he never visits here!

polarcubs left a reply on Eloquent Relationship And GetPrimaryKeyAttribute Conflict. • 1 month ago

By why only numbers as username I mean you 36864 (Your laracasts username)

polarcubs left a reply on Eloquent Relationship And GetPrimaryKeyAttribute Conflict. • 1 month ago

@36864. I'm a month into the job now, did not succeed in convincing. My best bet for now I guess would be

function phone() {
    return Phone::where('username', 'right-format-string');
}

// do this

$user->phone()->first();

I'm not even allowed do a local dump of the database & it's tables actually. It is a US medical company that has to comply with HIPPA regulations in regards to personal health information (PHI). I don't understand it well enough yet despite a short course but I guess that means I must have no trace of patient health information on my computer (I'm a remote developer for them).

There is a staging posgresql database, probably 1 month older than the production 1. But also used by all the other softwares and websites of the company.

what's special about utf8mb4_general_ci and why only numbers as username? Just curious out of the blue.

polarcubs left a reply on Eloquent Relationship And GetPrimaryKeyAttribute Conflict. • 1 month ago

@sutherland I'm not allowed by my manager to add an id field to existing tables either.

polarcubs left a reply on Eloquent Relationship And GetPrimaryKeyAttribute Conflict. • 1 month ago

Hi @36864 I updated my post to explain more in details

Basically for the newer tables, username is stored as proper emails e.g. ([email protected])

However in the older tables username is stored as 'me\40hooray.com'

If I don't mutate, I can't do relationships with newer models. If I mutate I can't do relationships with older models. The best I came out with so far is

Laravel should have used $this->attributes['username'] internally.

My best try so far is to return Model::where('username', ...) where I do str_replace on @ or \40 depending on the table stores username in the old or new way. But that isn't that ideal. I can't do $user->phone, when I call $user->phone()->get(), I get a Eloquent Collection

polarcubs started a new conversation Eloquent Relationship And GetPrimaryKeyAttribute Conflict. • 1 month ago

Hi,

Currently in the legacly project I inherited username is the primary key

The username need some formatting when it is shown to user so naturally I did this

public function getUsernameAttribute() {

    return 'formatted-username-here'
}

However at the same time I am also writing Eloquent relationship methods

public function phone() {
    return $this->hasOne(Phone::class, 'username');

}

Everything looks good except that when I run $user->phone, I get null everytime

So I tried the following

$user->phone()->toSql(); // Looks good


// returns an array with the formatted string instead of the raw one!
$user->phone()->getBindings(); 

How do I fix this? Don't suggest me to remove getUsernameAttribute() and write a getFormattedUsernameAttribute() instead. I have my reasons not to.

30th September, 2017

polarcubs left a reply on Redis Sentinel In Laravel, NodeSetName, RedisConfigName, Back Off Strategy & Masters.etc Config? • 1 month ago

@cyrossignol Ah 1 more. If I use your package, do I need to comment out Laravel own Redis Service Provider and Facade?

For local development, I don't use sentinel. Only for staging and production use sentinel.

29th September, 2017

polarcubs started a new conversation How Do I Override Where() Method For A Particular Model? • 1 month ago

How do I override where() method for a particular model?

28th September, 2017

polarcubs started a new conversation Unable To Use $this->authorize In Controller Constructor • 1 month ago

Unable to use $this->authorize in controller constructor but able to use it in non constructor controller methods it seems. I'm on Laravel 5.5.

Any help on this?

26th September, 2017

polarcubs started a new conversation Redis::get Returns FALSE Or Null When Key Not Found? • 1 month ago

Some place tell me it returns FALSE when a key is not found, some place tells me it returns null. Which is correct?

I'm on Laravel 5.2 but fine with answers for later versions too.

16th September, 2017

polarcubs left a reply on How To Validate JSON Input Using Requests? • 2 months ago

Hi some questions. Do I still need to add this JsonApiMiddleware in Laravel 5.5?

Should I add an array cast or not as suggested by @zainescu ?

I'm a bit worried $request->getContent() might returns me an object or does json_decode always return an array?

15th September, 2017

polarcubs left a reply on Is It Possible To Define Eloquent Relations Where Table A Is In A Different Schema From Table B? • 2 months ago

I did that already, but can I join them given they are in different Schemas?

polarcubs started a new conversation Is It Possible To Define Eloquent Relations Where Table A Is In A Different Schema From Table B? • 2 months ago

Is it possible to define Eloquent relations where table A is in a different Schema from table B?

Using PostgreSQL. Same database but table A is in a different Schema from table B. I'm new to postgreSQL too. I see Schema as a sub database.

14th September, 2017

polarcubs started a new conversation InvalidArgumentException With Message 'Trailing Data' For A Date Field • 2 months ago

Hi for some reason when I try to access an existing database table created_at field I keep getting a InvalidArgumentException with message 'Trailing data' error.

The value of created_at is something like this:

2015-03-12 09:25:42.383103

How do I fix it?

In my models I had $dates array defined. in $casts I defined created_at as a datetime field. I commented both out but I still get the same error. It's a postgres database. I don't have the rights to modify the database table only the code.

I searched Github and it appear a few people has filed this issue with Postgres & laravel, however @TaylorOtwell closed each of them. Does anybody know of a fix I can apply?

polarcubs started a new conversation Eloquent Relationships Where Foreign Key Are Same Bug Also Different • 2 months ago

Well inherited a codebase. It uses email as PK for the users table. However the @ symbol is stored as \40 and some other character for something else

There are other tables, but in the other tables, when referring to the user, it is the correct email unicode style say [email protected]

How do I define eloquent relationship and join them? I can't modify any of the tables as the iOS app, Andriod App and other stuffs worked on by other developers all uses that

13th September, 2017

polarcubs started a new conversation Attribute Casting Question When Value In Db Is Null • 2 months ago

in my $casts, I set a field to => 'string', however for some rows it had null values. When I retrieve it, will be be null or an empty string? same for those I had cast to integer.etc

$casts = [

    'quantity' => 'integer'
    ...

];

12th September, 2017

polarcubs left a reply on Redis Sentinel In Laravel, NodeSetName, RedisConfigName, Back Off Strategy & Masters.etc Config? • 2 months ago

Ah thanks for the help I set 'connection' to the respective different values such that none refer to 'default now. Yet I get this error

The Redis Sentinel connection [default] is not defined.

Is it a must to define a default value? Cause in queue.php, session.php, cache.php, broadcasting.php my connection value is not 'default' but a value like 'production', 'staging' as the old settings refer to.

polarcubs left a reply on Redis Sentinel In Laravel, NodeSetName, RedisConfigName, Back Off Strategy & Masters.etc Config? • 2 months ago

Ah! okay

It seems the code base config is more troublesome than this.

different REDIS_HOST, REDIS_PORT, REDIS_SENTINEL_SERVICE, database values are grabbed dynamically from somewhere else depending on if it's production, staging or local that I have no access to in database.php rather than from the local .env file

So I'm going to look at what is prescribed in your database.php file section to figure things out

Your docs say the following are handled

Redis::get('key');
Cache::get('key');
Session::get('key');
Queue::push(new Job());

However in the codebase more methods such as set, expire, del are used. Does it automatically map over as well?

Do I need a spacing between hosts? sentinel1.example.com, sentinel2.example.com?

11th September, 2017

polarcubs left a reply on Redis Sentinel In Laravel, NodeSetName, RedisConfigName, Back Off Strategy & Masters.etc Config? • 2 months ago

Sure I will just switch to yours then. I'm not familiar with redis beyond using it as a queue and simple cache. so a guide as for how to map each of the option to yours would be great. I am going to look at your docs now.

9th September, 2017

polarcubs started a new conversation Redis Sentinel In Laravel, NodeSetName, Back Off Strategym Masters.etc Config? • 2 months ago

Hi guys,

Recently I inherited a Laravel 5.2 codebase. It utilises Redis Sentinel with itryit/laravel-ps-redis (https://github.com/iTryIt/laravel-PSRedis) which isn't supported in Laravel back then. However a quick google search showed that Redis Sentinel support is added this year to Laravel. Probably for Laravel 5.4

https://github.com/laravel/framework/pull/18850

Now I'm in the process of upgrading it to 5.3 and hopefully 5.4/5.5

I looked at the config settings for itryit/laravel-ps-redis and Laravel 5.4 and couldn't exactly map out which value go where. Any help would be appreciated. Especially I don't see nodeSetName, cluster (I assume this fall under clusters->default),

Example itryit/laravel-ps-redis Config

    /** redisConfigName config is supported since version 2.2 */
    'redisConfigName' => 'redis', // your redis setting key name, 'redis' for default, this would be compatible with past versions

    'redis' => [

        /** the name of the redis node set */
        'nodeSetName' => 'your-sentinel-node-set-name',

        'cluster' => false,

        /** database config is supported since version 2.1 */
        'database' => 0, // redis database choice

        /** Array of sentinels */
        'masters' => [
            [
                'host' => 'sentinel-instance.domain.com',
                'port' => '26379',
            ],
            [
                'host' => 'sentinel-instance.domain.com',
                'port' => '26379',
            ]
        ],
    
        /** how long to wait and try again if we fail to connect to master */
        'backoff-strategy' => [
            'max-attempts' => 10, // the maximum-number of attempt possible to find master
            'wait-time' => 500,   // miliseconds to wait for the next attempt
            'increment' => 1.5, // multiplier used to increment the back off time on each try
        ]
    ];  

Example Laravel 5.4 Sentinel Config that I am trying to map to

return [
   // ...
    'redis' => [
        'client' => 'predis',
        'sentinel' => [
            'tcp://10.24.5.136:26379?timeout=0.100',
            'tcp://10.24.5.137:26379?timeout=0.100',
            'tcp://10.24.5.138:26379?timeout=0.100',
            'options' => [
                'replication' => 'sentinel',
                'service' => env('REDIS_SENTINEL_SERVICE', 'mymaster'),
                'parameters' => [
                    'password' => env('REDIS_PASSWORD', null),
                    'database' => 0,
                ],
            ],
        ],
    ],
];

Any help would be great!

7th September, 2017

polarcubs started a new conversation Is There A Method I Could Call To Get A List Of All Defined Gate Strings I Defined? • 2 months ago

Is there a method I could call to get a list of all defined Gate strings (abilities) I defined?

Example:

Gate::define('update-post', ...); Gate::define('delete-account', ...);

Calling that method could return me something like ['update-post', delete-account']

29th June, 2017

polarcubs left a reply on Collect.js: Use Laravel Collections API In JavaScript. • 4 months ago

How is it performance wise as compared to lodash

28th June, 2017

polarcubs left a reply on Laravel Training • 4 months ago

Looks like you are getting more of the hang of Laravel now. Jeffery videos are great in my opinion but they may not be for everyone.

When I tried introduce Laracasts to my school mates as a learning resource, they struggled with it but when they watched pluarlsight laracasts videos, it clicked much easier for them.

Not to say Jeffery is bad (he is excellent for many of us and I paid), just that if you find a resource that doesn't suit you, feel free to seek out other resources till there is something that click it for you.

polarcubs left a reply on Laracast Subscription • 4 months ago

That entitles your supervisor to a yearly subscription but it doesn't entitle you or your colleagues to a subscription. As that would be considered account sharing strictly speaking that is.

Still I know of many SAAS/content creators/founders being privately fine with users sharing their account with their family but limit it beyond that.

So you may have to ask @JeffreyWay on his private stand on this.

26th June, 2017

polarcubs left a reply on Restricting 2FA Only For Users On Paid Plans • 4 months ago

In my country, hardly anyone use an auth app. They rather receive an SMS or email and type the code in. That's what I know.

24th June, 2017

polarcubs started a new conversation A Private Area For Laravel Spark Internals Discussions • 5 months ago

Hi @TaylorOtwell and @JeffreyWay

Sometimes I have questions to ask about the internals of Laravel Spark to better understand its internals.

However as Laravel Spark is a paid product, I hesitate to copy and paste code I see in the spark folder publicly in the forum. Raising it up as a github issue in laravel/spark doesn't feel right either as it isn't a bug.

So I would like to suggest a private Channel where we can do this more freely. Only users who have verified that they purchased Laravel Spark would be able to access.

23rd June, 2017

polarcubs left a reply on Restricting 2FA Only For Users On Paid Plans • 5 months ago

Well I'm planning a donationware app, pay what you want subscription model. Lowest is free. Followed by $1.etc

All users get everything except for features that might cause me money like SMS for 2FA.

For hosting I cover the cost myself of course.

Still pretty new to 2FA stuffs was only a consumer so far.

polarcubs left a reply on Restricting 2FA Only For Users On Paid Plans • 5 months ago

If I'm not wrong Authy sends an SMS if the user does not have the authenticator app.

I think most people wouldn't bother with downloading with an authenticator app.

polarcubs left a reply on Restricting 2FA Only For Users On Paid Plans • 5 months ago

Wouldn't sending SMS incur some costs?

22nd June, 2017

polarcubs started a new conversation Restricting 2FA Only For Users On Paid Plans • 5 months ago

Well I think 2FA is going to incur a little costs so I would like that feature to be only for paid monthly/yearly subscribers. What are the steps I need to take?

12th April, 2017

polarcubs started a new conversation How Do You Get Homestead And Spark To Work Well Together? • 7 months ago

How do you get Homestead and Spark to work well together?

Seem to be lacking good instructions on this

7th April, 2017

polarcubs started a new conversation Anyway To Get Laravel Collections To Search With Binary Search? • 7 months ago

Anyway to get Laravel Collections to search with binary search?

Or are there any package for me to do so

I was reading a huge text file with words sorted in ascending order.

I converted it to an array and then collection. search() works fine but I think it is linear

6th April, 2017

polarcubs left a reply on How Do I Return A Single Computed Value From A Collection? • 7 months ago

Hmm I used ->each but store the result in a external variable and return false. Yours look good too though I have yet to test. But does it perform early exit?

filter sound like it will go through all records than to leave once it is found

polarcubs left a reply on How Do I Return A Single Computed Value From A Collection? • 7 months ago

@tykus reduce take produce a single value from all the values in the array

For me I just find the right value, do a bit of computation on it and return out from the function

I know my code doesn't reveal its purpose. It's for an job interview question so I don't feel appropriate pasting it verbatim (I have submitted my code to the interview though)

So let me think of another similar example

polarcubs left a reply on How Do I Return A Single Computed Value From A Collection? • 7 months ago

I want to use collections and avoid loop that why I ask the question

polarcubs left a reply on How Do I Return A Single Computed Value From A Collection? • 7 months ago

Hi @starmatt but I only want to return 1 value. Map gives back 1 value for each item in the array.

polarcubs started a new conversation How Do I Return A Single Computed Value From A Collection? • 7 months ago

I guess my title is bad so help me suggest better ones. Basically I have code that look like this


        foreach ($this->dictionary as $array) {

            $itemKey = array_search($item, $array);

            if ($itemKey !=== FALSE) {
                return $itemKey * 12345 // Some Computed value
            }
        }

        return 888;

I decide to turn it into a collection based code. But I can't figure out which collection functions to use. I thought of reduce but it doesn't sound right. Any tips?

4th April, 2017

polarcubs started a new conversation Is There Anything Like Java Streams In PHP That I Can Use With Laravel Collections? • 7 months ago

Well I'm parsing a huge text file and doing filtering before returning result, so loading it all into memory may not be a good option.

I know in Java I can do something like a Stream then filter.etc

In Laravel is there something like this? Great if I could use it with laravel collections

31st October, 2016

polarcubs left a reply on Laravel /passport And Postman Gets All The Time ⌚ Unauthorised • 1 year ago

Me too! all the online solutions I read is telling me to switch to Nginx but I want to fix this Authorization header issue in Passport with Apache!

29th October, 2016

polarcubs started a new conversation How To Force HTTP/1.1 Over HTTPS On Nginx • 1 year ago

Hi,

Recently I am trying to conduct an experiment to compare the differences between http1 and http2, however, I faced the following issues.

I enabled https on both sites and I noticed that just by enabling ssl and serve my site over https with nginx, http2 is automatically enabled. Which is not what I want.

I want 1 of the site to be served over https but on HTTP/1.1 not HTTP/2

Is there any way to do that? Thank you

My server config is shown below

server {
    listen 443 ssl; # HTTP2 is used, how do I disable the use of HTTP2 !
 
    server_name mysite.ip-address.nip.io;

    root /home/myuser/myapp.com/http1site;
    index index.html index.htm;

    ssl_certificate /etc/ssl/nip.io/nip.io.crt;
    ssl_certificate_key /etc/ssl/nip.io/nip.io.key;

    charset utf-8;

    location / {
        try_files $uri $uri/ =404;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt { access_log off; log_not_found off; }

    include h5bp/basic.conf;
}

polarcubs left a reply on How Do Remove Nodejs 7 Ppa And Install Nodejs 6? • 1 year ago

@willvincent I still need to know how to remove node7 ppa and node7 .etc at least.

polarcubs started a new conversation How Do Remove Nodejs 7 Ppa And Install Nodejs 6? • 1 year ago

Hi,

Recently I followed instructions at the following site to download and install nodejs 7

https://github.com/nodesource/distributions

curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
sudo apt-get install -y nodejs
...

However I encountered difficulties later when some of the node packages I needed doesn't work on nodejs 7

But I'm not sure how to remove the ppa for nodejs 7 and install nodejs 6 instead.

Any help would be appreciated.

My server is on digitalocean running Ubuntu.

28th October, 2016

polarcubs started a new conversation Passport Password Grant Issue, Unauthenticated Despite Passing Token • 1 year ago

Hi,

I'm trying to do Oauth password grant here and here are the steps I did and issues faced.

  1. First I used postman to grab my token

POST: http://my-app.dev/oauth/token

And I get a response back looking like this

{
  "token_type": "Bearer",
  "expires_in": -1477709422,
  "access_token": "shortened-access-token",
  "refresh_token": "shortened_refresh_token"
}

Everything looks fine so far, but when I proceed to access 1 of my protected routes

Route::group(['middleware' => ['auth:api']], function () {
    Route::get('/teams', 'Api\[email protected]'); // This 1
}
...

I got the following error

Illuminate\Auth\AuthenticationException Unauthenticated.

For extra information, I did pass in Headers 'Accept application/json' and Authorization Bearer token_here

What did I do wrong?

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.