tykus

tykus

Full Stack PHP Developer at Linked FInance

Dublin

Member Since 4 Years Ago

Experience Points 732,280
Experience
Level
Lessons Completed 1358
Lessons
Completed
Best Reply Awards 1121
Best Answer
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.

12 Nov
1 day ago

tykus left a reply on Filtering And Reducing A Collection

'component.value' is a string

tykus left a reply on Filtering And Reducing A Collection

You have a QEC value for one component - if this is not expected, then you need to modify the query:

$value = ComponentsModel::with(['component' => function ($builder) {
    return $builder->where('cat', 1);
})->where('model_id', $this->id)->get();

Your eager-loaded components might be null in some circumstances, you should mitigate property of a non-object errors by using the optional() helper:

$cat1 = $value->filter(function($v) {
    return optional($v->component)->cat == "1";
})->;

To get the sum, you can simply chain ->sum(component.value) (if that is the property you want to sum.

Is it coincidence that all of the records have the same orderId?

11 Nov
2 days ago

tykus left a reply on Unlink File When Parent Deleted

You can pluck the paths from the jobs to be deleted - therefore needing only two queries:

\DB::transaction(function () {

    $builder = Job::whereIn($id, explode(',', $request->ids); // this is a builder instance

    $filesToDelete = $builder->pluck('filepath');   $builder->delete(); // this is a Collection of file paths

    foreach($filesToDelete as $file) {
        unlink($file);
    }

    $builder->delete(); // deletes the records
});

tykus left a reply on Scheduled Task To Update Model Status

What stage is the Tender at between 09:00 and 09:01?

tykus left a reply on Catch When An Email Address Is Wrong

I don't use Sparkpost, but expect you can get Sparkpost webhook events https://www.sparkpost.com/docs/tech-resources/webhook-event-reference/. You will need to find a property to link the webhook to an email message your system sends.

Be aware, if the email address provided by the customer is incorrect, but is valid and exists (i.e. someone else's email address), then you will not know there was an issue.

09 Nov
4 days ago

tykus left a reply on Choosing Best Reply Leeds To A 404 Page

It's feedback for Laracasts @

08 Nov
5 days ago

tykus left a reply on Asset Conversion

asset() will only generate a URL, the rest of the HTML is up to you:

<link rel="stylesheet" href="{{ asset ('css/style.default.css') }}" id="theme-stylesheet">

tykus left a reply on Get Value Of Id In Constructor Of A Model

Seems like you have a self referencing belongsTo relationship, i.e. a unit belongs to a base unit _a kg belongs to a g_.

You can always eager-load the base unit by specifying a $with property on your model:

// Unit.php

class Unit extends Model
{
    protected $with = ['baseUnit'];

    public function baseUnit()
    {
        return $this->belongsTo(Unit::class, 'base_unit_id');
    }
}

You will be able to get to the base_unit property from the relationship on any model instance, (albeit some might be null if unassigned).

If you like this, then the retrieved model event approach suggested previously is unnecessary. Otherwise, when you want to work with an instance, you should do that additional work in the model event Closure rather than in the constructor.

tykus left a reply on Vue: Add Css Class On Click To Non-dinamic Navbar

There is no jQuery in my reply; that is vanilla javascript.

tykus left a reply on Duplicate The Best Answer.

The best answer is always duplicated after the question; it happens that the first answer is the best, so appears directly after the duplicate. This would not be so jarring if the best reply was later in the thread.

tykus left a reply on Get Total Amount Of Users.

That';s not a very efficient solution. You can get the count directly in a query rather than instantiating object for every user record and then counting the resulting collection:

$countUsers = User::count();

tykus left a reply on Laravel Development Package

What is the error? Anything to do with the invalid / in the namespace; should be \.

If Job and JobReq are in the same namespace; then you do not need the fully qualified class name.

public function jobreqs()
{
    return $this->hasMany(JobReq::class);
}
07 Nov
6 days ago

tykus left a reply on Model Stripping URL In Function

Did you know you can fallback to another service like uinames.com; it would save you a lot of work? The d query string parameter will use UINames if Gravatar does not have a result for the email hash. You need to urlencode the fallback when it is a URL:

public function getAvatar()
{
    $hash = md5($this->email);

    $gravatarUrl = ;https://www.gravatar.com/avatar/{$hash}';
    $fallbackUrl = urlencode('https://ui-avatars.com/api/?name=' . $this->firstname . '+' . $this->lastname);

    return $gravatarUrl . '?d=' . $fallbackUrl;

Now there is no need for requests and HTML in your model, only a URL string will be returned.

tykus left a reply on Issues With JSON Response From API - Object Not Array

@cronix the OP expects a sheets key in the response, that is the incorrect key to remove.

tykus left a reply on Issues With JSON Response From API - Object Not Array

You are returning nested associative arrays, these become JSON objects. If you want a JSON array, then remove the key!

tykus left a reply on Vue: Add Css Class On Click To Non-dinamic Navbar

You can get the current uri from the window:

$uri = window.location.pathname

Not Vue-related really, just match it with the href on the link to set an active class:

document.querySelectorAll('.nav-link').forEach(function (link) {
    if (link.href == window.location.pathname) {
        link.classList.add('active');
    }
})

tykus left a reply on How To Save Id In On Checkbox?

I decided to save id to show the infraction

What do you mean by this; eager-loading the Infraction?

I suggested a pivot table days ago... it fell on deaf ears.

tykus left a reply on Add Items To Beginning Of Collection

not sure if that makes sense?

It does not.

i need an external index or array of $productsAtBeginning for each query

You want those $productsAtBeginning at the top of every page of results???

tykus left a reply on Add Items To Beginning Of Collection

Just add a column to promote those records to the top. For example, add a sort_order column and give those records a higher priority that the other records.

$product = Product::orderBy('sort_order')->paginate();

tykus left a reply on How To Save Id In On Checkbox?

Did you cast the infraction_id property to array on the Model?

protected $casts = [
    'infraction_id'
];

Once this is done, Laravel will serialize the array when saving, and unserialize on retrieval.

tykus left a reply on Get Value Of Id In Constructor Of A Model

What happens when there is no id i.e. when the model instance has not come from the database. Your model class will not always be a representation of an actual record.

You can hook into the retrieved event to do stuff with a retrieved instance instead:

public static boot()
{
    parent::boot();

    static::retrieved(function ($model) {
        var_dump($model->id);

        // now you will actually have a Model instance with an id
    });
}

tykus left a reply on Display Created_at From Pivot

AFAIK, you can only access these timestamps throught the pivot property; you could add an accessor method on the User class:

public function getAddedToGroupAttribute()
{
    return optional($this->pivot)->created_at;
}

And add added_to_group to the $appends property on the User model:

public $appends = [
    'added_to_group'
];

I suppose Eloquent will export an array to build the Excel file, so this will include the pivot created_at whenever it is available

tykus left a reply on Display Created_at From Pivot

Do you have withTimestamps() on the relation?

You can get the pivot timestamps thru the pivot object:

$student->pivot->created_at

tykus left a reply on Vue: Applying Css Class If Condition Is Met

You need v-bind:class; which you can use in addition to a regular class

If you depend of the truthiness of activeIndex, then:

<span class="slider_dots_dot"
    v-for="slider in slidersCount"
    :key="slider"
    :class="{'your-css-class: activeIndex}"
    @click="goToSlider(slider)"
>
</span>

or if the activeIndex is the name of the CSS class you want applied:

<span class="slider_dots_dot"
    v-for="slider in slidersCount"
    :key="slider"
    :class="activeIndex"
    @click="goToSlider(slider)"
>
</span>

tykus left a reply on A Comma In The Data Prevents A SQL Insert In Laravel

Disregard the lack of quotation marks, they do not appear in the error message, but are included in the built query.

The warning is actually for truncated data - it doesn't like 29-11-04. Do you have a length on that column that is shorter than 8 characters?

tykus left a reply on Customizing An Error Message

Just create a new middleware in the app/Http/Middleware directory, giving it the same (or very similar) as the Laravel one you are replacing.

Copy the Laravel implementation into your new middleware, changing the Exception message.

Lastly, update the route middlewares mapping in app/Http/Kernel.php from the Laravel class to yours.

tykus left a reply on Homestead Question, About Port 3306/33060

Your port is still incorrect

tykus left a reply on Homestead Question, About Port 3306/33060

If you do not have a local MySQL instance, you can set the envrioment varaiableDB_HOST=192.168.10.10 and use DB_PORT=3306 allowing you to use Tinker, Artisan etc. on the host but using the VM.

tykus left a reply on Query Builder Issue

Ok, and there is a state column in the states table which is the same type as the incoming $request->state?

tykus left a reply on Query Builder Issue

Is state a relation on the City model; whereHas checks for the existence of a relation to scope the parent (City) query?

If state is a column on the cities table, then the query should be:

if ($request->has('state')) {
    $city->where('state', $request->state);
}

tykus left a reply on Exclude Result When The -with- Statement Is Null

In this case there is no need to the line ?

You still will need that constraint to only eager-load lines that are not private.

tykus left a reply on Customizing An Error Message

This is hardcoded in the EnsureEmailIsVerified middleware, and since this is in the vendor directory is not advisable to change it.

I would suggest re-implementing the middleware in your App\Http\Middleware namespace and changing the mapping in the $routeMiddleware array in your app\Http\Kernel.php file to point instead to your implementation.

06 Nov
1 week ago

tykus left a reply on Export To Excel

Ok. Am curious about the ambiguous id...

What SQL query is actually being run?

tykus left a reply on Export To Excel

students is a relation, right? What SQL query is actually being run?

tykus left a reply on Export To Excel

That query doesn't need a where - it is already scoped using the $group model instance:

$group->students; // ()->where('group_id', '=', $group->id)->get();

tykus left a reply on Take Only One, Latest Row For Each Element In (whereIn) Array

Yes, that will work, but you will get a collection of users each with their most recent site as a property; you will simply need to map over that Users Collection in Laravel to get the Site collection that you originally needed in the OP.

tykus left a reply on View Composer:sharing Data With All Views Like

Would something like this even work?

Yes.

tykus left a reply on Exclude Result When The -with- Statement Is Null

This is a case for whereHas:

$response = station::select('id', 'name', 'label', 'address', 'longitude', 'latitude', 'active', 'line_id')
    ->where('active','=',1)
// startWhereHas
    ->whereHas('line', function ($q) {
        $q->where('private', '=', 0);
    })
// endWhereHas
    ->with(['line' => function ($q) {
        $q->select('id', 'name', 'label', 'number', 'url');
        $q->where('private', '=', 0);
    }
    ])
    ->whereRaw($sql_statement, [
        $from_location[0],
        $from_location[1],
        $from_location[0],
    ])
    ->take(config('parameters.numberOFresultsTOtakePERsearch'))
    ->get();

tykus left a reply on Take Only One, Latest Row For Each Element In (whereIn) Array

If I understand what you are looking to achieve, then eager-loading is not applicable; instead you want a query like the following:

SELECT *, MAX(created_at)
FROM sites
WHERE client_id IN ( /* $clientIds */)
GROUP BY client_id;

In Eloquent, it would be:

Site::selectRaw('*, MAX(created_at)')
    ->whereIn('client_id', $clientIds)
    ->groupBy('client_id')
    ->get();

tykus left a reply on List From Database With Links To Other Pages

So my link would then have the module id

Yes, or a slug... anything that would identify the individual module instance.

I don't know why you are showing redirect responses now when your were making links previously?

You can use a single generic action to handle the requests as well; there is no requirement to have an individual controller action for each id like you are showing here:

return redirect()->action(
    '[email protected]', ['id' => 1]
);

tykus left a reply on Take Only One, Latest Row For Each Element In (whereIn) Array

What is the relationship between Site, Client and Log(?) models?

tykus left a reply on Fetch Data And Populate In Text Boxes If Selected Dropdown Option

@partabsaifzakir I have just reread the edited OP, and noticed that the data on the component assigns a new Form to the form key... we were not replicating this when the response was returning from the database:

axios.get('api/ticket-invoice/' + this.selectedTicketInvoiceId)
    .then(({data})=> {
        this.form = new Form(data) 
        // ensure response data match the keys in the component's data.form property
    })
     // ...

tykus left a reply on List From Database With Links To Other Pages

If you want to go to different pages, then your href attribute should be different for each module in the Collection - this might be a URI segment:

 @foreach($modules as $module)
    <tr>
        <td><a href="/module/{$module->id}/listings/create">{{$module->modules}}</a></td>
    </tr>
@endforeach 

or a query string:

 @foreach($modules as $module)
    <tr>
        <td><a href="/listings/create?module=$module->id">{{$module->modules}}</a></td>
    </tr>
@endforeach 

Depending on the approach you choose to take, you will need to modify your routes, or otherwise, get the $moduleId from the request object.

tykus left a reply on Error2 Migration

Is it possible you have a separate migration which also attempts to define the unique index?

tykus left a reply on Difference Between Query()->where() And Where() ?

As mentioned earlier, the query() method just gives you a Builder instance to begin the process of creating a query - in the example User::query()->where(), it adds nothing really as the where method will return a Builder instance anyway.

Whenever you want to conditionally add terms as @Snapey mentioned, you can also use the when method:

$query = User::when($request->name, function ($q) use ($request) {
        $query->where('name',$request->name);
});

tykus left a reply on Dropdown List

Is there a locations property on the Location model; what is it, string, int???

Right now it is not putting anything in

Anything including the other fields on the form? Are you sure that you are POSTing to that controller method?

tykus left a reply on Forge Not Adding Full Github Repo

The .env file is typically not included in your Git repo for reasons of security of your various credentials.

The vendor directory is a side effect of running composer install - based on either the composer.json or composer.lock files, it contains all of the dependencies that your app needs, and can be created whenever you deploy your project. A deploy script will comprise the commands necessary to (i) pull the code (if you are not using webhooks) and (ii) run any deployment commands including composer install and perhaps npm run production.

tykus left a reply on Stranger Things - Create Item In Pivot Table But Get An Error

The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining

public function participants()
{
    return $this->belongsToMany('App\EventUser', 'event_users', 'event_id', 'user_id');
}