burlresearch

burlresearch

Member Since 5 Years Ago

Ottawa

Consultant at https://burlresearch.com

Experience Points 118,240
Experience Level 24

1,760 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 756
Lessons
Completed
Best Reply Awards 98
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.

13 Feb
5 days 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
6 days 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
1 week 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

10 Feb
1 week ago

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

What you're describing here is a prototypical many-to-many relationship.

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

You have 2 models that you have described, Users and Activities. You will need a 3rd table to track the many-many relationship between these, Laravel will expect you to name this pivot table: activity_user

To ensure that you cannot enter duplicates, you should place an additional constraint on that pivot table that says $table->unique(['activity_id','user_id']); in your migration.

This should take care perfectly what you want, and make it easy to count your points.

08 Feb
1 week ago

burlresearch left a reply on Laravel One To Many Polymorphic - One (model) To Many (many Types Of Models)

The way I like to handle this, and I think Jeffrey has similar precedents here on Laracasts, is to create a Trait for your Streamable type:

<?php namespace App\Traits;
use App\Stream;

/**
 * Trait Streamable
 * @package App\Traits
 */
trait Streamable {
  /**
   * @return \Illuminate\Database\Eloquent\Relations\MorphMany
   */
  public function streams() {
    return $this->morphMany(Stream::class, 'streamable');
  }
}

then you can easily make your polymorph models share that part with a simple: use Streamable;

In the migration for you would, as typical, have a starter like:

public function up() {
    Schema::create('streams', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('streamable_id');
        $table->string('streamable_type');
        // ...
        $table->timestamps();
    });
}

which can be extended to include the common traits.

Does this help clarify things? Or are you asking something more specific?

burlresearch left a reply on Specify Sort Order Of Pivot Table Entries In View

The simple way that I have handled this, in a solution to a similar to what you want, is to use an extra column on the pivot table - called order.

Then when I pull the many relations to the model that is currently displayed, just make sure the extra pivot data is included, in your Model:

return $this->belongsToMany('App\RelatedModel')->withPivot('order');

Then I just make sure I sort the models by their order when their displayed.

On the client-side, using Vue, there is a handy plugin I used to make a nice drag-and-drop UI for the admin-user to reorder their lists, as desired: Vue.Draggable

29 Jan
2 weeks ago

burlresearch left a reply on AJAX Data

Here is my blade file (using jQuery, since that's what it looks like you were expecting) that might help you.

You simply need to loop over the response from the $ajax call, here using $.each() loop to render the nested lines on your page:

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <h3>Weather Report</h3>
            <ul id="report"></ul>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
      $(document).ready(function () {
        $.ajax({
          'url': 'https://apis.is/weather/forecasts/is',
          'type': 'GET',
          'dataType': 'json',
          'data': {'stations': '1,422'},
          'success': function (response) {
            let cities = '';
            $.each(response.results, function (key, res) {
              // console.log(res);
              cities += '<li>'
                + ' City name: ' + res.name
                + ' @ ' + res.atime
                + '<ul>'
              ;
              $.each(res.forecast, function (fkey, fore) {
                cities += '<li>'
                  + ' ftime: ' + fore.ftime
                  + ' F: ' + fore.F
                  + ' D: ' + fore.D
                  + ' T: ' + fore.T
                  + ' W: ' + fore.W
                  + '</li>'
                ;
              });
              cities += '</ul></li>';
            });
            $('#report').append(cities);
          },
        });
      });
    </script>
@endpush
24 Jan
3 weeks ago

burlresearch left a reply on How Can I Use Jquery For One Component In Vue ?

This is a relatively straight forward thing to do. I got it working on my site by:

fetch it using NPM

$ npm install particles.js

then, import with Laravel webpack:

webpack.mix.js

let mix = require('laravel-mix');

mix.js('resources/assets/js/app.js', 'public/js')
  .sass('resources/assets/sass/app.scss', 'public/css')
  .scripts('node_modules/particles.js/particles.js', 'public/particlesjs/particles.js')
  .copy('node_modules/particles.js/demo/js/app.js', 'public/particlesjs/')
;

Then, from my homepage Blade file, I just pushed it on my scripts stack:

welcome.blade.php


@push('scripts')
    <script src="{{ asset('particlesjs/particles.js') }}"></script>
    <script>
        particlesJS.load('particles-js', 'particlesjs/particles.json', function () {
            console.log('callback - particles.js config loaded')
        })
    </script>
@endpush

And, I think there was one more config I brought in to configure things:

public/particlesjs/particles.json

22 Jan
3 weeks ago

burlresearch left a reply on Installing Laravel On A Freelancers Machine

Config files will likely be in (on a Mac): /etc/php.ini - check there

burlresearch left a reply on In A Complete Mess With Vue And Charts.js

You basically had most of it. I tidied up what you had - and fixed a couple of the little data issues. Not sure what you're going for exactly, cause your data was a little weird (too many of the same keys...). Here is a working example with some little tweaks:

<template>
  <div class="container">
    <div class="row">
      <div class="col">
        <canvas width="300" height="150" ref="chart"></canvas>
      </div>
    </div>
  </div>
</template>

<script>
  import Chart from 'chart.js';

  export default {
    name: 'GraphJs',
    props: ['temps', 'jdata'],
    components: ['Chart'],

    data() {
      return {
        vtemps: [
          {'hour': '2202', 'temperature': '12'},
          {'hour': '2203', 'temperature': '13'},
          {'hour': '2204', 'temperature': '5'},
          {'hour': '2205', 'temperature': '8'},
          {'hour': '2206', 'temperature': '11'},
          {'hour': '2207', 'temperature': '10'},
        ],
      };
    },

    mounted() {
      let context = this.$refs.chart.getContext('2d');

      let cdata = {
        labels: this.vtemps.map(function (i) { return i.hour }),
        datasets: [
          {
            label: 'Hourly Temperatures',
            data: this.vtemps.map(function (i) { return i.temperature }),
            fill: false,
          },
        ],
      };
      new Chart(context, {type: 'line', data: cdata});
    },
  };
</script>
18 Jan
1 month ago

burlresearch left a reply on Help In Building Eloquent Relationships

This is a big ask - b/c so many moving parts. I'd suggest to

  1. build what you want incrementally, one or two models at a time
  2. focus initially on the links between the models (rather than the properties of the models, this is just additional typing)
  3. test the relationships - then think of expanding to the next model

It's good that you have an overall picture of what you want. But as you build it you will run into little things that will tweak how you round out the schema relations.

Likely I'd start with a Technician model (since that looks central to you) and work out from there.

(I've actually built a Laravel site that essentially does almost the same thing as what you describe.)

From a Laravel command line, I'd say start building the relationships between the core models of your schema:

[email protected]:/srv/trades$ artisan make:model -a -- Technician
Model created successfully.
Created Migration: 2019_01_19_034657_create_technicians_table
Controller created successfully.
[email protected]:/srv/trades$ artisan make:model -a -- Company
Model created successfully.
Created Migration: 2019_01_19_034705_create_companies_table
Controller created successfully.
[email protected]:/srv/trades$ artisan make:model -a -- Customer
Model created successfully.
Created Migration: 2019_01_19_034723_create_customers_table
Controller created successfully.
[email protected]:/srv/trades$ artisan make:model -a -- Service
Model created successfully.
Created Migration: 2019_01_19_034807_create_services_table
Controller created successfully.
[email protected]:/srv/trades$ 
14 Jan
1 month ago

burlresearch left a reply on Vuejs Filter With Checkbox

There is some helpful detail in the VueJS guide for dealing with Filtering, as you want to do:

https://vuejs.org/v2/guide/list.html#Displaying-Filtered-Sorted-Results

I have a working example here that you should be able to directly apply to your table variation:

<template>
  <div class="container">
    <div class="row">
      <div class="col">

        <div v-for="cat in categoryList">
          <input type="checkbox" :id="cat" :value="cat" v-model="categories">
          <label :for="cat">{{cat}}</label>
        </div>
        <br>
        <span>You have chosen: {{ categories }}</span>

      </div>
      <div class="col">
        <strong>Items in chosen category(s)</strong>

        <ul>
          <li v-for="item in selectedItems"> category: {{item.category}} | name: {{item.name}}</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Checkbox',
    data() {
      return {
        categoryList: ['animal', 'fruit', 'clothes'],
        categories: [],
        items: [
          { id: '1', name: 'apple', description: 'description about product', category: 'fruit', },
          { id: '2', name: 'mango', description: 'description about product', category: 'fruit', },
          { id: '3', name: 'shoes', description: 'description about product', category: 'footwear', },
          { id: '4', name: 'shirt', description: 'description about product', category: 'clothes', },
          { id: '5', name: 'dog', description: 'description about product', category: 'animal', },
          { id: '6', name: 'cat', description: 'description about product', category: 'animal', },
        ],
      };
    },
    computed: {
      selectedItems: function () {
        let cats = this.categories;
        return this.items.filter(function (item) {
          return -1 !== _.indexOf(cats, item.category);
        });
      },
    },
  };
</script>
11 Jan
1 month ago

burlresearch left a reply on Append Data To Nested Array Collection

You need to know the length of each sub-collection - that's what the '7' represents, would be the 8th item in the collection.

But that should be the idea.

10 Jan
1 month ago

burlresearch left a reply on Append Data To Nested Array Collection

Since you're looking to modify your data array, in place, I think you may want to check out: data_set. With this method you can easily alter your nested structures.

Here is a suggestion that might lead you in the right direction:

data_set($col, 'groups.7.5.port.7.service.5.name', $name);

Or so - you'll have to do some experimenting for how to get the array.length counts...

04 Jan
1 month ago

burlresearch left a reply on Vmware Ubuntu

Looks like you'll need VMware Vagrant plug-in to use it with Homestead. But Homestead will work fine on VMware. The docs are pretty clear on how to get started:

https://laravel.com/docs/master/homestead#installation-and-setup

Is there something else you're looking for?

03 Jan
1 month ago

burlresearch left a reply on Move From Sentinel To Laravel Auth

If you're still early in your project - like no production users - then you could likely get away with just installing php artisan make:auth and a migration to copy your user details from the Cartalyst tables to the native Laravel App\User table.

Better to switch earlier than later.

19 Dec
1 month ago

burlresearch left a reply on Datetime Zone Issue

This should come from your config/app.php settings, make sure:

    'timezone' => 'UTC',

is set any that should take care of your default timestamps.

18 Dec
2 months ago

burlresearch left a reply on Laravel Collection Always Returns An Object Instead Of An Array

This is a perfect candidate for which to use an Eloquent: API Resource.

In fact, because you have a hybrid model here you could even use 5 API Resources. One each, to model the 4 pure models, and a 5th to model the hybrid representation that you want to model in your API response.

I have actually built a system very similar to what you're working on, and this is how I do it. The API resources make a perfect solution, not just for exporting to your front-end, but also later for flat-file export and BI-layer consumption.

12 Dec
2 months ago

burlresearch left a reply on How To Open List Where Parent_id 1

Just as I wrote in the explanation. Before you click, this.adverts = [] so the 2nd list will contain no items. When you @click="sendAdvert(category.id)" you will call your HTTP endpoint that will populate the list of child-objects, into your this.adverts.

Then Vue will pickup the change and render the list items, in:

Child Listing (after your Categories)

<ul class="list-group">
    <li v-for="advert in adverts" :id="'advert-'+advert.id" class="list-group-item">{{ advert.name }}</li>
</ul>
10 Dec
2 months ago

burlresearch left a reply on How To Open List Where Parent_id 1

I think the first thing is to realize that your Category is related to itself, and that you can represent this relation just like any other Eloquent relation.

class Category extends Model {
  public function parent() {
    return $this->belongsTo(Category::class, 'parent_id');
  }

  public function children() {
    return $this->hasMany(Category::class, 'parent_id');
  }
}

This way, you can get all the children of an object like this:

>>> Category::find(1)->children
=> Illuminate\Database\Eloquent\Collection {
     all: [
       App\Category {
         id: 2,
         parent_id: 1,
         name: "Devil",
         created_at: "2016-08-17 09:58:54",
         updated_at: "2018-04-18 10:34:52",
       },
       App\Category {
         id: 3,
         parent_id: 1,
         name: "Taz",
         created_at: "2017-05-08 00:24:19",
         updated_at: "2018-02-26 20:32:14",
       },
     ],
   }

Then your store() method is simply returning the children:

public function store(Request $request)
{
    $id = $request->id;
    $category = Category::find($id);

    return $category->children;
}

(Although I don't think this is well-named, this method should really be called children(); and better accessible as a GET request, but you can refactor later.)

Now, when you call: axios.post('adverts/store', { id: id })

Your response data will be adverts as you have it, an array of child objects. I suppose you could add a second list, for the children, in a second list (however you want to handle it):

<ul class="list-group">
    <li v-for="advert in adverts" :id="'advert-'+advert.id" class="list-group-item">{{ advert.name }}</li>
</ul>
06 Dec
2 months ago

burlresearch left a reply on Static Methods And Method Chaining

In order to chain methods, the trick is to, at the end of each function, return a reference to object that was just called. The object then has a function defined on it for the next thing in the chain.

Your MyStaticMethod is static - so you're probably not returning a reference to the object when returning self. You could try returning new self, but you'll have to test:

    public static function MyStaticMethod($param) {
        // do __METHOD__
        return new self;
    }

this will call the constructor on the current class, and return an object that you can chain.

For the non-static method, if it's just modifying the current object, you can probably just: return $this;

02 Dec
2 months ago

burlresearch left a reply on Mail Not Sending Cc

sounds like an issue more with your mailer, than with how you're sending...

01 Dec
2 months ago

burlresearch left a reply on Jobs Applications Board

You'll want to name your pivot table according the Laravel table naming convention. Of course, you don't have to, but it will make things work a little smoother if you use the name: job_user table.

To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.

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

Once that is setup, you'll be able to see if a User has a related Job record with a query, maybe like:

$jobid = 123;
$user = App\User::find(1);
$already_applied = $user->jobs()->where('id', $jobid)->count() > 0;

burlresearch left a reply on Mail Not Sending Cc

https://laravel.com/docs/master/mail#sending-mail

The cc method accepts an email address, a user instance, or a collection of users. If you pass an object or collection of objects, the mailer will automatically use their email and name properties when setting the email recipients, so make sure these attributes are available on your objects.

So you should be able to simple pass the user for your to target, and according to docs, a simple email address int he cc field should do the trick.

Mail::to($event->user)  // User object, with `email` field
  ->cc('[email protected]')  // email address should work
  ->send(new AccountRenewalEmail($event->user, $mailcentre, $payment));
29 Nov
2 months ago

burlresearch left a reply on Laravel Horizon Handle Long Running Jobs

Instead of running 1 Job that does 200,000 things - it might be better conceived to run 200,000 Jobs that do 1 thing each.

Think about how to process each specific job chain, and think about error recovery. It's much easier to handle 1 single error than it is to handle an error in the middle of 200,000 things. What do you do for the rest?

I'd say turn your thinking inside-out.

28 Nov
2 months ago

burlresearch left a reply on Get Record Of The Item Before Specific Date

sorry dude, now I'm even more confused.

Do you want the last 5 entries before the current, empty, one? Or just the last non-null one? This doesn't seem to be as hard as you're making it?

burlresearch left a reply on Get Record Of The Item Before Specific Date

What I posted is just 2 snippets to help with the code you posted here. The question on SO seems rather different. After reading it, I suspect there is more going with what you want. I'd like to help, but you'll need to clarify.

Does the current day-of-week matter?

IE if today is Tue, but has no data, do you want the data from last Fri, or do you want the data from last Tue (assuming both have data)?

burlresearch left a reply on Get Record Of The Item Before Specific Date

I have these 2 lines which may help you:

>>> Carbon\Carbon::parse( 'Nov 21' )->day
=> 21
>>> collect([15, 18, 10, 20, 32])->filter(function($i) { return $i < 21; })->max()
=> 20

burlresearch left a reply on Vue: Truncate Filter With Html?

Sure thing - filters are a great way to do this, with Vue. I do this to truncate text entries when rendering table columns:

    filters: {
      trunc(str, len = 87) {
        _.trim(str);
        return _.truncate(str, {'length': len});
      },
    },

Called from the template section (with optional len argument):

              <template slot="purpose" slot-scope="data" v-if="data.item.experiment">
                <abbr :title="data.item.experiment.purpose">
                  {{ data.item.experiment.purpose | trunc }}
                </abbr>
              </template>
26 Nov
2 months ago

burlresearch left a reply on Supervisor Queue:work Failing

Sorry bro, just trying to help.

I can't get away from the fact that the error is PDOException [2002] Connection refused - why would the database refuse a connection during the Job, but not from a Console command?

Something is different there - and that's the issue, it seems. By the sounds of it you have supervisor and your queue:worker setup OK.

Does your queue worker call the same code path as the Console application? What does your crontab -l -u www-data look like? (It's calling your Job scheduler correctly?)

Again, my spidey-sense says it's something other than the queue worker...

burlresearch left a reply on Supervisor Queue:work Failing

This doesn't sound like an issue with supervisor as much as it sounds like an issue with your database crashing. This probably shouldn't be happening.

Even in the event of the database going down temporarily - I can see that some jobs would fail - but supervisor ought to pick up OK and keep processing any new work.

There is pretty good explanation on how to deal with failed Jobs:

https://laravel.com/docs/5.7/queues#dealing-with-failed-jobs

I'd recommend using Horizon, instead, if you want a nice way to see what's going on:

https://laravel.com/docs/5.7/horizon

21 Nov
2 months ago

burlresearch left a reply on Regex Is Almost Complete

Not sure what you're going for, if you need the full-name to be exactly the whole line, but with regex, as mentioned, the simplest solution always wins. What about:

/[а-яА-Я][ы-эЫ-Э]\s+[а-яА-Я]+/

burlresearch left a reply on L5.6 Broadcast And Queue Both To Use "redis"

You certainly can use redis to back any of your drivers, I often use it for all three of:

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

in a project, simultaneously. Never had a problem. There must be something with your config.

Have you done:

composer require predis/predis

burlresearch left a reply on Supervisor Queue:work Failing

I wouldn't run the command as user=root - I'd bet that there's something weird going on with the user permissions. Try and switch root for the user that owns your application, what user is returned by:

stat -c%U /var/www/site/artisan

14 Nov
3 months ago

burlresearch left a reply on Compute Values And Insert Them In The View

I didn't actually run this code, so it probably will need a little tweaking to run.

You can see that when we iterate over the subproducts, we use the key there to store the sum.

So for your products.key (in your example [3, 4]) the idea would be to store the durationSum in that slot: dur[3], and dur[4], respectively. That gets accumulated when we each over the subarray:

durs[key].add(...);

13 Nov
3 months ago

burlresearch left a reply on Compute Values And Insert Them In The View

I'm not sure about how you're using your computed property, but I have an idea for the meat of the issue. You're using Vue, so if you haven't disabled them, you likely have moment.js and lodash.js still loaded - I'd take advantage of these libraries to help with the Duration calculations:

accumulate() {
    let durs = [];

    _.each(this.user[0].products, function (subproducts, key) {
        durs[key] = moment.duration();   // start at 0

        _.each(subproducts, function (i) {
            durs[key].add(moment.duration(i.time));  // accumulate sub-product durations
        });
    });

    let seconds = _.map(durs, function (i) {
        return i.asSeconds();   // https://momentjs.com/docs/#/durations/as/
    });

    // seconds <- (5) [empty, empty, empty, 11, 29]
},
09 Nov
3 months ago

burlresearch left a reply on What Is .then For?

the .then() represents the success response path of an asynchronous Promise in JavaScript.

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

In your example the call to axios.get(url) returns such a Promise, and the .then() code branch is only entered later, on the successful return of that call. It may fail. Also it may take some time, yet your application continues to run, asynchronously while waiting.

It may be helpful to read some more background:

There are several good reasons for the move to use the Promise architecture in JS.

04 Nov
3 months ago

burlresearch left a reply on Relation With Pivot Table

You're right, hasManyThrough is just a shortcut for a 2 step belongsTo - so it's essentially a many-to-one.

I wonder if your Influencer-Social relation is many-many, it likely that an Influencer generally has only 1 account / platform, so maybe you could get away with 1-many here - not sure though, perhaps you have exceptions to this.

Of course, it's up to you, and your domain knowledge + requirements, but you may want to instead think of the Campaign as being polymorphic and spanning many social platforms, but rather sort of being a Tag or a label you assign the the various Influencer-Posts.

01 Nov
3 months ago

burlresearch left a reply on Find Neighbors

It would be up to you define "what is a neighbor" and to implement that yourself.

You could start by making this a function on your Model, and refactor from there if you want a Repository pattern, or whatever you like.

It's up to you do define your concept of adjacency. If by next / prev you just want to go by ID's then you could do something like:

class Profile extends Model {
    public function next() {
        return self::find($this->id + 1);
    }
    public function prev() {
        return self::find($this->id - 1);
    }
}
31 Oct
3 months ago

burlresearch left a reply on I Cant Understand Fluent Interfaces

Nah. The point of static interfaces is that there is no context, you don't need an instance to call them - they're just there ready to process something for you.

I think the point of the fluid chaining is to progress an instance through a state-machine. So having static functions here don't really make sense.

When you make your methods static public then you must abandon the $this reference in the function, it has no context.

burlresearch left a reply on Convert Multiple Array Into A String In Laravel

If you want a string, then use implode, if you need an array, then stop at pluck:

Establishments::where('status', 0)
    ->where('city', '=', $data['location'])
    ->pluck(['id'])
    ->implode(',');
// > "43,71,41,39"

Establishments::where('status', 0)
    ->where('city', '=', $data['location'])
    ->pluck(['id']);
// > [43, 71, 41, 39]
30 Oct
3 months ago

burlresearch left a reply on Improve The Search By Specific Date In Laravel

You could do this in a single call:

$from_date = Carbon::parse(request('from_date'));

Events::whereBetween('from_date', [$from_date->startOfDay(),$from_date->endOfDay()])->get();

I don't think this changes the accuracy, but it might do what you want...

burlresearch left a reply on I Cant Understand Fluent Interfaces

Given that you've watched the episode then it seems pretty clear that the create() method would simply end with: return $this;

So, you could then chain the call forward to the next method.

I suppose your real question is how to create the dynamic method setThing() which does a set action on the the Thing column. Perhaps you should refer to how Taylor does it in the Illuminate source code, for the trait ForwardsCalls:

src/Illuminate/Support/Traits/ForwardsCalls.php

https://github.com/laravel/framework/blob/5.7/src/Illuminate/Support/Traits/ForwardsCalls.php#L20-L38

    protected function forwardCallTo($object, $method, $parameters)
    {
        try {
            return $object->{$method}(...$parameters);
        } catch (Error | BadMethodCallException $e) {
            $pattern = '~^Call to undefined method (?P<class>[^:]+)::(?P<method>[^\(]+)\(\)$~';
            if (! preg_match($pattern, $e->getMessage(), $matches)) {
                throw $e;
            }
            if ($matches['class'] != get_class($object) ||
                $matches['method'] != $method) {
                throw $e;
            }
            static::throwBadMethodCallException($method);
        }
    }
28 Oct
3 months ago

burlresearch left a reply on How To Get The Sum Of All Fares

If you have Lodash then this could be much simpler:

getFareTotal() {
  return _.sumBy(this.form.ticketInvoiceItems, 'fares');
},
20 Oct
3 months ago

burlresearch left a reply on Retrieve Only Identical Array

I can think of a couple ways to do this, off-hand:

  1. array_unique(array_merge($names, $tags))
  2. array_merge($tags, array_diff($names, $tags))

burlresearch left a reply on How To Exit Out Of Saving A Record If A Condition Is Not True

This makes no sense, whatever you are trying to do, I think you need at least 1 more variable.

This code has bigger problems than deciding how to fail.

12 Oct
4 months ago

burlresearch left a reply on Re-loading Part Of The Page When Adding New Data

If you're really gung-ho about the async refresh then you could go all client-side, but I'd probably recommend a vue component for that. This way you may still pass in the $pageList set from the controller - to a $prop in Vue, OR, you could just fetch the data on mounted() of the Vue instance.

That could look like:

mounted() {
      axios.get('/api/newpage').then(res => this.pages.push = res.data);
}
11 Oct
4 months ago

burlresearch left a reply on Re-loading Part Of The Page When Adding New Data

Vue's 2-way data binding works by rendering lists of item's. If that list of items is modified after render, then Vue will take care of it, only if the list is managed by a Vue v-for. Which is not true, in your case. You have 2 options:

  1. reload the page, outright
  2. modify the Blade foreach loop you have to be a Vue iterator

Either way, you'll have to do something in the axios.post().then() block.

For 1. it would be window.location.reload(); - that may work.

For 2. you have to convert the blade foreach to be a Vue-rendered list, and push the page name into that list, in the then() block.

It might look something like:

    axios.post('/api/newpage', {
          .then(res => {
            this.pages.push(res.data);
    })

Or something close to that.