Digitalized

Digitalized

Member Since 10 Months Ago

Newcastle upon Tyne

Software / Web Development at Digitalized Ltd

Experience Points 34,990
Experience Level 7

10 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 260
Lessons
Completed
Best Reply Awards 14
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.

08 May
1 month ago
25 Apr
2 months ago

Digitalized left a reply on Querying Model Based By Two Different Pivot Tables

Assuming you have an equipment relationship set up on your exercise table, try chaining an extra wherehas call onto your statement eg.

$exercises = Exercise::whereHas('bodyparts', function ($q1) use ($bodypartIds) {
    $q1->whereIn('id', $bodypartIds);
})->whereHas('equipment', function($q2) use ($equipmentIds) {
    $q2->whereIn('id', $equipmentIds);
})->get();

Hopefully that will give you what you want

18 Apr
2 months ago

Digitalized left a reply on Select With Over 10.000 Records

Are you using any JS frameworks for your front end? eg. jQuery, Angular, Vue js? Each framework will have its own popular implementations of a typeahead

17 Apr
2 months ago

Digitalized left a reply on Return ID From UpdateOrInsert Laravel Query Builder

@cronix reply seems to be the most sensible to me if you want to use the updateOrInsert method

Of course you could always use the updateOrCreate method instead, which returns the updated/created model. If you are using an auto-increment ID in your database table and you are not specifying the ID in the data array, then I don't think there's any reason to use updateOrInsert

Digitalized left a reply on Return ID From UpdateOrInsert Laravel Query Builder

Unlike updateOrCreate which returns the updated model, updateOrInsert just returns a boolean response. If you want to get the last inserted ID, you can do the following just after your query:

$last_id = Illuminate\Support\Facades\DB::getPdo()->lastInsertId();
18 Mar
3 months ago

Digitalized started a new conversation Best Practice For Structuring App.js File

Hi all,

I have a question about best practice (or at least sensible practice) with regards to structuring an app.js file within Laravel.

In the past I included js files separately in my main template, each dealing with various parts of my application. However having recently watched one of Jeffrey's tutorials on Webpack, I am now looking to have a single app.js file for my project.

There are a fair few guides to using Webpack in Laravel, but I'm struggling to find some examples of the app.js file itself - with respect to a real-world project.

My webpack.mix.js file is currently configured like so:

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

mix.js([
    'public/js/src/app.js'
], 'public/js/dist/app.js').version();

..and my app.js file in the src directory like this:

import Activities     from '../activities/activities.js';
import AddressFinder  from '../address/address-finder.js';
import ChartManager   from '../analytics/analytics.js';
import ImportUsers    from '../import/import-users.js';
import Confirm        from '../alerts/confirm.js';
import Toaster        from '../alerts/toaster.js';
import Modal          from '../alerts/modal.js';
import Api            from '../api/api.js';
import ChangeLanguage from '../language/change-language.js';

global.Activities     = Activities;
global.ChartManager   = ChartManager;
global.ImportUsers    = ImportUsers;
global.Confirm        = Confirm;
global.Toaster        = Toaster;
global.Modal          = Modal;
global.Api            = Api;
global.AddressFinder  = AddressFinder;
global.changeLanguage = new ChangeLanguage;

The public/js/dist/app.js file is the only file I include in my main view template;

In my src/app.js file I am importing any classes my views need to access globally, each of these main classes may include private classes from other files, as required.

In your experience, is this a good structure? Are there better ways of doing this?

One thing i'm not 100% sure about with this approach is how I can load scripts ad-hoc, for example, admin scripts shouldn't really be loaded by general users, etc.

I guess when everything is minified and packed this might not be so much of an issue, but it's something i'm wondering about, and whether I can add some conditional statements to fix this.

Thanks and look forward to hearing your advice, Paul

30 Jan
4 months ago

Digitalized left a reply on Array To String In Laravel

You will get better responses if you explain the problem in more detail and post some example code so people can understand the context

Digitalized left a reply on How To Increase New Visitors?

There are lots of ways to do this. Improving your website's SEO, advertising through Google Ads, paid advertising, social media, are just some of them. It just depends on your needs.

In my experience getting your website address listed on other websites is a free and effective way of generating extra website traffic. In order to do that, you need to give others a compelling reason to visit your site though!

If you want to increase traffic on a shoestring budget then social media, blogs, improving SEO, and generating back-links from other websites is a good way to go.

If you already have existing users, then you may want to look into how to improve your websites viral coefficient, in other words, how easy and likely it is for a website visitor to share your website with their own friends or network. There's a good book called Viral Loop by Adam L Penelberg which I recommend reading. Again though, this really depends on the type of website you have.

If you have money to spare then advertising can also be very effective. The advertising platform you choose will naturally depend on the type of website you have and the target market you want to reach, but you might look at Google Ads or Facebook advertising for example.

29 Jan
4 months ago

Digitalized left a reply on Disable Exception Handling In Laravel Tests

After adding:

$this->withoutExceptionHanding();

within your test, try adding ->getContent() and echoing the response or ->dump() to your phpunit json call. Either of those might help identify the issue

Digitalized left a reply on Import Model Without Namespacing It

Assuming all namespaces are the same, you will need to append the namespace to the start of the model name eg.

$class = 'App\' . $model;

// Then you should be able to call like this:

$modelTest = $class::all();

22 Jan
5 months ago

Digitalized left a reply on Calculating Review Scores

@SPEEDYDAN - Great stuff, glad to hear it worked! :)

21 Jan
5 months ago

Digitalized left a reply on Calculating Review Scores

I think I have a better understanding of your problem. One way to do this would be to get your listing model to use a custom collection, then add a method to return just the listings with the highest review average. eg


class Listing extends Model {
    
    public function reviews()
    {
        return $this->hasMany(Review::class)
    }


    public function avgScore():float
    {
        return $this->reviews->avg('overall_score');
    }
    
    
// Adding this method means when you create any sort of listing collection, your custom listings collection will be returned, rather than the regular Collection class - dont forget to include the namespace
    public function newCollection(array $models = [])
    {
        return new Listings($models);
    }

}


class Listings extends Collection {
    

    public function topTen():Collection
    {
        return $this->sortByDesc(function($listing) {
            return $listing->avgScore();
        })->take(10);
    }

}

Digitalized left a reply on Calculating Review Scores

Ah I understand

How is the overall_score calculated?

Digitalized left a reply on Calculating Review Scores

As for working out the "average" - a collection has an "avg" method. So you could try the following:

$average = $listing->getTopReviews()->avg('overall_rating');

Digitalized left a reply on Calculating Review Scores

Apologies, I meant to say "in your model" not "in your controller" - I've updated my original answer!

Digitalized left a reply on Calculating Review Scores

You could maybe try something like this in your controller?

public function topReviews()
{
    return $this->hasMany(Review::class)->orderBy('overall_rating', 'desc');
}


public function getTopReviews($n=10)
{
    return $this->topReviews->take($n);
}

14 Jan
5 months ago

Digitalized left a reply on What Does MorphTo Actually Do?

"MorphTo" is used to define the relationship from a one-to-one or one-to-many polymorphic table to whichever model or models it is linked to

https://laravel.com/docs/5.7/eloquent-relationships#one-to-many-polymorphic-relations

For example, lets say you had an Address model

One or more models could link to the same addresses table / model, via an addresses relationship. eg.

class User {

    public function addresses()
    {
        return $this->morphMany('App\Address', 'addressable');
    }

}


class Provider {
    
    public function addresses()
    {
        return $this->morphMany('App\Address', 'addressable');
    }

}

// Conversely, the address model can link back to the User or Provider model (the polymorphic part) 

class Address {

    // This could link to either a provider or a user!
    public function addressable()
    {
        return $this->morphTo();
    }

}

This means you can have a single addresses table for both users or providers, rather than one address table for users, one for providers, etc.

Hope that makes sense 
11 Jan
5 months ago

Digitalized left a reply on How To Get Monthly Users Month By Month For A Table

I would check that your series array is in the correct format - I had a quick look at the chartlist.js api docs and it is expecting an array of arrays.

I would maybe try json encoding the users object, then mapping over it and creating an array of arrays, rather than mixing javascript and php as you have done - which I suspect may be the issue.

09 Jan
5 months ago

Digitalized left a reply on How To Get Monthly Users Month By Month For A Table

Glad to help,

If my answer resolved your issue, please mark my answer as the accepted answer

Wrt the month format, you can apply a carbon method to get the format you need. You can access Carbon directly in the view like so:

Carbon\Carbon::parse($key)->someMethodName()

See the Carbon documentation for list of available formats

https://carbon.nesbot.com/docs/

Digitalized left a reply on How To Get Monthly Users Month By Month For A Table

@LAWKUNCHI - If you used the group by method on the collection I suggested, then you should be able to echo the count like this in the view:

@foreach($users as $key => $group)
    <tr>
                <td>{{ $key }}</td>
                <td>{{ count($group) )}</td>
          </tr>
@endforeach

Digitalized left a reply on How To Get Monthly Users Month By Month For A Table

@ROBOROBOK - I agree that filtering the collection will be slower, but depending on the use case and number of records, it may be of no concern.

Your suggestion of adding a clause on the database query would certainly be faster - but I think using a group by on the collection might be a bit easier for a novice to understand, and is easy to just add onto the end of an existing query.

There are pros and cons I guess

Digitalized left a reply on How To Get Monthly Users Month By Month For A Table

I don't know what your user query looks like, but one way to do this would be to group the collection, it wont be as efficient as a direct database query but should do the job!

You could try something like this (please note that you'll need to change the query to suit your purposes)

use Carbon\Carbon;

// Change the first part of the query below as required
User::get()->groupBy(function($user) {
    return Carbon::parse($user->created_at)->format('m');
});

Another way to do this would be to apply a group by query to the database query itself as RoboRobok suggested
05 Jan
5 months ago

Digitalized left a reply on Pulling Data From Table Based On ID

I think you have a typo in your view.

I assume it should be $user->name_first rather than Users::name_first

Digitalized left a reply on Pulling Data From Table Based On ID

Here's a useful article on route model binding which you should have a read through

https://laravel.com/docs/5.7/routing#route-model-binding

Digitalized left a reply on Pulling Data From Table Based On ID

Looks like you aren't passing the single user back to the view, try this instead

$user = User::findOrFail($id);

return view('profile', compact('validations', 'user', 'availability');

Then you just reference the $user object in the view.

Ps. as an aside - you may also want to look into Method model binding - as it will save you having to do the find or fail step in the controller

02 Jan
5 months ago

Digitalized left a reply on Problem Saving Repeated Array

Can you provide more details about the changes you are making? eg. do you want to update specific properties or values? Some additional context would be useful

31 Dec
5 months ago

Digitalized left a reply on Getting Ajax Undefined Response

Glad that sorted your issue!

I guess the $.ajax function is looking specifically for the string 'json'

:)

Digitalized left a reply on Grouping Routes

Ah snap, I just noticed that!

Digitalized left a reply on Grouping Routes

Just a guess - but I wonder if the following line could be causing issues - seeing as there appear to be two routes defined with the same url

/manager/

//Benefits
 Route::get('/', 'Manager\[email protected]')->name('benefit.index');

You could try commenting this line out and seeing if that sorts the issue

Digitalized left a reply on Getting Ajax Undefined Response

I wonder if the data is not being parsed correctly.

Try changing the dataType to 'json' (lowercase) - failing that - as a test you could add the following line just inside of your success function:

var data = JSON.parse(data);
console.log(data.Title);

Digitalized left a reply on Grouping Routes

Have you tried running php artisan route:list to see what routes have been registered?

30 Dec
5 months ago

Digitalized left a reply on Hey! Admin Something Isn't Right Here

I noticed the same thing myself today - I'm located in UK in case its a time zone issue - hope that helps

Digitalized left a reply on Barcode

I would try this package

https://packagist.org/packages/werneckbh/laravel-qr-code

I used it in a recent project, its really easy to install using Composer and to generate a QR code - and the API is simple and clear. Instructions on the GIT page

Hope that helps Paul

27 Dec
5 months ago

Digitalized started a new conversation Suggestion For New Browse Filter

Hi Jeffrey,

I often use the "Browse" part of the site to find lessons to watch - and usually watch lessons in an ad-hoc fashion.

However some days I want to methodically work my way through any lessons I haven't yet watched, to continue my learning and fill gaps in my knowledge.

In the latter case, I would find it very useful if there was a filter to show lessons I haven't yet watched. I am sure others would also find this useful.

Hope this request reaches you well, and love the site,

Paul

14 Dec
6 months ago

Digitalized left a reply on How Can I Share An Object Instance Between Two Controllers?

@zak always learning :) Thanks again, hope I can repay the favour sometime!

Digitalized left a reply on How Can I Share An Object Instance Between Two Controllers?

Thanks @zak I understand now!

I'm just getting to grips with the service container a bit more, really appreciate the advice, I'll refactor my code

Digitalized left a reply on How Can I Share An Object Instance Between Two Controllers?

Yes, exactly that.

The first controller show method is used to show the form where questions are listed to the user.

The second controller assess method is called when the answers are submitted.

I could quite easily move everything into one controller, but as it stands I have two controllers as the assess method saves answers against the user record so it made sense to separate the two.

Digitalized started a new conversation How Can I Share An Object Instance Between Two Controllers?

Hi all,

Please can someone suggest a good way to share the same object between two controllers? I'm scratching my head trying to come up with a good solution

Here is my issue:

I have an application where users can undertake question-based assessments.

The assessment comprises questions specific to the assessment, and the questions are randomly generated. The process is two parts - firstly the user is presented with some questions, secondly, they submit their answers and those same questions must be marked.

I have attempted to save my assessment object instance into the service container (as a singleton) in the first controller, then access it via the second controller - however it cannot be resolved the the service container

I assume this is because of where I am registering the singleton and its scope

My reason for going down the singleton route - when I create an assessment I want the questions to be "locked in" for the duration of the assessment, so I thought it a singleton might be a good pattern in this case


// Controller 1  

// A new assessment is instantiated via AssessmentFactory::lessonAssessment

// When the questions() method is called the first time, some random questions are chosen from a wider pool of questions. The method uses lazy loading, so each subsequent time the questions method is called, the exact same questions are returned.

public function show(Course $course, Unit $unit, Lesson $lesson):View 
{
    $lessonAssessment = AssessmentFactory::lessonAssessment($unit, $lesson);

    // I have tried the following as a test!
    app()->singleton('lesson_assessment', function() use ($lessonAssessment) {
        return $lessonAssessment; 
    });

    $questions = $lessonAssessment->questions();
        
    return view('lesson_show', compact('course', 'unit', 'lesson', 'questions'));
}


// Controller 2

// This controller should retrieve the same lessonAssessment instance created in the first controller and then mark the user answers which were stored in the session as the user answered each question.


public function assess(Unit $unit, Lesson $lesson):RedirectResponse
    {

        // The line below throws a ReflectionException ("Class lesson_assessment does not exist") - so Laravel is unable to resolve it out of the service container!

        // $lessonAssessment = resolve('lesson_assessment');
        
        // some other logic here which performs the assessment
    
    }

Any advice would be appreciated!

26 Sep
9 months ago

Digitalized left a reply on Splice Method Issue

Apologies, I've just tested this myself and it seems like it is possible to omit the second parameter as you have done, and simply provide the index

The first splice parameter should be an index value, if you console log this.current_event, is that the case?

25 Sep
9 months ago

Digitalized left a reply on Blade Null Coalesce Doesn't Work

Try this instead

{{ $title ?:  'Default page title' }}
24 Sep
9 months ago

Digitalized left a reply on Uploading Images Scenario

Sorry I'm not sure what your question is - what do you mean when you say "is that being used mostly"?

I use polymorphic relationships for Images in a couple of my projects and it works well for me - but may not be well suited to your own application.

As for your last paragraph, I'm also a little bit lost sorry - it sounds like you may have answered your own question?

Digitalized left a reply on How To Print Table Column Values Count Numbers With Relationship Table Values?

FYI, another solution might be just to add an accessor on the model which gets a count of the relation

Digitalized left a reply on How To Print Table Column Values Count Numbers With Relationship Table Values?

Since you want to access data mostly from the categories table, rather than the vehicles table, maybe try switching the order of the tables around in your query and then grouping by vehicle so you can get the aggregate sum of vehicles per category.

I'm a bit confused as to why you have categoryname on both tables, as this would seem superfluous on the vehicles table. In any case, my query below assumes you have a category_id field on the vehicles table (I assume that's the case based on your relationships)

Anyway you could try something like this:

$query = Category::select('id', 'categoryname', 'images', \DB::raw('COUNT(vehicles.id) as cnt'))
                 ->leftJoin('vehicles', 'vehicles.category_id', '=', 'categories.id')
                 ->groupBy('id')
                 ->get();  

This code is just an example and is untested - so I suggest you try this yourself to see if it gives you what you want, and tweak it if necessary.

Digitalized left a reply on How To Print Table Column Values Count Numbers With Relationship Table Values?

@Msoft Not unless you can provide more details about exactly what you are trying to achieve

Digitalized left a reply on How To Print Table Column Values Count Numbers With Relationship Table Values?

The outer loop gives you access to the category data, the inside loop gives you access to the vehicles data. Is the issue that you need to print in a different format?

If you need all data in one line and one loop, then a join may be the way to go. You can learn about joins here: https://laravel.com/docs/5.7/queries#joins

Digitalized left a reply on How To Print Table Column Values Count Numbers With Relationship Table Values?

I would probably go with a nested foreach loop as it means you can still access any model methods that you decide to add later on. eg.

@foreach($names as $name)
    {{ $name->categoryname }} ({{ $name->cnt }})
    @foreach($name->vehicles as $vehicle)
        // do whatever you need to with vehicles here
    @endforeach
@endforeach 

Digitalized left a reply on How To Print Table Column Values Count Numbers With Relationship Table Values?

You would either need to create a second loop inside the $names foreach loop - and loop through $name->vehicles. Or you would need to modify your $names query in the showcategoryname method, to join to the vehicles table

Digitalized left a reply on Htmlspecialchars() Expects Parameter 1 To Be String, Array Given

The error seems self explanatory, can you provide the code where it is failing to give some context?