burlresearch

Consultant at https://burlresearch.com

Hire Me

Experience

108,090

94 Best Reply Awards

  • Member Since 4 Years Ago
  • 686 Lessons Completed
  • 16 Favorites

12th October, 2018

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

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);
}

11th October, 2018

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

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.

burlresearch left a reply on Export • 1 week ago

It may depend on your version of Laravel that you are running: php artisan -V

If it's not recent enough, then you have to add to the providers list in your:

config/app.php

    'providers' => [
    // ...
        /*
         * Package Service Providers...
         */
        Maatwebsite\Excel\ExcelServiceProvider::class,

    // ...
    ],

and if that still doesn't work, then you could try:

$ composer dump-autoload

that should do it, you should be able to verify that that make:export command is in the list:

$ php aritsan list make

This basically is the config described in the setup. Trace it, what's missing?

10th October, 2018

burlresearch left a reply on How To Pass Data Image Location Using JQuery And Show It In Modal • 1 week ago

I'm a little confused by what I'm seeing, but I think I would:

  1. put the click on the button
  2. presume that the data-userphoto is the full url (?!)
  3. then use jQuery to replace the img.src property in the modal:
$('.showuser').click(function () {
  $('.form-group img').prop('src', $(this).data('userphoto'));
});

no?

9th October, 2018

burlresearch left a reply on Scheduler • 1 week ago

You certainly could schedule a task to do this. But you still need to have a task to schedule.

The way I generally is to start with an Artisan command that does the thing, then it's fairly easy to:

  1. riff on
  2. test
  3. call later from your code
  4. schedule

So, I'd start by writing your command with:

php artisan make:command --command=email:template -- EmailTemplate

and get that working. Then you can schedule it any way you want, even directly as a CRON job, at 9:15 tomorrow:

15 9 10 10 * /usr/bin/php /srv/laracasts/artisan  email:template > /dev/null 2>&1

burlresearch left a reply on Array Transformation • 1 week ago

This transformation can be achieved with simple a combine:

public function handle()
{
    $contacts = [
        'name'  => ["A", "B",],
        'phone' => ["1", "2",],
    ];

    $USE_ELOQUENT = false;

    if ($USE_ELOQUENT) {
        $coll = collect($contacts['name'])->combine(
            $contacts['phone']
        );
    } else {
        $coll = array_combine($contacts['name'], $contacts['phone']);
    }

    dump($coll);
}

Is there more to it? Did you mean to use an Eloquent approach?

burlresearch left a reply on Two Foreign Keys Referencing The Same Primary Key • 1 week ago

I think the simplest thing here, is for you to protect yourself against trying to dereference a [potentially] null-value, something like:

@foreach($task as $taskItem)
  @if($taskItem->assignedTo)
    <p>{{ $taskItem->assignedTo->name }}</p>
  @endif
  {{-- OR, --}}
  <p>{{ optional($taskItem->assignedTo)->name }}</p>
@endforeach 

5th October, 2018

burlresearch left a reply on How To Call Laravel Route From Js Script File? • 2 weeks ago

The use of named routes is pretty well defined:

https://laravel.com/docs/master/routing#named-routes

but, yes, your second definition does seem to work - but I'd stick with what the documentation says to do.

4th October, 2018

burlresearch left a reply on How To Call Laravel Route From Js Script File? • 2 weeks ago

no - those 'named routes' in your routes files are for Laravel on the server-side. Javascript on the client-side does NOT have access to the mechanisms to decode these.

You're best left to use the URI field from php artisan route:listto form your href entries in JS.

$ php artisan route:list
+---------------+---------------------+------------------+----------------+--------------+
| Method        | URI                 | Name             | Action         | Middleware   |
+---------------+---------------------+------------------+----------------+--------------+
| POST          | api/markers         |                  | Closure     ...| api          |
| GET|HEAD      | api/subcat          | subcat.index     | App\Http\Con...| api          |
| POST          | api/subcat          | subcat.store     | App\Http\Con...| api          |
| GET|HEAD      | api/subcat/create   | subcat.create    | App\Http\Con...| api          |
| GET|HEAD      | api/subcat/{subcat} | subcat.show      | App\Http\Con...| api          |

1st October, 2018

burlresearch left a reply on Jquery Not Defined • 2 weeks ago

Plus, check your use of asset() - not sure what your project structure looks like, but I suspect this isn't generating the correct path for you, either:

>>> asset('img/photo.jpg')
=> "http://laracasts.test/img/photo.jpg"

burlresearch left a reply on Create And Edit Data With Single Form • 2 weeks ago

Are you storing/fetching an old token somehow? This really doesn't make sense, as the token should have nothing to do with the form-data being sent. Just a thought.

You may want to post some more code here for us to look at - this isn't enough to go on.

30th September, 2018

burlresearch left a reply on How To Upload Multiple Images With Dropzone • 2 weeks ago

I wouldn't try to fight Dropzone. I would:

  • let it upload the files to your Laravel server as soon as they are dropped
  • verify the upload is roughly what you expect
  • store the files locally
  • return the pathname
  • store those pathnames as a hidden input in the form
  • then, when the form is completed and validated, grab those files and upload them to S3

Here is an upload() function that I have used:

public function upload(Request $request)
{
    \Log::debug(__METHOD__, $request->toArray());
    $response = ['status' => 'ack'];

    if ($request->hasFile('file') && ($request->file->isValid())) {
        $fname = sprintf("%s-%s", date('ymdhis'), $request->file->getClientOriginalName());

        $stored             = $request->file->storeAs('uploads', $fname);
        $response['stored'] = $stored;

        if ($this->checkValidUploadType($stored)) {
            ImportJob::dispatch($stored);   // artisan make:job ImportJob
        } else {
            unlink(storage_path('app/' . $stored));
            abort(406, 'Unrecognized CSV header.');
        }
    } else {
        $response['status'] = 'error: during upload';
    }

    return $response;
}

28th September, 2018

burlresearch left a reply on How To Add A Where Clause For A Resource By Default? • 3 weeks ago

I thought your question was about modifying global scope

I want to modify the resource query by adding a where clause by default

If you don't want it to always apply, then consider using local scopes

burlresearch left a reply on Notification • 3 weeks ago

If the people on the site are not logged in - then the Auth::user() will most certainly be null.

This is your error, by definition.

I think what you want is just simply fire a new NotifyDashboard event, should be something simple like: event(new NotifyDashboard)

Maybe check for more info:

https://laravel.com/docs/master/events

burlresearch left a reply on How To Add A Where Clause For A Resource By Default? • 3 weeks ago

Sounds like you want to check out Eloquent Global Scopes for your model. If I read your question correctly, this will allow you to modify all() queries against your model, by default.

Global scopes allow you to add constraints to all queries for a given model. Writing your own global scopes can provide a convenient, easy way to make sure every query for a given model receives certain constraints.

26th September, 2018

burlresearch left a reply on Laravel API Endpoint Pattern • 3 weeks ago

Honestly I wouldn't differentiate between the routes at all. I'd like the application serve up the data at the route endpoint: /jobs/{jobId}

Then, I'd treat the request to the model with the appropriate Authorization Policy to see if the user making the request should be allowed to have the information, or whether to abort(403)

burlresearch left a reply on Vue Default Selection For Select • 3 weeks ago

Once I figured out vue-select, which works fine for either single or multiple select inputs, I have been using them ever since - they do simplify a lot of logic, and I hate excessive javascript:

<template>
  <form @submit.prevent="submit">
    <form-group id="company" label-for="company" label="Company">
      <v-select :options="companies" v-model="formdata.company"></v-select>
    </form-group>
  </form>
</template>

<script>
  import vSelect from 'vue-select';

  export default {
    components: {vSelect},
    data() {
      return {
        form: new Form,
        formdata: {},
        companies: [
          {'value': 1, 'label': 'Acme Inc'},
          {'value': 2, 'label': 'Beta Ltd'},
          {'value': 3, 'label': 'Chaz Co.'},
        ],
      };
    },
    methods: {
      submit() {
        this.form.save('/form-end-point', this.formdata)
          .then(() => console.log('submitted'))
          .catch(err => console.log('ERRORS', err.response));
      },
    },
  };
</script>

25th September, 2018

burlresearch left a reply on How Would I Tackle This Code (Vue) In Laravel? Parsing XML • 3 weeks ago

In order to parse the XML data, you could start with SimpleXML:

http://php.net/manual/en/simplexml.examples-basic.php

Guzzle used to wrap this for you:

http://docs.guzzlephp.org/en/5.3/quickstart.html#xml-responses

But it looks like it leaves it up to you now to manage the payload yourself.

burlresearch left a reply on Sequence Code Does Not Work • 3 weeks ago

the way this works, @slickness , is:

  1. when you ask a question
  2. and someone takes the time to answer it and suggests code
  3. you study the tip and make it work for you
  4. you learn something
  5. you mark their answer as best answer, not your own study notes

24th September, 2018

burlresearch left a reply on How To Access All Values From Calculated Field And Pass Them In Array? • 3 weeks ago

The get() will return a standard Laravel Collection. So, as usual, to "access a column" you could pluck the values, of any of the selected elements:

$excelentes = ...->get();

$names = $excelente->pluck('name');
$cantidads = $excelente->pluck('cantidad');

But calling first() on the collection will return only the first element. So, as @dextercampos mentions - you still need to iterate through the collection, either using foreach, or one of the other Collection Iterators

burlresearch left a reply on Vue Default Selection For Select • 3 weeks ago

There are nice plugins for this which provide all the functionality you'd ever want:

Both of these automate everything about selects in Vue, with a little configuration. Let us know if you're interested in going this route, or if you really want to code-your-own.

21st September, 2018

burlresearch left a reply on Radio Button Array Store • 4 weeks ago

<input onclick="sendRating({{$book['id']}}, {{$rating}})" id="b-{{$book['id']}}}-r-{{$rating}}" name="book-{{$book['id']}}" value="{{$rating}}" type="radio" class="">

Then you just have to write the javascript function sendRating, or whatever you want to call it...

burlresearch left a reply on Radio Button Array Store • 4 weeks ago

Totally didn't get that from your question. Then for each Book you will want 5 inputs, each sharing a name, for the group:

@foreach($books as $book)
  <div class="row">
    <strong>Book # {{ $book['id'] }}: </strong>
    @foreach(range(1, 5) as $rating)
      <div class="">
        <input id="b-{{$book['id']}}}-r-{{$rating}}" name="book-{{$book['id']}}" value="{{$rating}}" type="radio" class="">
        <label for="b-{{$book['id']}}}-r-{{$rating}}" class="">{{ $rating }}</label>
      </div>
    @endforeach
  </div>
@endforeach 

20th September, 2018

burlresearch left a reply on Sequence Code Does Not Work • 4 weeks ago

Even if it worked, it will be hell to maintain. The steps you're doing make sense, let's see if we can clean them up a bit?

  1. get the most frequent recent tags
  2. get the articles with those tags, i think?

So, 1, the top recent tags:

$recent_tags = Taggable::where('created_at', '>=', now()->subHours(48))
    ->pluck("tag_id")
    ->filter()
    ->all();

$cnts = array_count_values($recent_tags); // count the values
arsort($cnts);                            // sort them
$cnts = array_slice($cnts, 0, 3, true);   // take however many
$top3_tagids = array_keys($cnts);         // the winners

And, 2, the articles:

$articles = Article::with([
    'tags' => function ($query) use ($top3_tagids) {
        $query->whereIn('id', $top3_tagids);
    },
    ]) // ...
    ->get();

burlresearch left a reply on Radio Button Array Store • 4 weeks ago

I'm not sure what you mean by:

and i want to store it on database with 5 rows

Radio buttons are about selecting a single option, from a set. So you only need 1 database field in which to store this. There can be only only.

Are you trying to do something else here?

burlresearch left a reply on Radio Button Array Store • 4 weeks ago

If you want them all to submit for the same radio-set, then you'll have to use the same name foreach of them. The values, labels, and id's foreach should be different:

@foreach($books as $book)
    <input id="bookid_{{ $book->id }}" class="bookval" type="radio" name="book" value="{{ $book->id }}">
    <label for="bookid_{{ $book->id }}" class="custom-control-label">
        {{ $book->name }}
    </label>
@endforeach 

burlresearch left a reply on Adding Default Value If Nothing Is Submitted To Field • 4 weeks ago

When you're creating a new coupon, you must be supplying a value for the field 'couponcode' => null, so it's not getting it's 'default' value, but rather the one you're providing, only the database is constrained to not allow a null-value.

You can do 1/2 things:

  1. make the field nullable: $table->string('couponcode')->default('default')->nullable();
  2. make sure you filter out null-values, when you create new coupons: Coupon::create(array_filter($coupon_data));

Not sure which suits you best, but either of those approaches might work.

burlresearch left a reply on Laravel Deployment Server Reqeuirements • 1 month ago

Laravel 5.6 needs PHP ^7.1.3:

https://laravel.com/docs/5.6/installation

So get a new server.

burlresearch left a reply on WEEKDAY() Wont Work Non Sqlite Database • 1 month ago

When you're using whereRaw you are using database specific query strings. These, clearly, are not portable across database engines. Case in point: weekday() is a MySQL. function.

You could create a raw query using strftime('%w', 'now') in SQLite, but you're still tying that query to your database.

To do this in Eloquent, you could use a filter on the Carbon instance of the created_at field:

Book::all()->filter(function ($i) {
    return $i->created_at->dayOfWeek == Carbon::now()->dayOfWeek;
});

burlresearch left a reply on Getting A Object From A Collection In The Blade File • 1 month ago

If $channels is a Eloquent Collection, then you can be a little more direct:

$channels->find(1)->name

You can use find on an Eloquent Collection to search on the primary ID, which you seem to want.

But, I think there is more to your problem...

18th September, 2018

burlresearch left a reply on Students Position From Average • 1 month ago

Just for the record, here is a minor variation that does the ranking (with ties) in a single pass. Quite simple:

public function handle() {
    $marks = collect([3101625668 => 98.0, 3101635921 => 98.0, 3913126364 => 35.77, 3913058204 => 25.33, 3101372540 => 33.47, 3913752741 => 40.0, 3913120054 => 20.4, 3913998755 => 26.67, 3913861492 => 25.2, 3913881854 => 19.8,]);
    $avg   = $marks->avg();
    $rank  = 0;
    $run   = 0;
    $prev  = null;

    $marks->sort()
        ->reverse()
        ->map(function ($mark, $id) use ($avg, &$rank, &$run, &$prev) {
            $run  = $mark == $prev ? $run + 1 : 0;
            $prev = $mark;
            return [
                'mark' => $mark,
                'rank' => ++$rank - $run,
                'dev'  => $mark - $avg,
                'id'   => $id,
            ];
        })
        ->dump();
}

14th September, 2018

burlresearch left a reply on Students Position From Average • 1 month ago

    public function handle() {
        $marks = collect([3101625668 => 98.0, 3101635921 => 98.0, 3913126364 => 35.77, 3913058204 => 25.33, 3101372540 => 33.47, 3913752741 => 40.0, 3913120054 => 20.4, 3913998755 => 26.67, 3913861492 => 25.2, 3913881854 => 19.8,]);
        $avg  = $marks->avg();
        $rank = 1;

        $marks->sort()
            ->reverse()
            ->map(function ($mark, $id) use ($avg, &$rank) {
                return [
                    'dev'  => $mark - $avg,
                    'id'   => $id,
                    'mark' => $mark,
                    'rank' => $rank++,
                ];
            })
            ->dump();
        
        /* Illuminate\Support\Collection {
        array:10 [
          3101635921 => [
            "dev" => 55.736
            "id" => 3101635921
            "mark" => 98.0
            "rank" => 1
          ]
          3101625668 => [
            "dev" => 55.736
            "id" => 3101625668
            "mark" => 98.0
            "rank" => 2
          ]
          3913752741 => [
            "dev" => -2.264
            "id" => 3913752741
            "mark" => 40.0
            "rank" => 3
          ]
          3913126364 => [
            "dev" => -6.494
            "id" => 3913126364
            "mark" => 35.77
            "rank" => 4
          ]
          3101372540 => [
            "dev" => -8.794
            "id" => 3101372540
            "mark" => 33.47
            "rank" => 5
          ]
          3913998755 => [
            "dev" => -15.594
            "id" => 3913998755
            "mark" => 26.67
            "rank" => 6
          ]
          3913058204 => [
            "dev" => -16.934
            "id" => 3913058204
            "mark" => 25.33
            "rank" => 7
          ]
          3913861492 => [
            "dev" => -17.064
            "id" => 3913861492
            "mark" => 25.2
            "rank" => 8
          ]
          3913120054 => [
            "dev" => -21.864
            "id" => 3913120054
            "mark" => 20.4
            "rank" => 9
          ]
          3913881854 => [
            "dev" => -22.464
            "id" => 3913881854
            "mark" => 19.8
            "rank" => 10
          ]
        ]
        */
    }

11th September, 2018

burlresearch left a reply on Admin Dashboard As SPA! • 1 month ago

You may want to take a look at:

https://nova.laravel.com/

before you begin. It's not exactly an SPA, but you may want to consider your level-of-effort...

burlresearch left a reply on Linking Articles With Groups • 1 month ago

OK, now I think I get what you want. If, for a given group, you want to find all the articles which have exactly the same tags, then my approach would be to get the set of tag->ids and then find the articles that share that set - an intersection of tags:

$group_tag_ids = $group->tags->pluck('id')->all();

Article::all()->filter(function ($m) use ($group_tag_ids) {
    return $m->tags->pluck('id')->all() == $group_tag_ids;
});

This way you can ->filter the set of Articles by the ones that match only the association. I think this would be my approach...

9th September, 2018

burlresearch left a reply on Linking Articles With Groups • 1 month ago

@slickness , I don't understand your question about how to use the code in a controller.

I think my last snippet shows how, given a $group you could list all $articles which share any of the same $tags. Is this not your question?

The conversation may be drifting a little here - why not show this controller method you're working on, we'll see if we can make progress ...

2nd September, 2018

burlresearch left a reply on Result Filtering • 1 month ago

I think you'd want to take advantage of Eloquent to help you build your query. In this case, it sounds like you want to start with Person - so Eloquent would encourage that:

$person = Person::findOrFail(25);
$histories = $person->histories()>where('action_id', '1')->get();
dd($histories->toArray());

This will let you inspect the result generated - if correct, then remove the dd line and pass that to your view.

1st September, 2018

burlresearch left a reply on Get The Data From Google Spread Sheet In Laravel • 1 month ago

For your 1st issue: did you run the artisan vendor:publish as the document specifies. The error seems to refer to that.

2nd, I think all you need to do is to type-hint the

function index(Request $request)

burlresearch left a reply on GetTransName() Function Returning {"fr":"étoile"} Instead Of étoile Alone • 1 month ago

Here is a nice link for some packages that provide additional functionality on top of Laravel localization:

https://quickadminpanel.com/blog/10-best-laravel-packages-for-multi-language-projects/

In particular I have often use, and can recommend:

https://github.com/mcamara/laravel-localization

given that it can help with route localization.

I write many of my Laravel sites in 2 languages, working for Canadian gov't and others, usually we have requirements for En + Fr. Laravel makes this very easy, compared to most CMS's and frameworks I have had to use in the past...

31st August, 2018

burlresearch left a reply on Get The Data From Google Spread Sheet In Laravel • 1 month ago

Your link isn't working - but that's not the issue.

In order to re-create a spread-sheet in Laravel then you will inevitably generate column-based data in many rows. Each column is defined by a migration:

http://laravel.test/docs/master/migrations

Building an appropriate table for your sheet, and importing the data-rows, is what you want...

burlresearch left a reply on How To Add Multiple Same Name Input Fields In One Form Into Database? • 1 month ago

But if there are many inputs with the same name on submit, then how will you store them?

This isn't a technical issue, but a planning issue, so far. What are you looking to achieve here?

30th August, 2018

burlresearch left a reply on Table Witch Real Time Search • 1 month ago

I use Bootstrap-Vue to great effect:

https://bootstrap-vue.js.org/docs/components/table

It makes building tables from AJAX data a breeze, and can handle rough but fast searches and pagination, on moderate amounts of data.

Typically I use this to prototype pages, and then enhance later as needed.

burlresearch left a reply on GetTransName() Function Returning {"fr":"étoile"} Instead Of étoile Alone • 1 month ago

I think the answer to your question is: you could do it like this:

public function getTransName($code) {
  return $this->select($code)->first()->{$code};
}

But, this certainly looks like you're trying to do some form of localization. As above, I'd highly recommend you take a little time to make sure you understand what Laravel provides out-of-the-box for this issue.

You'll be leagues ahead if you can use that.

29th August, 2018

28th August, 2018

burlresearch left a reply on Laravel Passport, Axios Error "Unauthenticated" • 1 month ago

I got bit by the same thing - it was driving me nuts. I don't know how this hasn't generated more traffic, it took me forever to figure out.

What happened was around ~5.6.30 there was an upgrade to some Passport code that serializes cookies - and I believe this to be the issue. You need to set:

\Laravel\Passport\Passport::$unserializesCookies = false;

And this should fix your issue. There is a new method provided, also ~5.6.30, which you can use to set this from your:

\App\Providers\AppServiceProvider::boot()

    public function boot()
    {
        /*
         * https://twitter.com/laravelphp/status/1027634172477595648
         * https://stackoverflow.com/questions/49445559/always-got-message-unauthenticated-laravel-passport/51975786#51975786
         */
        \Laravel\Passport\Passport::withoutCookieSerialization();
    }

This worked for me.

burlresearch left a reply on Logout From Facebook With Socialite • 1 month ago

You can't control Facebook from your Laravel app. You can only logout of your Laravel app.

You have to go to Facebook, to logout from Facebook.

27th August, 2018

burlresearch left a reply on Relationships Problem HasMany • 1 month ago

This looks correct, but there are a couple stylistic things that I'd normally point out.

  1. Plural relation method; since your Hub's haveMany Devices, I'd expect the method name to reflect this: public function devices(){ // so: Hub::find(1)->devices
  2. Redundant indexes; given that your foreign key on Device is correctly named (hub_id) you do not need to declare them, Laravel makes this assumption:
public function hub() {
  return $this->belongsTo(Hub::class);
}
public function device(){
  return $this->hasMany(Device::class);
}

So this is all fine, and isn't your issue. But you ask about:

Does it has to do something with the foreign key of Hubs table?

There should be NO foreign key at all on your Hubs table - this could be your issue. The only foreign key is hub_id, on the devices table.

If this isn't the issue, let's see your migrations?

21st August, 2018

burlresearch left a reply on Laravel Learinig • 1 month ago

Eloquent.

17th August, 2018

burlresearch left a reply on How Can I Display Dinamyc Key Of Array In The Laravel Blade? • 2 months ago

That should give you the basic idea - but that approach is how you can do it.

burlresearch left a reply on How Can I Display Dinamyc Key Of Array In The Laravel Blade? • 2 months ago

You have an array-of-arrays, and the nested array may have a variety of keys. The hint here is that you have 2-deep arrays, so use 2 for-loops. To get what you want you could try:

@foreach($items as $row)
    <ul>
        @foreach($row as $attr => $valu)
            <li><strong>{{ $attr }} :</strong> {{ $value }}</li>
        @endforeach
    </ul>
@endforeach

rendering this as a table is a poor choice, since, as you know, you will have a different number of columns foreach, though it can be done.

This will get your data out - you can play around with how you finally render it.

Edit Your Profile
Update

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