cometads

cometads

Member Since 2 Years Ago

Experience Points
13,030
Total
Experience

1,970 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
32
Lessons
Completed
Best Reply Awards
16
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 3
13,030 XP
Nov
04
1 month ago
Activity icon

Replied to Need Help Using A "cmd Tool"

You can use PHP's exec() function to run shell commands. See documentation.

For a little more of a Laravely feel you can use Symfony's Process Component which would be included as a dependency of Laravel by default.

Sep
18
2 months ago
Activity icon

Replied to How Many Middleware Am I Allowed To Include In The Get Method Of The Routes.

As many as you wish. This, along with many other Laravel methods, uses argument unpacking.

Sep
17
2 months ago
Activity icon

Replied to Using Laravel Nova As Frontend

Depending on complexity, this should just be a matter of setting your resource policies correctly. Make sure users and admins can view resources but only admins can modify resources.

Activity icon

Replied to Laravel Auth To Different BBDD

The concept you're looking for is Multitenancy.

There are several threads on this forum discussing multitenancy and an assortment of packages such as tenancy/multi-tenant

Activity icon

Replied to Condition Make The Operation After If() But Returns False

try/catch would look something like this:

try{
    Mail::to('[email protected]')->send(new BugReport($validatedData));
    flash('Hlásenie o chybe bolo úspešne odoslané.Ďakujeme')->success();
}catch(\Exception $e) {
    report($e);
    flash('Chyba! Hlásenie o chybe sa nepodarilo odoslať. Skúste znova neskôr')->error();
}
return view('bug');

You should be more explicit with the Exception you catch though.

But to be honest, if you don't know what a void function or a try/catch statement is then I would highly recommend you take a beginner's PHP/OOP course. Jeffrey offers his own course here.

Activity icon

Replied to Condition Make The Operation After If() But Returns False

I believe send() is a void function. So it will always return null and your check will always fail.

If the message (is not queued) and fails to send, it should throw an exception. So use a try/catch instead if/else.

Activity icon

Replied to Passing Single Variable Across Multiple Controllers?

The reason it doesn't show in users.index is you're already assigning the view variable $users to your paginated list of users.

As for sharing data across all views see this part of the docs.

So your AppServiceProvider would look something like this:

use App\User;
use Illuminate\Support\Facades\View;
...
    public function boot()
    {
        View::share('user_count', User::count());
    }
...
Activity icon

Replied to Advice On My .htaccess /public Folder Redirect

The point they're making is you should never have anything below the /public directory publicly accessible. Regardless of what you do with .htaccess, it is still conceivable for someone to read sensitive information such as that contained within /storage.

In essence, your issue is moot because your file structure is flawed to begin with. Find a way to make public the web root or find an alternative to Azure.

Sep
11
3 months ago
Activity icon

Replied to Disable Autoplay Feature

I know this isn't exactly a solution but incase anyone wasn't aware.

Safari, by default, never autoplays video. So if you used Safari to browse the courses they won't autoplay.

Sep
09
3 months ago
Activity icon

Replied to Vue Vuelidate Server Side Error Responses

Personally I use spatie's form-backend-validation which is specifically designed to work with Laravel's validation errors.

Activity icon

Replied to Axios Patch Issue When Updating Model

Forms do not support put, patch or delete. Docs

So if you want to use CRUD operations you need the '_method' key.

Pro/cons would be your general CRUD or not arguments.

Sep
06
3 months ago
Activity icon

Replied to What Is The Best Approach To Get Pc Name Or Unique Identifier?

For security reasons you simply cannot get any identifying information beyond IP, the user agent and other lesser information.

Why not use a classic user authentication workflow? You can then identify one user from another based on their authenticated session.

Activity icon

Replied to UpdateOrCreate Need More Help Cleaning Code

I'll repeat my advice from your last question.

Use a trusted package like spatie's Laravel Sluggable. It will handle all of the creation, updating and duplication logic.

Activity icon

Replied to Clean Code For Request->all()

all() returns an array. So just use array_merge.

if (!$organizer = $organizer->updateOrCreate(array_merge($request->all(), ['slug' => str_slug($request->input('title'))]))) {
            return response()->json(['error' => 'Failed to save organizer'], 402);
        }

Personally I always use a package for slugs such as Laravel Sluggable. They handle everything.

Sep
04
3 months ago
Activity icon

Replied to Mail Not Finding Mail Class

No worries. We all make mistakes like that. Better to ask for help then bang your head against a wall for hours trying to figure it out.

Activity icon

Replied to Mail Not Finding Mail Class

class ContactMail extends Mailable
{

Your class is defined as ContactMail, not ContactUs. Change it to ContactUs.

Activity icon

Replied to Mail Not Finding Mail Class

Oh. You capitalized the S in Us.

\Mail::to('[email protected]')->send(new ContactUs($data));

If that doesn't fix it please provide the source of ContactUs.

Activity icon

Replied to Mail Not Finding Mail Class

Mail facade is in the global namespace. The call should be:

\Mail::to('[email protected]')->send(new ContactUS($data));

or add use Mail;

Activity icon

Replied to Sesssion Expiry Without Auth

You can include the csrf token in an ajax request by setting the X-CSRF-TOKEN header.

Documentation: https://laravel.com/docs/6.0/csrf#csrf-x-csrf-token

Activity icon

Replied to ErrorException: Trying To Get Property Talk_time Of Non-object

The items in your collection are arrays, not objects. Use array notation.

  $collection = $collection->filter(function ($item, $key) use ($limit) {
      return $item['talk_time'] > $limit;
  });
Aug
29
3 months ago
Activity icon

Replied to Linux Ubuntu: Set Permissions Before Creating New Project?

@5circles to edit your reply, hover over it and click the three horizontal dots at the bottom right. You'll find the edit option there.

Activity icon

Replied to Query Strings Dynamically Updates Inputs In Form

Add watchers to foo and bar and then push the new parameters to the router.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue Router - Testing</title>

    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
    <div id="app">
        <h1>Vue Router - Query string</h1>
        <hr>
        <input type="text" v-model="foo">
        <input type="text" v-model="bar">
    </div>

    <script>
        const routes = [
            { path: '/' }
        ];

        const router = new VueRouter([
            routes
        ]);

        const app = new Vue({
            router,     
            el: '#app', 
            data: {
                foo: 'foo', 
                bar: 'World', 
            }, 
            watch: {
              foo: {
                handler: function() { this.updateUrl() },
                immediate: true
              },
              bar: {
                handler: function() { this.updateUrl() },
                immediate: true
              }
            },
            methods: {
              updateUrl() {
                this.$router.replace({query: {foo: this.foo, bar: this.bar}})
              }
            },
            mounted() {
                console.log('ok');
                console.log(this.$router.query); // Returns me UNDEFINIED
            }
        });
    </script>
</body>
</html>

Note: I did not test this using vue-router's browser history mode. If I'm not mistaken, that would cause a page reload on every replace. If this is the case, you can use window.history to directly manipulate the history state.

Activity icon

Replied to Is The Update->request(all) With Token A Recent Thing?

The CSRF token has always been included in the request.

However, you shouldn't need to explicitly exclude the token in your update call. Unless there is a mass assignable column named _token in your model, the token is simply ignored.

Activity icon

Replied to Get Last Row From Activiy_log Per User

My mistake. janosk is correct.

return User::with([
                'groups' => function ($query) {
                    $query->select(['name']);
                },
                'sdinfo',
                'actions' => function ($query) {
                    $query->latest()->first();
                }
            ])
            ->get();
Aug
28
3 months ago
Activity icon

Replied to JQuery, How To Call A Function In On Click

Huh. Did not know you could add another selector in the jQuery on handler. Learn something new every day.

Activity icon

Replied to How To Show The Selected File In File Input

<template>
  <div class="custom-file">
    <input
      v-on:change="onImageChange($event)"
      type="file"
      accept="image/*"
      class="custom-file-input"
      id="profilePicture"
    />
    <label for="profilePicture" class="custom-file-label">{{ fileName ? fileName : 'Select image' }}</label>
  </div>
</template>

<script>
export default {
  name: "FileInput",
  data: {
    fileName: null
  },
  method: {
    onImageChange(e) {
      let files = e.target.files || e.dataTransfer.files
      if (!files.length) {
        this.fileName = null
      } else {
        this.fileName = files[0].name
      }
    }
  }
}
</script>
Activity icon

Replied to JQuery, How To Call A Function In On Click

Your click event is malformed. If you're targeting .brandCheckBox inside of #myDiv it would be as such:

$('#myDiv .branchCheckBox').on('click', function(event) { 
    // do something
});
Activity icon

Replied to How To Use Google Spreadsheet API In Laravel Commands?

This is over three years old but here's the solution:

Google_Client is in the global namespace so you either need to change the calls to new \Google_Client(); or add use Google_Client;.

Aug
27
3 months ago
Activity icon

Replied to Php Artisan Syntax Error

This can happen on servers managed with software like cPanel. Multiple versions of PHP are installed to allow different PHP versions on a per site basis. So even though phpinfo() (FPM) is on 7.x, the command line (CLI) is not necessarily the same version.

As a work around you can find out where the proper PHP 7.x CLI binary is and directly call that instead of the bash alias.

Activity icon

Replied to Applying A Middleware In The Authenticated Method In The Login Controller Does Not Work

If you're only logging their ip when they've logged in, just do it inside the authenticated method.

If you want to log their ip on every authenticated request then you would use middleware.

Activity icon

Replied to WithFaker Returns Null

You have to run the setUpFaker method.

namespace Tests\Setup;

use Illuminate\Foundation\Testing\WithFaker;

class ThreadFactory
{
    use WithFaker;

    public function __construct()
    {
        $this->setUpFaker();
    }

    public function create()
    {
    
        return ['name' => $this->faker->name];
    }
}

But why aren't you using the existing factory functionality? Faker is automatically injected into factories like so:

use Faker\Generator as Faker;
use App\Models\ChannelCategory;

$factory->define(ChannelCategory::class, function (Faker $faker) {
    return [
        'name' => ucwords($faker->unique()->words(rand(2,4), true))
    ];
});
Activity icon

Replied to Applying A Middleware In The Authenticated Method In The Login Controller Does Not Work

You are applying the middleware properly.

However, the guest middleware is also applied to authenticated and is run first. By default that middleware will redirect any authenticated user to '/home'. So your CheckIpAccess middleware doesn't get a chance to run.

Activity icon

Replied to Database Table Size And Structure Question

I don't see the need to create separate models just to reduce the number of columns. Relationships inherently cause performance hits because they make multiple database queries. Unless the information could be shared across multiple events (for example, an event that occurs more than once at the same place) there's no need for a separate model for something like the location of the event.

I do agree that the column names can be cleaned up to be more legible. Remove all 'event' prefixes. This is the events table so it's safe to assume the street address is the event's street address.

Activity icon

Replied to Cors Middleware Does Not Work On New Computer

I would recommend using Laravel CORS. It's still middleware (that's the best/only way to handle CORS) but i've never had an issue with this package.

Activity icon

Replied to Get Last Row From Activiy_log Per User

It looks like the relationship between a User and Activity is actions. You should be able to simply call last() to get the latest activity.

return User::with([
                'groups' => function ($query) {
                    $query->select(['name']);
                },
                'sdinfo',
                'actions' => function ($query) {
                    $query->last();
                }
            ])
            ->get();
Aug
26
3 months ago
Activity icon

Replied to Redirect Back WithoutQueryParameters ?

I don't think my answer is super unreadable, especially if you have a strong grasp of Laravel's helpers and regex.

Regardless we're discussing abstraction at this point which has countless implementations and is largely personal preference. I'd agree with both replies. If you intend to repeat this code, use a global helper. If it's scoped to this Controller/Model make a private function.

Or, maybe, make a Trait. Do you. Whatever feels comfortable. Either way that regex (or explode) and helper is still the best option and will still exist in your code base.

Activity icon

Replied to Redirect Back WithoutQueryParameters ?

You can access the previous url with url()->previous().

So, get that, strip the query params and redirect to it.

return redirect()->to(preg_replace('/\?.*/', '', url()->previous()));

Activity icon

Replied to TDD Json Patch Request With 2 Parameters

Your json call isn't defining the post model:

$this->json('PATCH', '/oath/post/status/'. 'publish' , $post)->decodeResponseJson();

You should use something like:

$this->json('PATCH', '/oath/post/status/publish/' . $post->id , $post)->decodeResponseJson();

Where id is whatever the route key is.

Also, if you name your routes you can use the route helper to form the url for you:

Route::patch('/oath/post/status/{publish}/{post}',['uses' => 'Backend\Oath\[email protected]', 'as' => 'post.status']);

$this->json('PATCH', route('post.status', ['publish' => 'publish', 'post' => $post->id]), $post)->decodeResponseJson();

And that way if you were to change the uri in your routes file, you won't need to change your test!

Activity icon

Replied to Axios Dosent Redirect.

You have to do something with the response in Javascript. Expanding on @sergiu17 example:

axios.post('url', {})
.then(({data}) => {
    alert(data.flash);
    window.location.replace = 'domain.dev/home';
})
.catch(error => {});

Since you're using an ajax call PHP is unable to redirect or flash messages. You have to do that on the client side or switch to a more traditional form POST action instead of ajax.

Activity icon

Replied to Laravel Excel Multiple Sheets With Heading

I'm not sure what the issue is then. Here's an example of multiple sheets with headings working in one of my projects. Maybe you can use it to compare/contrast and find the issue.

Controller:

...
$export = new ReportExport($data['data']);

return Excel::download($export, 'report.xlsx');

Parent sheet:

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class ReportExport implements FromArray, WithMultipleSheets
{
    protected $sheets;

    public function __construct(array $sheets)
    {
        $this->sheets = $sheets;
    }

    public function array(): array
    {
        return $this->sheets;
    }

    public function sheets(): array
    {
        $sheets = [
            new ReportGeneralExport($this->sheets['general']),
            new ReportLeadsExport($this->sheets['leads']),
            new ReportVideoExport($this->sheets['video'])
        ];

        return $sheets;
    }
}

Child sheet:

<?php
namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithMapping;

class ReportGeneralExport implements FromArray, WithHeadings, WithTitle, ShouldAutoSize, WithColumnFormatting, WithMapping
{
    protected $rows;

    public function __construct(array $rows)
    {
        $this->rows = $rows;
    }

    public function map($row): array
    {
        return [
            $row['name'],
            $row['impressions'],
            $row['clicks'],
            $row['ctr']
        ];
    }

    public function headings(): array
    {
        return [
            'Name',
            'Impressions',
            'Clicks',
            'CTR'
        ];
    }

    public function array(): array
    {
        return $this->rows;
    }

    public function title(): string
    {
        return 'General';
    }

    public function columnFormats(): array
    {
        return [
            'B' => '#,##0',
            'C' => '#,##0',
            'D' => NumberFormat::FORMAT_PERCENTAGE_00
        ];
    }
}

Hope this helps.

Activity icon

Replied to Laravel Excel Multiple Sheets With Heading

Ohhhh. Apologies. Misunderstood your issue. Thought you meant title of the worksheets, not column headings.

So rephrasing of my first question, are you implementing WithHeadings in the child classes?

Activity icon

Replied to Laravel Excel Multiple Sheets With Heading

That all looks correct assuming your use and implements are there.

The sheets are generated just not named correctly right? What are the sheets being named?

Activity icon

Replied to Laravel Excel Multiple Sheets With Heading

Can you show your code for the parent sheet and one of your children sheet classes?

Activity icon

Replied to Laravel Horizon: Recurring Allowed Memory Size Exhausted Exception

Not sure this would be the issue but do you have 512MB+ on your server? 512MB is an awful lot to dedicate to each worker.

If you lower this, or leave it undefined, does the issue still occur?

Activity icon

Replied to Laravel Horizon: Recurring Allowed Memory Size Exhausted Exception

Looks like one or more of your jobs are using too much memory.

You can increase the PHP memory limit to fix this. However, it would be better to refactor your job to use less memory.

Activity icon

Replied to Laravel Excel Multiple Sheets With Heading

Are you implementing WithTitle in each of your Spreadsheet classes?

See this example from the dos: https://docs.laravel-excel.com/3.1/exports/multiple-sheets.html#sheet-classes

Activity icon

Replied to How To Increment A Value In Users Table When User Change The Password

Probably the most reasonable place is wherever you have your user update logic (Controller, Model, Repo, etc.)

public function update(UserUpdateRequest $request, User $user)
{
    $data = $request->all();

    if(!\Hash::check($data['password'], $user->password)){
        $data['password_changed_count'] = $data['password_changed_count']++;
    }

    $user->update($data);

    ...
}

Make sure you hash the new password correctly before updating the User.

You could also do this login in an Event or an Observer watching for the updating event on the User model.

Activity icon

Replied to Axios Dosent Redirect.

You also can't/shouldn't use ->with() with a json response. You should define whatever messages inside the response itself:

return response()->json(['flash' => 'Bókun þín hefur verið gerð!']);
Aug
23
3 months ago
Activity icon

Replied to A Tag Have Href And Click Event.

Do you own and control "netgreidslur.korta.is"?

If so, then try laravel-cors instead of custom middleware.

If not, you'll want to make the request to your backend which itself makes the call to netgreidslur.korta.is to avoid CORS issues.

Activity icon

Replied to With Vue-form-wizard Define If Capture Is Clicked?

I believe defining the footer slot should work for you. You can apply a disabled attribute here.

<template slot="footer" slot-scope="props">
  <div class="wizard-footer-left">
      <wizard-button  v-if="props.activeTabIndex > 0 && !props.isLastStep" @click.native="props.prevTab()" :style="props.fillButtonStyle">Previous</wizard-button>
  </div>
  <div class="wizard-footer-right">
    <wizard-button v-if="!props.isLastStep"@click.native="props.nextTab()" class="wizard-footer-right" :style="props.fillButtonStyle">Next</wizard-button>

    <wizard-button v-else @click.native="alert('Done')" class="wizard-footer-right finish-button" :style="props.fillButtonStyle" :disabled="!is_recaptcha_verified">  {{props.isLastStep ? 'Done' : 'Next'}}</wizard-button>
  </div>
</template>

As side note make sure you are verifying the response from vue-recaptcha with Google's API and your private key. It is not enough to merely accept the response from vue-captcha. It needs to be verified by the recaptcha API.