martinbean

martinbean

Senior Developer at Visualsoft Ltd

Member Since 5 Years Ago

Newcastle upon Tyne, UK

Experience Points
529,115
Total
Experience

0 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
532
Lessons
Completed
Best Reply Awards
708
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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 50
529,115 XP
May
30
1 day ago
Activity icon

Awarded Best Reply on How To Deal With Mandatory Properties Of An Object.

@isarantoglou Congratulations, you’ve discovered domain models and the concept of invariants and integrity :)

If you have an entity in your application then you want a class that represents that entity, and with which only valid entities can be constructed. So you’re right in thinking about the constructor, but I wouldn’t overload the constructor of an Eloquent model.

This is getting into Domain-Driven Design territory, but you would have a “POPO” (plain ol’ PHP object) that represents an entity. So in your example, a Book. Your Book entity class should have a constructor that takes the required arguments needed to initialise a valid instance of itself:

class Book
{
    public function __construct($title, $author, $isbn)
    {
        $this->title = $title;
        $this->author = $author;
        $this->isbn = $isbn;
    }
}

The best things about classes like this is, you can create value objects representing other things in your application. For example, an author could be elevated to a class of its own. So you could then tell your Book class that it needs a valid Author instance to be passed for the $author argument, rather than any value:

class Book
{
    // Only allow books to be created with a valid author instance
    public function __construct($title, Author $author, $isbn)
    {
        $this->title = $title;
        $this->author = $author;
        $this->isbn = $isbn;
    }
}

Currently, both $title and $isbn are free-form. But ISBNs have rules of their own that determine what’s a valid ISBN value. So you can create an Isbn value object that can only be constructed with a valid value:

class Isbn
{
    public function __construct($value)
    {
        // Ensure given value is numeric, and either 10 or 13 digits
        if (ctype_digit($value) && (strlen($value) === 10 || strlen($value) === 13)) {
            $this->value = $value;
        }

        throw new InvalidArgumentException(
            'ISBNs should be numeric, and either 10 or 13 digits long'
        );
    }
}

So with the above, it’s now impossible to create an Isbn instance with an invalid value, as it will throw an exception if an invalid value is used to try and construct the class. We can now use this class as a type-hint for the $isbn argument in the Book class:

class Book
{
    // Only allow books to be created with valid title, and valid author and ISBN instances
    public function __construct(string $title, Author $author, Isbn $isbn)
    {
        $this->title = $title;
        $this->author = $author;
        $this->isbn = $isbn;
    }
}

Now, it’s only possible to create a Book instance with any string value for the title, and only valid Author and Isbn instances!

Activity icon

Replied to A Facade Root Has Not Been Set.

@abdellah Check your error log: storage/logs/laravel.log

Activity icon

Replied to Run Job Every Second Laravel

@fluber Send message to who/what? Because it’s gong to use a lot of server resources to do something every second, more so if it has any database interaction.

Also, a queue is not an appropriate solution as a queue does not guarantee when a message is delivered; only that it will be at some point in the future.

Activity icon

Replied to A Facade Root Has Not Been Set.

@abdellah Still need more information. If the application is throwing an exception, then it’ll give you a stack trace for you to find what piece of code is actually triggering that error.

You can’t just post a snippet of an error message with no context and expect someone to magically know what the problem is and how to fix it.

Activity icon

Replied to Paypal Fees Calculation

@chron Yes, payment providers charge you fees to send and receive payments. That’s kinda how they make their money.

I wouldn’t rely on trying to calculate a fee in code, because if PayPal updates their fee structure then your code is immediately out of date and calculating incorrect values.

So either price your product/service to account for payment processing fees, or make the customer pay the fee, but don’t rely on being able to calculate the fee before setting the amount to be charged.

Activity icon

Replied to Run Same Code In Several Functions

@ladydeathkzn I actually wrote a blog post on this topic a couple of years ago: https://martinbean.dev/blog/2017/11/27/binding-configured-services-to-laravels-container/

You can wrap up WHM-related functions in a service class and put that class in the service container. You’d then be able to inject that service class into your controllers and call the methods on it:

public function __construct(WhmService $whm)
{
    $this->whm = $whm;
}

public function index()
{
    $accounts = $this->whm->searchAccounts();
}
Activity icon

Replied to Push Queued Jobs Up The Queue/process Immediately

@lunah Yes. You can define multiple queues and process them in order of priority: https://laravel.com/docs/7.x/queues#queue-priorities

Activity icon

Replied to Run Job Every Second Laravel

@fluber What is it you actually need to do, that needs to be done every second?

May
29
2 days ago
Activity icon

Replied to Redirect To Two Different Routes In The Controller At The Same Time (new Tab).

@JoaquinVilchez No, you can’t redirect to two URLs at the same time. How would that even work?

Activity icon

Replied to How Do I Refactor 2 Similar Controllers?

@cipa It might help if you actually gave us proper examples instead of just numbers.

Activity icon

Awarded Best Reply on Non Skipable Ads Like Of Youtube

there is no such package associated with laravel

@wajid Yes, because you would implement it in your video player, and not Laravel.

I don’t really understand what you mean by “merging”. It’s something you would do on the client-side, i.e. JavaScript. It has nothing to do with Laravel.

Activity icon

Replied to Non Skipable Ads Like Of Youtube

there is no such package associated with laravel

@wajid Yes, because you would implement it in your video player, and not Laravel.

I don’t really understand what you mean by “merging”. It’s something you would do on the client-side, i.e. JavaScript. It has nothing to do with Laravel.

Activity icon

Replied to Non Skipable Ads Like Of Youtube

@wajid You’re looking for “pre-roll ads”. Have a look for plugins for whatever video player you’re using to add videos to your website.

May
28
3 days ago
Activity icon

Awarded Best Reply on Restrict The Use Of An API In Laravel To A Single Application

But I understand that CORS protect the user of a website from other websites not making AJAX requests to it without their knowledge, but this does not apply to me

@brahimbjz Wrong. CORS would be suitable. From https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#What_requests_use_CORS:

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that let servers describe which origins are permitted to read that information from a web browser.

Also, from https://auth0.com/blog/cors-tutorial-a-guide-to-cross-origin-resource-sharing/#CORS---Why-Is-It-Needed-

For example, if you're running a React SPA that makes calls to an API backend running on a different domain.

So, you can use CORS to allow your API to specify the origins (i.e. your web application) that can call it.

Activity icon

Replied to Restrict The Use Of An API In Laravel To A Single Application

But I understand that CORS protect the user of a website from other websites not making AJAX requests to it without their knowledge, but this does not apply to me

@brahimbjz Wrong. CORS would be suitable. From https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#What_requests_use_CORS:

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that let servers describe which origins are permitted to read that information from a web browser.

Also, from https://auth0.com/blog/cors-tutorial-a-guide-to-cross-origin-resource-sharing/#CORS---Why-Is-It-Needed-

For example, if you're running a React SPA that makes calls to an API backend running on a different domain.

So, you can use CORS to allow your API to specify the origins (i.e. your web application) that can call it.

Activity icon

Replied to PHP Variable Mutation

@king_eke If you want to add conditions to your query based on data in the query string, then you can do so with the when() method.

It takes a condition and a callback to invoke if that condition is truth-y:

$loans = Loan::query()
    ->when($request->has('from') && $request->has('to'), function ($query) use ($request) {
        $query->whereBetween('created_at', [$request->from, $request->to]);
    })
    ->whereNotNull('user_id')
    ->whereNull('underwriter_level_1_user_id')
    ->count();
Activity icon

Replied to How To Assign A Particular Store Based On User Location Input In A Multi Branch Ecommerce Setup?

@jinner Did you bother to read the links I gave you? The second one is a complete tutorial from Google implementing store search!

Activity icon

Replied to Restrict The Use Of An API In Laravel To A Single Application

@brahimbjz Look into CORS. You can restrict what hosts can access your API that way.

Activity icon

Awarded Best Reply on Google API With User Password Auth Rather Than Key

@drewdan I think you’re looking for OAuth authentication. Google will allow a user to authenticate your app using their Google account: https://developers.google.com/identity/protocols/oauth2

Activity icon

Awarded Best Reply on Why Auth::user Return Null?

@timwuuk Stop reinventing the wheel. Passport is an OAuth server implementation and therefore supports tokens issued via the password grant: https://laravel.com/docs/master/passport#password-grant-tokens

So you can swap a user’s email and password for an OAuth token instead of rolling your own authentication, which is never a good idea if a framework offers authentication out of the box.

Auth::user() also won’t work because you’re not using Laravel’s built-in authentication any more. OAuth tokens are used for “stateless” authentication, so there’s no user in the session; the user is identified by the token you pass to your API routes. So there’s also no need to “log out”, as you don’t “log out” of a stateless API; you just stop using the token. If you want to revoke a token, then build an endpoint (e.g. [email protected]) that revokes or deletes a token passed in the request.

Activity icon

Replied to How To Deal With Mandatory Properties Of An Object.

@isarantoglou Congratulations, you’ve discovered domain models and the concept of invariants and integrity :)

If you have an entity in your application then you want a class that represents that entity, and with which only valid entities can be constructed. So you’re right in thinking about the constructor, but I wouldn’t overload the constructor of an Eloquent model.

This is getting into Domain-Driven Design territory, but you would have a “POPO” (plain ol’ PHP object) that represents an entity. So in your example, a Book. Your Book entity class should have a constructor that takes the required arguments needed to initialise a valid instance of itself:

class Book
{
    public function __construct($title, $author, $isbn)
    {
        $this->title = $title;
        $this->author = $author;
        $this->isbn = $isbn;
    }
}

The best things about classes like this is, you can create value objects representing other things in your application. For example, an author could be elevated to a class of its own. So you could then tell your Book class that it needs a valid Author instance to be passed for the $author argument, rather than any value:

class Book
{
    // Only allow books to be created with a valid author instance
    public function __construct($title, Author $author, $isbn)
    {
        $this->title = $title;
        $this->author = $author;
        $this->isbn = $isbn;
    }
}

Currently, both $title and $isbn are free-form. But ISBNs have rules of their own that determine what’s a valid ISBN value. So you can create an Isbn value object that can only be constructed with a valid value:

class Isbn
{
    public function __construct($value)
    {
        // Ensure given value is numeric, and either 10 or 13 digits
        if (ctype_digit($value) && (strlen($value) === 10 || strlen($value) === 13)) {
            $this->value = $value;
        }

        throw new InvalidArgumentException(
            'ISBNs should be numeric, and either 10 or 13 digits long'
        );
    }
}

So with the above, it’s now impossible to create an Isbn instance with an invalid value, as it will throw an exception if an invalid value is used to try and construct the class. We can now use this class as a type-hint for the $isbn argument in the Book class:

class Book
{
    // Only allow books to be created with valid title, and valid author and ISBN instances
    public function __construct(string $title, Author $author, Isbn $isbn)
    {
        $this->title = $title;
        $this->author = $author;
        $this->isbn = $isbn;
    }
}

Now, it’s only possible to create a Book instance with any string value for the title, and only valid Author and Isbn instances!

Activity icon

Replied to Google API With User Password Auth Rather Than Key

@drewdan I think you’re looking for OAuth authentication. Google will allow a user to authenticate your app using their Google account: https://developers.google.com/identity/protocols/oauth2

Activity icon

Awarded Best Reply on Laravel Mix Versioning

@giacholari It doesn’t actually add any hashes to the filename itself. When the file is referenced in your HTML, it will append a query string value with a hash of the file’s contents.

This is to get around assets that are aggressively cached by CDNs, etc. If you have a file, say app.css, and you make changes to it and re-deploy your application, some caches may serve an old, cached version because it sees the filename and goes, “Oh, I already have a cached version of app.css so I’ll serve that version instead of the one from the server.” This obviously isn’t what you want if you’ve updated your website’s styles!

Adding a query string value gives it a “unique” value. So app.css?id=abc is different to app.css?id=def. So anything caching your assets will see the “new” filename and instead fetch the latest version of the file from your server instead of serving a stale version if it has a stale version cached.

Activity icon

Replied to Using API Resources With Repository / Service Pattern?

@panthro API resources are used for transforming models to a JSON representation, yes. I don’t really understand your question though because you touch on the answer in your post.

return a JSON response and means that you can hide your database structure / not effect the API if your database structure changes as you can transform responses.

This is exactly it. You can control what columns are exposed via your API.

Are responses from API routes not just JSON anyway

Yes, but if you don’t transform the model then it’s just going to return the “default” JSON representation, which may include columns you don’t want exposed, and won’t allow you to keep API responses consistent if you change the name of a column in your database.

Would you transform it just in the API controller and not the web controller

Why would you use an API resource in a web controller? You’ve understood API resources are for returning JSON representations of a model, so why would a web controller return JSON? Surely your web controllers are returning HTML views?

Activity icon

Replied to Laravel Mix Versioning

@giacholari It doesn’t actually add any hashes to the filename itself. When the file is referenced in your HTML, it will append a query string value with a hash of the file’s contents.

This is to get around assets that are aggressively cached by CDNs, etc. If you have a file, say app.css, and you make changes to it and re-deploy your application, some caches may serve an old, cached version because it sees the filename and goes, “Oh, I already have a cached version of app.css so I’ll serve that version instead of the one from the server.” This obviously isn’t what you want if you’ve updated your website’s styles!

Adding a query string value gives it a “unique” value. So app.css?id=abc is different to app.css?id=def. So anything caching your assets will see the “new” filename and instead fetch the latest version of the file from your server instead of serving a stale version if it has a stale version cached.

Activity icon

Replied to Why Auth::user Return Null?

@timwuuk Stop reinventing the wheel. Passport is an OAuth server implementation and therefore supports tokens issued via the password grant: https://laravel.com/docs/master/passport#password-grant-tokens

So you can swap a user’s email and password for an OAuth token instead of rolling your own authentication, which is never a good idea if a framework offers authentication out of the box.

Auth::user() also won’t work because you’re not using Laravel’s built-in authentication any more. OAuth tokens are used for “stateless” authentication, so there’s no user in the session; the user is identified by the token you pass to your API routes. So there’s also no need to “log out”, as you don’t “log out” of a stateless API; you just stop using the token. If you want to revoke a token, then build an endpoint (e.g. [email protected]) that revokes or deletes a token passed in the request.

Activity icon

Replied to How To Assign A Particular Store Based On User Location Input In A Multi Branch Ecommerce Setup?

@jinner Each store would have its coordinates (latitude and longitude) recorded in the database. When the user lands on the website for the first time, you need to get their coordinates, and then look up the store with the closest coordinates to them.

These resources may help:

May
27
4 days ago
Activity icon

Replied to Jobs Failing On Heroku But Work Correctly In Local Environment

@deladels Have you checked your failed_jobs table?

Activity icon

Replied to Composer Runs On @includes

@bvanhaastrecht Views included using @include are just that: views. If you have a composer attached to every view (View::composer('*', 'FooComposer')) then yeah, your composer is going to run for includes as well.

Activity icon

Replied to Choosing The Right API Solution

@nigeldorning For OAuth, client credentials grant would be suitable if the third-party has a system that needs to integrate with your API, and there’s no “person” in the middle.

May
26
5 days ago
Activity icon

Replied to Laravel Money

@andriichuk Did you really revive a five-year-old topic to spam a link to your package…?

Activity icon

Replied to Jobs Failing On Heroku But Work Correctly In Local Environment

@deladels Well what’s the error you get on Heroku…?

Activity icon

Replied to How To Store Product Variants In Database?

@karolmenhart Don’t fret, every one started somewhere!

It sounds like there are three entities in your scenario: a pizza, a dough, and a size. You can create Eloquent models for these. So a single pizza may be pepperoni, a size would be say, 9 inches; and a dough would be American. So for each variant, you could have a table that specifies a combination of all three models:

Schema::create('pizza_variants', function (Blueprint $table) {
    $table->unsignedBigInteger('pizza_id');
    $table->unsignedBigInteger('dough_id');
    $table->unsignedBigInteger('size_id');
});

So, for each pizza you’ll be able to list all the doughs available, and all the sizes it comes in.

Activity icon

Replied to I Have An Old Project Using Laravel 5.5 Should I Upgrade To 6.0 Or 7.x?

@rotaercz Well, first I’d ask: do you actually need to upgrade?

Activity icon

Replied to Laravel JSON API Testing

@fullstackfool I don’t really understand that test. You’re creating a user and then testing that you can create that user via your API? But surely that call should fail if the user’s already been created?

Activity icon

Replied to Trait Vs Hepler In Laravel

@zizi_ove Traits are for re-using logic in various classes to get around PHP not supporting multiple inheritance in classes.

Helpers are for when you’re lazy and want to call a function anywhere just because you can, and not because you should.

Activity icon

Awarded Best Reply on Can Someone Recommend Some Tutorials Or Resources For This?

@nickcourage S3 is just an object store. There’s no “associating” it with a user in your application. You read and write objects (file); nothing more.

If you want to associate an object with a user, then you’d store a reference to the object and your user in your own database.

Laravel’s filesystem component has S3 support out of the box. You just need to set the relevant values in your config/filesystems.php file and set the default driver from local to s3. You can then upload user-submitted files just like any other file:

<input type="file" name="resume" />
$path = $request->file('resume')->store('resumes');

This will return the path the object was stored in (i.e. resumes/somerandomhash.docx) which you can then save to your database along with the authenticated user’s ID:

$request->user()->resumes()->create([
    'path' => $path,
]);

Documentation:

Activity icon

Replied to Can Someone Recommend Some Tutorials Or Resources For This?

@nickcourage S3 is just an object store. There’s no “associating” it with a user in your application. You read and write objects (file); nothing more.

If you want to associate an object with a user, then you’d store a reference to the object and your user in your own database.

Laravel’s filesystem component has S3 support out of the box. You just need to set the relevant values in your config/filesystems.php file and set the default driver from local to s3. You can then upload user-submitted files just like any other file:

<input type="file" name="resume" />
$path = $request->file('resume')->store('resumes');

This will return the path the object was stored in (i.e. resumes/somerandomhash.docx) which you can then save to your database along with the authenticated user’s ID:

$request->user()->resumes()->create([
    'path' => $path,
]);

Documentation:

Activity icon

Replied to Class Interfaces Explanation

@dk4210 You’re on a website that publishes videos on Laravel. Maybe search it?

https://laracasts.com/search?q=interfaces

Activity icon

Replied to Which Stack Should I Use In My SaaS Project?

@affdata The “easiest” solution is to stick with what you know. You’re asking about Spark, a third-party template, and Vapor. That’s a steep learning curve.

I’d also question the use of a Vue SPA. Will your application actually benefit from an SPA over a “traditional” server-rendered application?

Spark is a fine starting point for SaaS applications as that’s what it was built for. It has it’s own Vue-based control panel for managing teams and subscriptions, but you’ll need to build the actual logic and screens for your application. It’s impossible to tell how well a third-party template will slot into this.

Personally, I wouldn’t use Passport and Cashier if all I was going to do is re-build what Spark already does.

May
24
1 week ago
Activity icon

Replied to Calling Routes Internally

@untymage What do you mean by, you want to call routes internally?

Activity icon

Replied to Manually Add Authorisation Code To Socialite

@bobbyaxe61 Use the password grant, instead. You can have your user enter their account email address and password in your mobile app, and your mobile app would then swap those for an access token.

Activity icon

Replied to How To Deploy A Laravel/vue Project On Heroku

@spiral Follow Heroku’s documentation to get the Laravel portion deployed. When you’ve got the Laravel portion working, you can then add the Node.js build pack to your Heroku app, and run Mix whilst deploying to generate your front-end assets.

May
23
1 week ago
Activity icon

Replied to How To Deploy A Laravel/vue Project On Heroku

@spiral Where did you look for 5 or 6 hours? Because Heroku has a guide on deploying Laravel apps: https://devcenter.heroku.com/articles/getting-started-with-laravel

Activity icon

Replied to Tools For Auto Deployment After Subscription

@thinkingman Just use subdomain routing. Only show a website if a user has subscribed.

May
22
1 week ago
Activity icon

Replied to Route (eg. /home) Shared By Multiple Roles. Your Solution?

@uhoh Simple: I don’t have “home” pages for each role and just have a user dashboard. That dashboard then displays whatever content is relevant to that user’s role.

Activity icon

Replied to Web And Api Use Cases

@orest Use web routes for your web application and api routes for exposing an API for your application.

An API != “JSON responses”. An API could return other types of responses: XML, files, plain text. JSON just happens to be common.

If you’re planning on using AJAX, then AJAX requests would normally be made against an API rather than your web application. Your web application would serve HTML views, whilst AJAX requests data in a more, “raw” format (i.e. JSON), and then your client-side JavaScript would use a template to render that data back in your HTML view.