martinbean

martinbean

Senior Developer at Visualsoft Ltd

Member Since 6 Years Ago

Newcastle upon Tyne, UK

Experience Points
601,455
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
593
Lessons
Completed
Best Reply Awards
794
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.

  • community-pillar Created with Sketch.

    Community Pillar

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

Level 50
601,455 XP
Dec
02
1 day ago
Activity icon

Replied to Repository Pattern Create Method

@armingdev Repositories shouldn’t be used to persist entities. They should be used for finding entities based on a given criteria.

If you’re separating things from the controller then there are other pattens that are more appropriate, such as commands or a service class.

Nov
30
3 days ago
Activity icon

Commented on Hook Into PHPUnit's Pass/Fail Events

This is exactly what I wanted to do with my PHPUnit at home! 😄

My intention was to buy some of those LED light strips and put them on the back of my iMac, and then wrap the phpunit command to make them flash green if the exit code was 0 or red for any other exit code.

Activity icon

Replied to Does Laravel Nova Support Php 8.0?

@gianmarx The Composer error is telling you “no”.

Nov
29
4 days ago
Activity icon

Replied to LARAVEL API

@emfinanga Probably not wise to share your mobile number and email address on a public forum…

Nov
25
1 week ago
Activity icon

Replied to Why Does Laravel Have It's Own Carbon Class?

That’s… not what was asked?

Activity icon

Replied to Best Way To Abstract Queue OnConnection

@master_chief_sunday I don’t really know what the QUEUE_DEFAULT environment variable is; that’s not a default variable provided by Laravel. But even if you did have multiple queue configurations, you can use the same driver for all of them. You don’t need to be referencing environment variables or doing environment checks in if statements in your code at all.

I think you might be confusing connections and queues. This might explain a little better than I can: https://laravel.com/docs/8.x/queues#connections-vs-queues

A connection can have many queues. So your sqs connection could have multiple queues (i.e. low priority, medium priority, high priority, etc) but they would all use the same connection. So you don’t need to be manually specifying onConnection in your code if you intend to use the same driver (i.e. SQS or sync) throughout your codebase. The connection used will just be whatever you set as the value of QUEUE_DRIVER.

Activity icon

Replied to How To Install New Packages On Godaddy Shared Hosting

@mecjos Shared hosting packages are notoriously limited, because the resources on them are shared. Hosting companies don’t want you running intensive processes like composer and npm or queue workers because then that ties up processing power for other customers using that site.

Instead, you should just upload the files via FTP. If you want to run processes on the server, then you’ll need to upgrade from shared hosting to a more appropriate product.

Activity icon

Awarded Best Reply on Model Factories Confusion

@phpmick I think a new campaign is going to be created regardless, because you’re calling create on the campaign factory in your “thing” factory definition.

Instead, you can just specify the campaign factory in your “thing” factory with no methods appended, and it will only be evaluated and return the primary key if you don’t specify a campaign_id:

$factory->define(Thing::class, function (Faker $faker) {
    return  [
         'campaign_id' => factory(Campaign::class),
         'title' => $faker->sentence(6),
    ];
});
Activity icon

Replied to Which Parts Of Your Website / App Use Vue?

Yeah, they’re good candidates for Vue components, because you can create a generic <like-button> component and then pass the URL it should use as a prop:

<like-button url="/posts/123/like"></like-button>

You can now use the like-button component for any type of content.

Activity icon

Replied to Best Way To Abstract Queue OnConnection

@master_chief_sunday I don’t really understand the point of calling onConnection if you’re just specifying the default queue any way? You also shouldn’t be using the env helper in your code, and you definitely shouldn’t be doing environment checks in your code, otherwise that’s just to litter your codebase with lots of if statements.

The queue component is deliberately configurable. So you can set the QUEUE_DEFAULT environment variable to sqs in production and sync in your Docker environment. Your code will then do what you want.

However, if you are using queues in your application, then I’d use something like Redis rather than the sync driver in your Docker environment, otherwise your Docker environment isn’t really a good reflection of your production environment if production dispatches jobs asynchronously and your Docker environment doesn’t. If you’re using Docker, then it’s going to be trivial to add a Redis container that handles your queued jobs.

Activity icon

Replied to Which Parts Of Your Website / App Use Vue?

@thebigk Vue and jQuery aren’t really comparable. Vue is a component framework; jQuery is a generic JavaScript utility library.

You use Vue components to wrap up specific functionality in your web application, making it dynamic and to add interactivity. Good use cases for Vue components are interactions that would incur a page load/refresh if you used a “traditional” approach.

So think of a “like” button: you click it to like something, click it again to “un-like” it. This could be a Vue component so you don’t have to create a form, that submits to a controller, to redirect back. It just fires an AJAX request to an API to “like” something, and then updates its state.

In terms of discussion forums, you can look at Laracasts as an example. One such example would be editing a post. Instead of an edit button taking you to a new route to edit the post, you can edit the post inline. And then when you submit, it will send the updated post data via AJAX to an API route and then just update the text in the page without redirecting away.

Activity icon

Replied to Model Factories Confusion

@phpmick I think a new campaign is going to be created regardless, because you’re calling create on the campaign factory in your “thing” factory definition.

Instead, you can just specify the campaign factory in your “thing” factory with no methods appended, and it will only be evaluated and return the primary key if you don’t specify a campaign_id:

$factory->define(Thing::class, function (Faker $faker) {
    return  [
         'campaign_id' => factory(Campaign::class),
         'title' => $faker->sentence(6),
    ];
});
Activity icon

Replied to Run A Controller By The Role

@soogo That’s not how controllers works. A controller handles a request, and returns a response. In that controller is where you would do any authorisation to determine if the user can access it or not.

Nov
24
1 week ago
Activity icon

Replied to Laravel Mix And Multiple Vue Files

@user1980 You need to define a custom filename if you don’t want Mix to use its default format: https://webpack.js.org/guides/lazy-loading/

Activity icon

Replied to Write PHP Logic In Blade?

is it good practice to write a lot of PHP logic in Blade?

@gthell No. It completely defeats the purpose of MVC.

Blade template are views. Your pass views the data they need via a controller. Your views should not be doing business logic.

Nov
22
1 week ago
Activity icon

Replied to How To Mock A Job Object In Laravel?

@cosmic_learning The problem is, you’re not resolving the job class from the container so you’re not going to be able to mock it or swap the instance in the container.

Personally, I wouldn’t catch this in the controller. If the job throws an exception, then let the exception handler catch it and return the appropriate response.

Activity icon

Replied to How To Mock A Job Object In Laravel?

@cosmic_learning You’re not quite separating them, though. You should have a feature test that only tests the job you’re expecting is dispatched when you perform an action:

Queue::fake();

// Do something, like make a request

Queue::assertPushed(ProcessRunEndpoint::class);

You should then have a separate test for your ProcessRunEndpoint class that tests that class and that class alone:

class ProcessTestEndpointTest extends TestCase
{
    public function testItDoesSomething(): void
    {
        // Mock any dependencies 

        $job = new ProcessRunEndpoint($parameterOne, $parameterTwo);

        $job->handle($parameterThree, $parameterFour);

        // Perform some assertions here
    }
}

Because you’re testing your class and your class only (and not how it’s passed through Laravel’s queue dispatcher), you can mock any parameters in its constructor as well as any parameters passed to the handle method.

Tests shouldn’t do too much. If you have a feature test hitting a controller, it should just test the controller returns the correct response and as much mocked as possible. Individual classes should then be tested, which makes them easier to refactor in the future as if you change a class, you only have to update the one corresponding test.

Activity icon

Replied to What Is The Safe/best Way To Use Sanctum And Vue?

@imwaller Absolutely not. You should not be persisting cross-site request forgery protection measures anywhere.

Activity icon

Replied to How To Mock A Job Object In Laravel?

@cosmic_learning If you have a feature test that tests a controller or something, then you should be mocking the queue. You can then create a separate test that tests the queue job in isolation, mocking its dependencies if needs be.

Activity icon

Replied to Repository Pattern In Laravel

@ustabasiibrahim It’s an awful pattern, and there are ways to write “clean code” without the repository pattern.

Activity icon

Replied to How Do You Handle Controllers With Partial Identical Business Logic?

@lazos99 Yes, and what you’ve described is exactly what the adapter pattern is for. You have common functions but different implementations. So encode the LDAP-specific business logic in your LDAP implementation, and your Eloquent-specific business logic in the Eloquent implementation.

Activity icon

Replied to How Do You Handle Controllers With Partial Identical Business Logic?

@rodrigo.pedra Thanks! To be honest, I skimmed it on first read with how long it was, but your understanding of repositories is certainly correct: they should only really be used to fetch entities and not the place for all CRUD operations like creating, updating, and deleting entities.

I seldom use repositories myself, but I’d use them where the same storage mechanism used is used throughout the application, as you’d usually bind a single implementation to an interface, and then use the interface for dependency injection.

If there are parts of the application that use different storage mechanisms but should adhere to the same interface, then I’d create a class that then accepts a particular implementation for that storage mechanism. The base class would then just call methods on that particular adapter:

class UserService
{
    protected $store;

    public function __construct(UserStore $store)
    {
        $this->store = $store;
    }

    public function export($id)
    {
        return $this->store->export($id);
    }

    public function restore($id)
    {
        return $this->store->restore($id);
    }

    public function destroy($id)
    {
        return $this->store->destroy($id);
    }
}

So the UserService class just delegates method calls to a particular implementation. You can then inject different implementations based on which controller is wanting the UserService using contextual binding:

$this->app
    ->when(EloquentUserController::class)
    ->needs(UserService::class)
    ->give(function () {
        return new UserService(EloquentUserStore());
    });

$this->app
    ->when(LdapUserController::class)
    ->needs(UserService::class)
    ->give(function () {
        return new UserService(LdapUserStore());
    });

The two controllers can then just extend a base one, because it’ll get the user service with the correct store injected in its constructor:

abstract class BaseUserController extends Controller
{
    protected $service;

    public function __construct(UserService $service)
    {
        $this->service = $service;
    }

    public function export($id)
    {
        $this->service->export($id);
    }

    public function restore($id)
    {
        $this->service->restore($id);
    }

    public function destroy($id)
    {
        $this->service->destroy($id);
    }
}
class EloquentUserController extends BaseUserController
{
    // No body needed
}
class LdapUserController extends BaseUserController
{
    // No body needed
}
Activity icon

Replied to How Do You Handle Controllers With Partial Identical Business Logic?

@lazos99 It sounds like the perfect candidate for the adapter pattern. If your business logic is the same but the underlying provider changes, then you can replicate that in your project.

You can have a user service class that exposes common methods for what you need: export, destroy, restore, etc. But these methods then delegate to another class under the hood with that particular implementation.

Think of the queue component in Laravel: you interact with the queue using the same methods, no matter what adapter you’re using.

Nov
21
1 week ago
Activity icon

Replied to Is It Worth Working On Homestead?

@onca 7 seconds is a long time. It might help if you said how you were currently serving your app? Because running your app within Homestead isn’t going to magically make your web app faster. In fact, it’ll probably do the opposite with it having to virtualise hardware.

Nov
19
2 weeks ago
Activity icon

Replied to Pass Data From Controller To Another View

Trying to get property 'id' of non-object

@vironeer Yes. I read the error message the first time. Now how about you read the error message, instead of just posting it a second time?

Activity icon

Replied to Pass Data From Controller To Another View

@vironeer Then Auth::user() isn’t an object. Read your error messages; they’re there to help you.

Activity icon

Replied to Real World Usage Of Interface And It's Meaning

@rymercyble Interfaces are definitions for a common set of classes. If you think of the queue component in Laravel, there are many implementations (Redis, SQS, etc) but they all conform to a common interface, so that you can use a queue anywhere in your application without worrying about the specific implementation of that interface.

It’s an abstract way of thinking about classes. So when you work with interfaces, rather than implementations, your code becomes easier to work with and easy to re-factor.

Another real-world example would be in a video on demand marketing I built and operate. Customers can upload videos, so videos need to be transcoded before they can be embedded in a web page and watched by other users. Currently, I use AWS Elastic Transcoder for this, so I have an ElasticTranscoderVideoTranscoder class that does this logic, but that class implements a generic VideoTranscoder interface. This means that if I decide to use another transcoder in the future (i.e. AWS Media Elements, or a non-AWS offering) then I can create a class for that particular service, and as long as it confirms to the same VideoTranscoder interface, swap the Elastic Transcoder implementation out, and I’ll not have to change any other code in my application to support the new transcoder service.

So, the next time you inject a class as a parameter into a method or another class, think, “Could this be made generic and could I use an interface here instead?”

Nov
18
2 weeks ago
Activity icon

Replied to Creating And Consuming An API Service Within Laravel

@nickcourage First I’d determine whether building API-first and building an SPA is actually going to bring you any benefits or advantages. If you decide it is, then you just build your API by putting your routes in your routes/api.php file, and then have a web controller that returns a Blade view, which in turn has a <script> tag that loads your Vue SPA’s entry point, i.e. /js/app.js.

Activity icon

Awarded Best Reply on Overriding Core Classes

@mdupor In that case, I’d define macros with a name more appropriate or intention-revealing. I don’t know the reason for using string columns for timestamps, but maybe define a macro like:

Blueprint::macro('stringTimestamps', function () {
    $this->string('created_at')->nullable();
    $this->string('updated_at')->nullable();
});

And you can then use this macro in your migrations:

$table->stringTimestamps();

Given you’re overriding the framework’s conventions, this will need to be something you need to inform new team members of (“we use string timestamps for Reason X”) and be vigilant of in pull requests.

Nov
17
2 weeks ago
Activity icon

Replied to Packages Development

@abdosaeedelhassan This may be of help: https://spatie.be/videos/laravel-package-training

There’s then also the Laravel documentation, of course: https://laravel.com/docs/8.x/packages

Activity icon

Replied to Laravel Passport

@jokerdz First party clients are things like your own mobile apps. Third party clients are exactly that: third parties that need to access your data for some reason.

Think about Facebook. When you authenticate with Facebook to get a user’s details, you do so as a third party. You don’t work for Facebook, but you’re using OAuth to retrieve data from Facebook’s servers. Whereas the Messenger app would be a first party client to Facebook, because Facebook owns and operates Messenger and its apps.

Activity icon

Replied to Vue Vs Livewire

@gianmarx Define “better”.

Activity icon

Replied to Package For Generating /scafolding Tests?

@jaynarayan Not really, because tests are application-specific. Set up some snippets in your text editor if you need to write a lot of tests.

Activity icon

Replied to Laravel Passport

@jokerdz Passport adds OAuth authentication to your application, so it allows first- and third-party clients to request tokens for your users, which you can then use to make API requests as that user. You don’t “log in” to an API; you use tokens to authenticate each request.

For registration, if you want to be able to register users from a first- or third-party client, then you’ll need to create an API endpoint that facilitates this. Be sure to add spam prevention measures to this endpoint though, such as rate limiting, reCAPTCHA for repeated registrations from the same device/location, etc.

Activity icon

Replied to Overriding Core Classes

@mdupor Ah, sorry, I missed that.

If that’s the case, wouldn’t the columns be integers and a foreign key pointing to a user? If so, you could maybe add a macro for “audit fields”:

Blueprint::macro('auditFields', function () {
    $this->foreignId('created_by')->nullable()->constrained();
    $this->foreignId('updated_by')->nullable()->constrained();
});
$table->timestamps();
$table->auditFields();
Activity icon

Replied to Overriding Core Classes

@mdupor In that case, I’d define macros with a name more appropriate or intention-revealing. I don’t know the reason for using string columns for timestamps, but maybe define a macro like:

Blueprint::macro('stringTimestamps', function () {
    $this->string('created_at')->nullable();
    $this->string('updated_at')->nullable();
});

And you can then use this macro in your migrations:

$table->stringTimestamps();

Given you’re overriding the framework’s conventions, this will need to be something you need to inform new team members of (“we use string timestamps for Reason X”) and be vigilant of in pull requests.

Activity icon

Replied to Overriding Core Classes

@mdupor The decorator class needs to implement the same interface as the class you’re extending. The Blueprint doesn’t seem to implement an interface, so you can just delegate any unhandled methods to the underlying instance in your decorator class:

namespace App\Extensions\Database;

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Traits;

class BlueprintExtension
{
    use ForwardsCalls;

    protected $blueprint;

    public function __construct(Blueprint $blueprint)
    {
        $this->blueprint = $blueprint;
    }

    public function timestamps($precision = 0)
    {
        // Your timestamps implementation
    }

    public function __call($method, $parameters)
    {
        return $this->forwardCallTo($this->blueprint, $method, $parameters);
    }
}

When extending a binding in the container, you’ll receive the original instance as the first parameter in the callback function:

$this->app->extend(Blueprint::class, function (Blueprint $blueprint) {
    return new BlueprintDecorator($blueprint);
});

Now, whenever the Blueprint class is resolved by the container, your decorator class will be returned instead.

Nov
16
2 weeks ago
Activity icon

Replied to Repetitive Validation Rules And Messages

@orest I don’t really see what the problem is, to be honest.

If I’m looking at validation, I want to be able to read the rules, not see that it uses some abstract “body” rule. A “body” rule tells me nothing about the data under validation, which means I need to look in another location.

Activity icon

Replied to Question On Testing

@jlrdw I don’t really know because I can’t see how those variables get their values, or what it is you’re wanting to assert.

Activity icon

Awarded Best Reply on Get Non-persistent (Model-)Objects From Collection

@aitsu If you have a collection of model instances, some persisted and some not, then the easiest method is to filter your collection using the exists property, not method:

$unsavedCars = $cars->reject(function ($car) {
    return $car->exists;
});

You can then chunk the resulting collection and save them in batches if you’re working with ~40,000 records:

$unsavedCars->chunk(100)->each(function ($chunk) {
    // Chunk will be a collection of up to 100 cars
    // Insert those using DB facade or something
});
Activity icon

Replied to Laravel Queue:work Setup In Background Cpanel

@neeraj1005 You’ve been told about three times now that this usually isn’t possible on shared hosting. So check with your host whether you can execute long-running processes like a queue worker, as I’m guessing not.

There’s no point continually asking how if it’s not possible.

Activity icon

Replied to Database Hacked

@nrginternetdiensten You too.

Be sure to rotate all of your passwords and API keys, and your application encryption key that was in the exposed .env, otherwise you’re just re-locking a door that someone already has the key to.

Activity icon

Replied to Laravel Queue:work Setup In Background Cpanel

SO instead of database should I have to use sync

@neeraj1005 No, because sync executes queue jobs synchronously, i.e. within a request, so it’s essentially not using a queue at all.

So, in cpanel I have to install supervisor and SSH? Do you have any idea how this can be resolve...?

Google it.

Activity icon

Replied to Get Non-persistent (Model-)Objects From Collection

@aitsu If you have a collection of model instances, some persisted and some not, then the easiest method is to filter your collection using the exists property, not method:

$unsavedCars = $cars->reject(function ($car) {
    return $car->exists;
});

You can then chunk the resulting collection and save them in batches if you’re working with ~40,000 records:

$unsavedCars->chunk(100)->each(function ($chunk) {
    // Chunk will be a collection of up to 100 cars
    // Insert those using DB facade or something
});
Activity icon

Replied to Upgrading VERY Old Laravel To The Latest Version.

@davidleads It’s impossible to say without knowing how “big” the project is.

If you do go the upgrade route, then be sure to upgrade version by version; don’t try and go straight from 5.x to 8.x, otherwise you’ll have a bad time and will probably be left with no option but to start over!

Activity icon

Replied to Laravel Queue:work Setup In Background Cpanel

@neeraj1005 You need to SSH into your server, and run php artisan queue:work as a detached process. You’ll also want to use something like Supervisor to make sure the process is restarted if it’s terminated for whatever reason.

However, if you’re using cPanel and this is a shared host, this will most likely not be possible. The reason being, with shared hosting, you share the resources of that server with other customers, so hosting company doesn’t want you triggering long-running processes and hogging up those resources. In which case, you’ll need to look at something “more”, like a dedicated host, VPS, or something.

Activity icon

Replied to Database Hacked

@nrginternetdiensten If you’ve been developing websites for 10 years then you really should know about how to set your web root on a server properly 😕

The only directory that should be publicly accessible is the conveniently-named public folder!

Nov
15
2 weeks ago
Activity icon

Replied to Using Dash Instead Of Slash In Routes

I fail to see what “SEO issues” arise from using slashes. It will hint to search engines the hierarchy of your website, whereas dashes will do the complete opposite.