burlresearch

burlresearch

Member Since 5 Years Ago

Ottawa

Consultant at https://burlresearch.com

Experience Points 131,790
Experience Level 27

3,210 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 812
Lessons
Completed
Best Reply Awards 112
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

24 Jun
1 day ago

burlresearch left a reply on Where Clause On Nested Relationships In Eloquent

It doesn't really seem to me that this is in fact a 'nested relationship'. Really, you're just doing some sort of modified auth policy.

I think you could achieve what you want with a User Model that looks something like this:

class User extends Authenticatable {
    use Notifiable; 
    protected $fillable = ['name', 'email', 'password',]; 
    protected $hidden = ['password', 'remember_token',]; 
    protected $casts = ['email_verified_at' => 'datetime',];

    public function activities() {
        return $this->belongsToMany(Activity::class, 'user_activity')
            ->withPivot(
                'type',
                'activity_text',
                'activity_url'
            )
            ->withTimestamps();
    }

    public function privacySetting() {
        return $this->hasOne(PrivacySetting::class);
    }

    public function gpaActivity() {
        return $this->privacySetting->gpa
            ? $this->activities()->wherePivot('type', 3)    // gpa <- type 3
            : $this->activities()->wherePivot('type', -1);
    }
}

This makes queries for GPA activity relatively easy, for User.id 2 then: User::find(2)->gpaActivity()->get() and you could write such a method for any of the activity types you like, or maybe consider a scope

18 Jun
1 week ago

burlresearch left a reply on Laravel 5.7 Login Session Expires Right After Redirect But Register Doesn't?

sounds like caching or session settings/conf/driver to me - something change on that front?

17 Jun
1 week ago

burlresearch left a reply on Using Attach With A Model Extending A Model

I see, wasn't sure what your intention was. Yes, what you're talking about makes sense, and should work. Maybe your problem is much simpler that I thought.

Sometimes attach() and sync() are a more fussy about what you're passing in. It may be better if you just pass in the tag ID, rather than the whole model when setting the relationship. Try:

        $image->tags()->attach($tag->id);
13 Jun
1 week ago

burlresearch left a reply on Using Attach With A Model Extending A Model

This is literally the textbook case of a polymorphic relationship.

It should be OK to have image extend File, but you'll need to have them both Taggable. I'd use a Trait for this.

The reason being, exactly as you said. A tag in your example is tied directly to the File Model (and it's IDs). Even though an Image "is-a" File - they occupy 2 different database tables, and thus have uncorrelated ID indexes. This makes the back-reference ambiguous, which databases cannot allow.

12 Jun
1 week ago

burlresearch left a reply on L5.2 Form Request With Comma Separated String Input

Just treat it as a string then. You say you're not getting an array, so don't expect one.

Then I'd maybe build a custom validation rule - one that will explode(...) a string into an array of elements, and check each element as existing in the table2 you're trying to validate.

28 May
4 weeks ago

burlresearch left a reply on Loop Question

NB the range() function includes the boundaries (so range(0,20) yields 21 items) Also, data_get() is very handy - can also take a third argument to use as a default, try this, below: data_get($values, $k, $k)

$values = range('A', 'J');  // collection or array 
foreach (range(1, 20) as $k => $i) {
    echo $k . ' ' . data_get($values, $k) . "\n";
}
24 May
1 month ago

burlresearch left a reply on Help With Nginx & Serving Internal App

If the PHP file is being downloaded, and not rendered, there is chance you are missing the PHP processor, like FPM, try:

$ sudo apt-get install php-fpm 

and you may still have some other dependencies to install if your LEMP server is still incomplete. Hopefully that will help you get on the right path.

If ther server_name still isn't resolving - are you sure you've edited the hosts file on your client machine?

burlresearch left a reply on Help With Nginx & Serving Internal App

try a solitary server config like this:

server {
  listen 80 default_server;
  server_name my_pretty_name.com;
  root /var/www/mySiteDir/public;
  index index.php index.html;
  location / {
    try_files $uri $uri/ /index.php?$query_string;
  }
}

and remove any server block from your /etc/nginx/nginx.conf file. This should do 2 things:

  1. set the default for any IP-only incoming requests
  2. match a specific request for your my_pretty_name.com domain

And, then even if you do have a entry in

/etc/hosts

123.45.67 my_pretty_name.com

It would still proxy the request.

23 May
1 month ago

burlresearch left a reply on Merge Two Arrays Based On Partial String In Key Value

This maybe isn't my best work - but as I understand it, is this what you're looking for:

public function handle() {
    $data1 = collect([
        [
            "CIRCUIT"      => ".LXFP.144374..LB",
            "DESCRIPTION"  => "This is the description",
            "INSTALL_DATE" => "2015-09-25",
        ],
        [
            "CIRCUIT"      => ".LXFP.123456..LB",
            "DESCRIPTION"  => "This is two description",
            "INSTALL_DATE" => "2016-06-26",
        ],
    ]);
    $data2 = collect([
        ["CAT_DESCRIPTION" => "LXFP/144374//LB Slightly different description",],
        ["CAT_DESCRIPTION" => "LXFP/123456//LB description two",],
    ]);

    $grp1 = $data1->groupBy(function ($i) {
        $matches = [];
        preg_match('/\d{6}/', $i['CIRCUIT'], $matches);
        return $matches[0];
    });

    $grp2 = $data2->groupBy(function ($i) {
        $matches = [];
        preg_match('/\d{6}/', $i['CAT_DESCRIPTION'], $matches);
        return $matches[0];
    });

    $grp = $grp1->map(function ($i, $k) use ($grp2) {
        $cd = data_get($grp2, $k . '.0.CAT_DESCRIPTION');
        if (!!$cd) $i = array_merge($i->first(), ['CAT_DESCRIPTION' => $cd]);
        return $i;
    });

    $this->info($grp->toJson(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

yielding,

{
    "144374": {
        "CIRCUIT": ".LXFP.144374..LB",
        "DESCRIPTION": "This is the description",
        "INSTALL_DATE": "2015-09-25",
        "CAT_DESCRIPTION": "LXFP/144374//LB Slightly different description"
    },
    "123456": {
        "CIRCUIT": ".LXFP.123456..LB",
        "DESCRIPTION": "This is two description",
        "INSTALL_DATE": "2016-06-26",
        "CAT_DESCRIPTION": "LXFP/123456//LB description two"
    }
}
20 May
1 month ago

burlresearch left a reply on Make A Hierarchical Structure For Instances Of A Model In Laravel

@russuo this thread was never completed - the OP didn't seem to indicate where he landed with this. I think my point here was that there are many packages to choose from out there that could be of help.

Also, that's it isn't that complicated to create a simple model that relates to itself in order to create a hierarchical data-structure, like a tree, in a single table. Depends on what you need it to do.

If you have a specific question, it might be worth starting your own thread for a new question.

15 May
1 month ago

burlresearch left a reply on Help With Refactoring Collection Methods / Am I Reinventing The Wheel?

I think this is what you're going for:

/**
 * @param \Illuminate\Support\Collection $matrix An M x N matrix
 * @param \Illuminate\Support\Collection $keys An N x 1 array
 * @return array An MxN array with rows keyed by $keys
 */
protected function addMatrixKeys(\Illuminate\Support\Collection $matrix, \Illuminate\Support\Collection $keys): array
{
    return $matrix->map(function ($row) use ($keys) {
        return $keys->combine($row);
    })
        ->toArray();
}

Hopefully this answers your question inline?

11 May
1 month ago

burlresearch left a reply on Something About Jeffery's Twitter

same same

Looks like it's been hacked?!

09 May
1 month ago

burlresearch left a reply on Task Scheduling Timing

Seems that artisan schedule:run will miss jobs unless it's run every minute - so just run it that way in your crontab to be safe.

08 May
1 month ago

burlresearch left a reply on Problems When Applying Migrations In Hosting With Laravel 5.5

looks like you're missing he PDO driver - type this on the command line:

sudo apt install php-mysql

burlresearch left a reply on Why Suffer Error Running Migration Under Vultr Vps

I think you have an error in your .env file, check what you have for DB_HOST, or simply delete that whole line and go with the default.

burlresearch left a reply on Blade Help

Maybe it just needs a little cleanup, easier to understand like this. And, your @case syntax was off:

@php
  $z = 'B';
@endphp

@foreach($sss as $smart)
  @php
    $z++;
  @endphp

  @if( $smart->server_exists
  && ! $smart->is_setup 
  && ! $smart->ready_to_receive_conf 
  && ! $smart->configured
  )
    class {{ $z }} serverexists <br>

  @elseif( $smart->server_exists 
  && $smart->is_setup 
  && ! $smart->ready_to_receive_conf 
  && ! $smart->configured
  )
    class {{ $z }} hascaipy <br>

  @elseif( $smart->server_exists 
  && $smart->is_setup 
  && $smart->ready_to_receive_conf 
  && ! $smart->configured
  )
    class {{ $z }} needsconf <br>

  @elseif( $smart->server_exists 
  && $smart->is_setup 
  && $smart->ready_to_receive_conf 
  && $smart->configured
  )

    @switch($ss->status->id)
      @case(1)
      case1 {{ $z }} running <br>
      @break

      @case(2)
      case2 {{ $z }} notrunning <br>
      @break

      @case(3)
      case3 {{ $z }} stopped <br>
      @break

      @default
      default {{ $z }} configured <br>
    @endswitch

  @else
    class {{ $z }} before <br>
  @endif
@endforeach

burlresearch left a reply on Blade Help

Maybe it just needs a little cleanup, easier to understand like this. And, your @case syntax was off:

@php
  $z = 'B';
@endphp

@foreach($sss as $smart)
  @php
    $z++;
  @endphp

  @if    ($smart->server_exists && ! $smart->is_setup && ! $smart->ready_to_receive_conf && ! $smart->configured)
    class {{ $z }} serverexists <br>

  @elseif($smart->server_exists && $smart->is_setup && ! $smart->ready_to_receive_conf && ! $smart->configured)
    class {{ $z }} hascaipy <br>

  @elseif($smart->server_exists && $smart->is_setup && $smart->ready_to_receive_conf && ! $smart->configured)
    class {{ $z }} needsconf <br>

  @elseif($smart->server_exists && $smart->is_setup && $smart->ready_to_receive_conf && $smart->configured)

    @switch($ss->status->id)
      @case(1)
      case1 {{ $z }} running <br>
      @break

      @case(2)
      case2 {{ $z }} notrunning <br>
      @break

      @case(3)
      case3 {{ $z }} stopped <br>
      @break

      @default
      default {{ $z }} configured <br>
    @endswitch

  @else
    class {{ $z }} before <br>
  @endif
@endforeach

burlresearch left a reply on Blade Help

Maybe it just needs a little cleanup, easier to understand like this. And, your @case syntax was off:

@php $z = 'B'; @endphp
 @foreach($sss as $smart)
        @php $z++;  @endphp


        @if($smart->server_exists == true && $smart->is_setup == false && $smart->ready_to_receive_conf == false && $smart->configured== false)
        class {{ $z }} serverexists <br>
        @elseif($smart->server_exists == true && $smart->is_setup == true && $smart->ready_to_receive_conf == false && $smart->configured== false)
        class {{ $z }} hascaipy <br>
        @elseif($smart->server_exists == true && $smart->is_setup == true && $smart->ready_to_receive_conf == true && $smart->configured== false)
        class {{ $z }} needsconf <br>
        @elseif($smart->server_exists == true && $smart->is_setup == true && $smart->ready_to_receive_conf == true && $smart->configured== true)
            @switch($ss->status->id)
                @case($ss->status->id == 1)
                case1 {{ $z }} running <br>
                @break

                @case($ss->status->id == 2)
                case2 {{ $z }} notrunning <br>
                @break

                @case($ss->status->id == 3)
                case3 {{ $z }} stopped <br>
                @break
                @default
                default {{ $z }} configured <br>
            @endswitch
        @else
        class {{ $z }} before <br>
        @endif

@endforeach

burlresearch left a reply on Laravel Handles User's Concurrent Requests Sequentially

if you want more parallelism in your web-server responses, you could make sure your server is using HTTP/2.

burlresearch left a reply on Doubt With Installation Of Project In Hosting

To find out about composer from command line:

$ which composer.phar
$ which composer
/usr/local/bin/composer    # if installed you should see something like this

composer isn't really part of any core Linux distro, so you may have to install it. If you really want a one-and-done setup, that is what Forge is for:

https://forge.laravel.com/

of course, you'll pay a little for the convenience.

burlresearch left a reply on Merge 2 Collections

You may want to look a little more closely. For $collection->merge():

https://laravel.com/docs/5.8/collections#method-merge

(but that's not what you want here)

And for the relation you want, it's literally the documented example:

https://laravel.com/docs/5.8/eloquent-relationships#one-to-many-inverse

With a minor swap of Model classes.

03 May
1 month ago

burlresearch left a reply on Atomic Database Row Selection

My gut reaction would be to handle the requests by creating a new Job to handle this activity, and Queuing them up.

https://laravel.com/docs/master/queues#creating-jobs

This would serve as:

  1. a lightweight manner to handle the request
  2. serialize the request stream (I would use Redis)
  3. a way to remove the database processing times from the handling chain

Not sure what you're expecting to return from your requests. If you need to respond with something like a Bushel_ID then of course, you can't make the Job's async, but there are work-arounds.

However, using a Queued Job would correct your initial problem of duplication of work.

29 Apr
1 month ago

burlresearch left a reply on Storing Data

You could simplify this a little, I think. I might write it as:

public function store(Request $request) {
    $request->validate([
        'first_name' => 'required|max:255',
        'last_name'  => 'required|max:255',
    ]);

    do {
        $number = mt_rand(1000000000, 9999999999);
    } while (App\Event::whereBarcodeNumber($number)->exists());

    $event = auth()->user()->events()->create([
        'first_name' => $request->first_name,
        'last_name'  => $request->last_name,
        'barcode'    => $number,
    ]);

    return $event;
}

As for the return redirect() - I would probably leave that to the success method of the POST call on your client-side. That's up to you, depending on what you're wanting to do...

18 Apr
2 months ago

burlresearch left a reply on API Integration

OK, Here's a good hint to get you started. I'll recommend you install GuzzleHTTP - you'll need something to make the http request. The instructions are pretty clear, this is what they are indicating you run to make the connection:

    /**
     * Ensure to install GuzzleHTTP for this to work:
     * $ composer require guzzlehttp/guzzle
     */
    public function handle()
    {
        $key = base64_encode('F50368501B084C26A480A7F728E4169E:E72E8F14846445248890038867E3FB03');
        $client = new \GuzzleHttp\Client([
            'headers' => [
                'Authorization' => 'Basic ' . $key,
                'Content-type'  => 'application/json',
            ],
        ]);

        $res = $client->get('https://api.eposnowhq.com/api/v2/product/');

        // An array of the first 200 products...
        $products = json_decode($res->getBody(), true);

        foreach ($products as $index => $product) {
            printf("%03d - [%s] %s\n"
                , $index
                , $product['ProductID']
                , $product['Name']
            );
        }
16 Apr
2 months ago

burlresearch left a reply on Laravel Form Request Custom Error Message For Regex Rule

I wonder if it's not your regex that's not quite right? I think what you have is more permissive than you think, it is testing whether exists in the code, not whether code is entirely that. What if you try this, it may trigger the error you want:

regex:/^[A-Za-z0-9 ]+$/'

burlresearch left a reply on Get Difference Between Two Date Type Column In A Query

@jlrdw I should have been more specific, that I didn't recognize that syntax (with the 3rd arg as date_format). Seems that SQLServer also has a similar function:

https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-2017

burlresearch left a reply on API Integration

Is this a homework assignment or a job interview?

burlresearch left a reply on Get Difference Between Two Date Type Column In A Query

Here is an example of an Eloquent version of what you might be looking for.

It's not clear to me what type of database you're querying, it doesn't look like MySQL syntax, but it also doesn't look like that SQLServer sytax either (but I'm not that familiar with SQLServer...).

No matter, here's an example that works for MySQL, perhaps this will help you:

public function recent() {
    return \DB::table('posts')
        ->selectRaw('*, datediff(created_at, now())')
        ->whereRaw('datediff(created_at, now()) > ?', [-99])
        ->get();
}
09 Apr
2 months ago

burlresearch left a reply on Unique Results

what makes your sub-jobs unique? There must be a property like name or category by which you can tell 2 sub-jobs are different?

01 Apr
2 months ago

burlresearch left a reply on Make A Search Form And Show Result On The Same Page

Your [email protected] function is called via a POST request - so return JSON from it, not a view().

Then you'll be able to see the response from the form submission will contain the data that was matched. This is all done asynchronously in Javascript, so you'll have to have a JS function to parse the response, and push the results onto your page.

30 Mar
2 months ago

burlresearch left a reply on Best Practice To Store And Output Data

Seems you're having some trouble trying to figure out: "what is a User in your context"

When crafting a database - you have to make some decisions about what your data means to you - then you can worry about the best way to store it.

With what you've given - there are some hints you've given. I think the way I like to think about some of your issues. When modelling a database:

  1. When you're talking about 1-1 relationships of tables, why are you making another table. There are good reasons to do this, sometimes. but often any 1-1 relationship of a table element really just represents a property of that element - why not just put that property on the same table? For a user, these are really properties that could easily be stored on the same table {Last Online, Birthdate, Website, Place of residence, Comment}
  2. If a "User" in your system could have multiple options, then I would think that's no longer a property of your user, but a relationship. So, {E-Mail, Skype, Phone} might be candidates for an alternate contact table where a given user could have multiple associated accounts. So maybe you want to break those out.

It's up to you how you model it, but try to keep things simple as possible, and don't be afraid to change them later, if you think your requirements merit a change.

25 Mar
3 months ago

burlresearch left a reply on If Condition Check Value

Reading this now I sound a little angry! Sorry if the tone was off - it was a little late when I posted.

But, that is a little pet-peeve of mine - ask any of my work-mates, LOL. Glad you asked.

burlresearch left a reply on If Condition Check Value

This is a pet-peeve of mine - remember the if statement branches on the value of a conditional - if your intention is to just return the validity of that, then the if statement is completely redundant - just return the condintional itself!

Maybe this is better:

public function paymentstore(Request $request,$id)

  return ($request->get('amount') <= Registration::findOrFail($id)->charges);
}
24 Mar
3 months ago

burlresearch left a reply on Merging Collection With Object Keys

I think you're a little incorrect here. It looks like you're creating probably an API Resource out of your collection, and that would "return" a \Illuminate\Http\Resources\Json\JsonResource.

This is not an array, but can be converted to one. So likely you're looking at the output of a controller function, which is converting your API Resource into an array, which is converted to JSON, and shown to you in a browser?

If you want it converted to a PHP Object, then I suppose you could cast it, but I suspect that's actually what you want.

$sampleRes = new SampleResource($all);
$obj = (object) $sampleRes->toArray();

will give you an object, but maybe you can explain what you are doing - this looks like you are a little confused?

burlresearch left a reply on Setting Up Proper Permissions For Laravel App In Ubuntu

You may reuse an existing group if you like. If ever you were to change webservers (maybe unlikely) then you might want a different group to share file access. If you have a non-standard group, then this migration would be simplified. I have used www-data in the past - sometimes that is convenient. The name of the shared group really doesn't matter.

The umask command option is kind of handy. The point is that when you create a new file (like your log-file you mention) then you will want that to be 'group-writeable'. This way, any other entities in that group would also be able to write that file. Avoiding the issue you mention. If you set the umask of your user to umask 002 then any new files or directories will get the inverse of that, by default.

So by default on unix, a files permission is 664 and with umask *002* then you end up with 664 & 002 = 664, which is group-writeable.

You could put in:

~/.bashrc

umask 002

and every time you login it will be set for you.

23 Mar
3 months ago

burlresearch left a reply on Setting Up Proper Permissions For Laravel App In Ubuntu

There is no right and wrong way to do this, and there will always be alternative solutions - it depends on how really fussy you want to be about system security and all that. Of course it may depend on the client and all sorts of other things, so you have to be a little flexible to other approaches, I always am.

But, since your asking for opinions ... I've setup a lot of servers and this is the approach that I like to use. I think it's reasonably secure (assuming general system security is up to snuff, with regular updates, ufw, controlling open ports and software and user accounts, etc). What I like:

  1. use a non-root account for login
  2. create a new group [say websrv] and set this group as the primary group for both your user account and the webserver account: $ sudo usermod -g websrv nginx
  3. set the umask 0002 for your user account (this means any new files/dirs will be group writeable - this is key)
  4. ensure your project is group writeable: sudo chmod -R ug+rw /var/www/laravel

This way when your webserver (nginx above) or your user writes files into the shared deployment directory, either user will later be able to write, or delete, those files, via the shared group permissions.

You may have to do a little work to make sure that the webserver uses that primary group, IE in the php-fpm config, and in the nginx.conf webserver config (or whatever it is for Apache, if you prefer that).

Maybe there are some security nuts who can criticize this setup, and I wouldn't use the same approach for a Wordpress server, but in terms of long-term facility vs pretty good security + Laravel being security conscious + saving me time and hassle - I find this to be a nice balance. (And have yet to have a server hacked that I've launched, in the last 30 years, so it works for me.)

burlresearch left a reply on HowTo? Create Entity For Users And Editable In Adminpanel?

You can be clever and still use the Artisan generator, if you like:

a make:controller -r -m Item -- Admin\\ItemController

burlresearch left a reply on QUEUES AND JOBS

Sounds like there may be too much context involved to separate the jobs easily - so that might not be right for you.

The Laravel Eventing system could be an option - it's very powerful and may suit what you want better. I've written some tricky SOAP interface systems before that work just this way.

So you could chunk(12) your workload; make the SOAP calls; and dispatch() an async handler depending on what comes back. This would be a nice use of the Queues and Events. Sounds like a job for Redis.

22 Mar
3 months ago

burlresearch left a reply on QUEUES AND JOBS

There is the concept of "Job Chaining" which it sounds like may help you. When you're describing your 'complex job' it sounds as though it's complex because there are several, sequential steps.

You may want to try and create 'simple Jobs' for each step - and then chain those jobs together so the chain forms the complex, and not some single monolith controller / handler.

Sounds like you're definitely on the right path though.

burlresearch left a reply on Retrieve Eloquent Relationships From A Pivot Table While Doing A BelongsToMany

I thought that what you wanted might work too - I gave it a try, but no. Thought that b/c the Pivot is a subclass of Model we might be able to use the relationship directly when we access the ->pivot element, but b/c it acting as the pivot here, and not as the actual relationship, trying to resolve a secondary relation off of the pivot doesn't seem to work.

// from: $ artisan make:model Driver
use Illuminate\Database\Eloquent\Model;

class Driver extends Model
{
    protected $guarded = ['id'];

    public function cars()
    {
        return $this->belongsToMany(Car::class)
            ->withPivot('id', 'rider_type_id');
    }
}

// from: $ artisan make:model --pivot CarDriver
use Illuminate\Database\Eloquent\Relations\Pivot;

class CarDriver extends Pivot
{
    protected $guarded = ['id'];
    public $incrementing = true;

    public function car() { return $this->belongsTo(Car::class); }

    public function driver() { return $this->belongsTo(Driver::class); }

    public function riderType() { return $this->belongsTo(RiderType::class); }
}

So the best I could do was to use the data id's that come via the ->withPivot() call to lookup the RiderType, either directly, or possibly as it relates to your Pivot class. It would be cool if it worked the way you wanted, but it does make sense why this doesn't work, I suppose.

>>> foreach (Driver::find(3)->cars as $c) {
    dump($c->pivot->toJson());
    dump(RiderType::find($c->pivot->rider_type_id)->toJson());
    dump(CarDriver::find($c->pivot->id)->riderType->toJson());
};
[!] Aliasing 'CarDriver' to 'App\CarDriver' for this Tinker session.
"{"driver_id":3,"car_id":4,"id":8,"rider_type_id":2}"
"{"id":2,"type":"esse","created_at":"2019-03-22 06:20:41","updated_at":"2019-03-22 06:20:41"}"
"{"id":2,"type":"esse","created_at":"2019-03-22 06:20:41","updated_at":"2019-03-22 06:20:41"}"
"{"driver_id":3,"car_id":3,"id":9,"rider_type_id":4}"
"{"id":4,"type":"omnis","created_at":"2019-03-22 06:20:41","updated_at":"2019-03-22 06:20:41"}"
"{"id":4,"type":"omnis","created_at":"2019-03-22 06:20:41","updated_at":"2019-03-22 06:20:41"}"

burlresearch left a reply on Select Nearest Cities From Table

I've been playing with this and have confirmed that this raw query works as expected.

$cities = DB::table('articles')
    ->selectRaw('id, name, st_x(location) as lat, st_y(location) as lng, ST_Distance_Sphere(location, POINT(?, ?)) as dist', [$lat, $lng])
    ->having('dist', '<', $distance)
    ->orderBy('dist')
    ->get();

this will return dist in meters, I suppose.

If you want to build it into your Eloquent Model a little more tightly, take a look at this article:

https://laravel.io/forum/working-with-spatial-columns-in-eloquent-model

16 Mar
3 months ago

burlresearch left a reply on Redis

You should be able to find the cache.prefix that your app is using:

/srv/laracasts$ artisan tinker
Psy Shell v0.9.9 (PHP 7.1.26-1+ubuntu16.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> config('cache.prefix')
=> "laracasts_cache"
>>> 

Then I pushed a value into the cache in a blade file:

    @php
        $cval = Cache::remember('welcome', 60, function () { return 'cached value'; });
    @endphp
    <h4> cache: <code> {{ $cval }} </code> </h4>

Then you should be able to find a value in your Redis explorer with the key named by the pattern <cache_prefix>:<key>, and mine from above, was: laracasts_cache:welcome

One thing I did notice, from Redis Desktop Manager, was that the cached values I was storing in my app code were stored in a different Redis Database than the default db0. All my cached values were instead in db1 - so from the command line I had to specify that database in order to see my cached values. Perhaps this is the issue you're running into, also. Tried:

/srv/laracasts$ redis-cli -n 1
127.0.0.1:6379[1]> get laracasts_cache:welcome
"s:12:\"cached value\";"
127.0.0.1:6379[1]> 
15 Mar
3 months ago

burlresearch left a reply on Select Nearest Cities From Table

I'm not sure what you mean by query in eloquent for this - since there is a lot of missing information about your model here, but in terms of a query (assuming MySQL?), you could avoid the [incorrect] geometry calculations by using the builtin function ST_Distance_Sphere with something like:

$results = DB::table('articles')
    ->selectRaw('id, ST_Distance_Sphere(location, POINT(?, ?) ) as distance', [$lat, $lng])
    ->having('distance < ?', [$distance])
    ->get();

I kind of inferred your POINT field was called location and the table name (articles). But maybe this will get you on track?

09 Mar
3 months ago

burlresearch left a reply on Attach() On Custom BelongsToMany-Model

OK, I suppose I agree, you could have a Model and simply set the $table in it to the 'correct' pivot table. I do feel this is misleading, though - since artisan will generate the pivot table for you. I created my test like this:

$ artisan make:model --migration --pivot UserRole

and this does create the create the table accordingly: Schema::create('user_role', function (Blueprint $table)

which leads to my assumption. I now see that the ->using function is only to associate the Model, while the underlying table name still needs to be overridden in the relationship definition: ->belongsToMany('App\User', 'user_role')

So I think, @gvstavnev the answer to you original issue, is thus, you must define the intermediate table name in your belongsToMany declaration:

User.php

    public function folders() {
        return $this
            ->belongsToMany(Folder::class, 'membership') // <-- this is the addition that you need
            ->using(Membership::class);
    }

burlresearch left a reply on Attach() On Custom BelongsToMany-Model

I understand this, but the example provided in the documentation does not work. From the docs, using the non-standard named pivot table App\UserRole (Laravel by convention would expect App\RoleUser), and trying the using->(...) approach from 5.8:

    public function users()
    {
        return $this->belongsToMany('App\User')->using('App\UserRole');
    }

when you attempt to use the relationship:

Psy Shell v0.9.9 (PHP 7.1.26-1+ubuntu16.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> Role::first()->users
Illuminate/Database/QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laracasts_58.role_user' doesn't exist (SQL: select `users`.*, `role_user`.`role_id` as `pivot_role_id`, `role_user`.`user_id` as `pivot_user_id` from `users` inner join `role_user` on `users`.`id` = `role_user`.`user_id` where `role_user`.`role_id` = 1)'

I don't see how this isn't a bug?!

burlresearch left a reply on Attach() On Custom BelongsToMany-Model

No @staudenmeir , the docs are fairly clear about this:

https://laravel.com/docs/5.8/eloquent-relationships#defining-custom-intermediate-table-models

If you would like to define a custom model to represent the intermediate table of your relationship, you may call the using method when defining the relationship. You can combine using and withPivot in order to retrieve columns from the intermediate table.

But on a fresh checkout of Laravel 5.8 the case described in the documentation seems to fail - I this would seem to be a bug, to me. Unless there is something I'm missing?

07 Mar
3 months ago

burlresearch left a reply on Attach() On Custom BelongsToMany-Model

Curious, this does seem to be a bug. The docs are pretty clear that what you're trying should work. I tried the exact same thing as you, in a fresh install of Laravel 5.8.3 and I saw the exact same thing.

I reverted to the "old method" that I would have used in <5.8 by simply using the 2nd argument to specify the pivot table, and that works, of course.

    public function folders()
    {
        return $this->belongsToMany(Folder::class, Membership::class)
            ; // ->using(Membership::class);
    }
    
    public function users()
    {
        return $this->belongsToMany(User::class, Membership::class)
            ; //->using('App\Membership');
    }

But the docs are very clear this is a new feature of 5.8 - and I agree, it does seem like you found a bug!

13 Feb
4 months ago

burlresearch left a reply on DB Design Help - Primary Index : String Or Numeric

right - seems somehow I've misread your question. So forget the 'activities', seems like what you want to model is Users, and Posts, and the activity you want to track is the interaction of users to posts, in this case 'by liking'.

There are 2 ways I have done this in the past, depending on how many other types of interactions you intend to track. But if it's just the ability to 'like a post' then let's start with that. Either way - you need to create a 3rd, 'pivot table' to track this interaction, here is likely what you're migration will look like;

    public function up()
    {
        Schema::create('post_user', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('post_id');
            $table->unsignedInteger('user_id');
            // $table->string('type');    // this is OPTIONAL, if you need to extend...
            $table->foreign('post_id')->references('id')->on('posts');
            $table->foreign('user_id')->references('id')->on('users');
            $table->unique(['post_id', 'user_id']);
        });
    }

Then on your User Model, you'll have a many-to-many relation for the posts they like:

    public function likes()
    {
        return $this->belongsToMany(Post::class);
    }
12 Feb
4 months ago

burlresearch left a reply on Laravel Relationship Query

This looks like a straight-up, many-to-many relationship:

https://laravel.com/docs/master/eloquent-relationships#many-to-many

once you have your pivot-table defined, which should be called category_country, and your Models defined correctly, as per the link above, then you will be able to reference the category names by looping over them:

$country->categories->each(function($c){
  dump($c->name);
})
11 Feb
4 months ago

burlresearch left a reply on DB Design Help - Primary Index : String Or Numeric

Given that each like for a user is unique - I assume you could just do:

$score = $post->likes->count() * 2