martinbean

martinbean

Senior Developer at Visualsoft Ltd

Member Since 5 Years Ago

Newcastle upon Tyne, UK

Experience Points
546,445
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
533
Lessons
Completed
Best Reply Awards
730
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
546,445 XP
Jul
08
1 day ago
Activity icon

Replied to Remove Laravel User Session After Laravel Passport Sends Token To A Frontend SPA App

@devondahon Passport’s a wrapper around an OAuth server. OAuth is token-based authentication. You request tokens from the OAuth server.

https://laravel.com/docs/7.x/passport#code-grant-pkce

Activity icon

Replied to Remove Laravel User Session After Laravel Passport Sends Token To A Frontend SPA App

@devondahon Why do you have a user session at all when Passport is for token-based authentication?

Activity icon

Replied to Where Not Null Eloquent

@marsuch That’s nothing to do with the whereNotNull method. Read the message: it’s saying the connection to your database was refused, so you have incorrect credentials.

Activity icon

Replied to How To Get User Information Using Accessor?

@shami003 An auction will have many bids. Fetch the bid with the highest value:

$highestBid = $someAuction->bids()->orderBy('bidamount', 'desc')->first();

Note: this will either return the bid with the highest amount, or null if there are no bids. So make sure you account for that in your code:

@if($highestBid)
    <!-- Display highest bid details -->
@else
    <p>No bids yet.</p>
@endif
Activity icon

Replied to Trait Naming Convention

Because I'm afraid if one day laravel will auto-resolve Traits

@pepsiisbetter They won’t. Traits are already “auto-resolved” by name through the PSR-4 autoloading standard. Laravel won’t do anything automated like that as it would break a lot of application code if it make a massive assumption like that.

The [PSR] is good, but why should I put 'Trait' on the Trait's name?

You don’t have to. The ‘R’ is ‘PSR’ is for Recommendation. You’re free to follow it or go against, like Laravel does when it names traits. Your code isn’t going to blow up if you create a trait with a name that doesn’t end with Trait.

Jul
07
2 days ago
Activity icon

Replied to How To Calculate Aggregate Sum Of A Table Column

@tomasosho I don’t really know what you’re expecting that to do since it’s not a valid value for sum()

Activity icon

Replied to How To Get User Information Using Accessor?

@shami003 Then get the bid with the highest value, and grab the user from that bid model.

Activity icon

Replied to How To Calculate Aggregate Sum Of A Table Column

@noblemfd I don’t know. What’s a “weighted score”? Sounds like an algorithm that you need to decide on.

Activity icon

Replied to String Not Changing To What It Should Be In The Email

@gnguyen Why don’t you just pass the carrier to your mailable, and then use it in your mail’s views?

# New message from {{ $carrier->name }} 

There’s no need to create a templating engine; Blade already is one.

Activity icon

Awarded Best Reply on How To Save Child Model Which Has Foreign Key Before I Save Parent Model?

@igeruns I would create the “travel” record and then let users add journeys to it.

Activity icon

Replied to Field Doesn't Have Default Value.

@ajsmith_codes You don’t seem to be doing anything with the user ID. The validate other data, but then you don’t add the user ID to the $salesorder array you try and create a model from.

Activity icon

Replied to How To Get User Information Using Accessor?

@shami003 Adding more accessors is not going to solve your problem.

If you have an “auction” model then I imagine it’s going to have some sort of user relation. That’s where you would get user information from.

Activity icon

Replied to How To Save Child Model Which Has Foreign Key Before I Save Parent Model?

@igeruns I would create the “travel” record and then let users add journeys to it.

Activity icon

Replied to How To Get User Information Using Accessor?

@shami003 By accessing the attribute or relation that holds the user information.

I’d also be wary of that accessor. It’s executing a query so if you call that in a loop, you’re going to encounter the N+1 problem.

Activity icon

Replied to How To Save Child Model Which Has Foreign Key Before I Save Parent Model?

@igeruns You can’t save a child record before saving its parent. You’ll need to create a travel record first before attaching any journeys to it.

Activity icon

Replied to Laravel: One File With Two Classes?

@ninjajoe Yes, but don’t. Have a read over the PSR recommendations.

Activity icon

Replied to Passing Props To Vue Component

@chizpon How are you intending to create a chart from data you don’t want the user to see…?

Activity icon

Replied to Passing Props To Vue Component

The thing is that $google is data that i don't want the user to see, not even with the inspector. Is there a way to hide it?

@chizpon No. Vue is JavaScript. JavaScript is client-side. Everything you pass or use in a Vue component is visible to someone who wants to inspect it.

If you don’t want users to see something, don’t pass it to your front-end. You’ll need to find an alternative approach.

If you tell us what you’re trying to do and not how you’re trying to do it, we may be able to suggest a better approach.

Activity icon

Replied to Get Src Inside $project->content

@browniecoffee You’re going to have to give us more information… We have no idea what $project->content looks like.

Activity icon

Replied to What Are Best Practices When Writing Tests With PHPUnit ?

I love data providers. I use them to run a test case multiple times with different inputs, as opposed to testing different scenarios, though:

/**
 * @dataProvider requiredFieldsDataProvider
 */
public function testFieldIsRequired(string $field)
{
    $data = [
        'name' => 'Test Name',
        'description' => 'Test description',
    ];

    Arr::forget($data, $field);

    $this
        ->post('/some-endpoint', $data)
        ->assertSessionHasValidationErrors($field);
}

public function requiredFieldsDataProvider(): array
{
    return [
        'name' => ['name'],
        'description' => ['description'],
    ];
}
Jul
06
3 days ago
Activity icon

Replied to Authenticate External Systems

@seamlabsweb A couple of ways. If the external system has a static IP address or domain name, only allow requests from that IP/domain.

If you need to use token-based authentication, then Passport would be the way to go. The client credentials grant would be the most appropriate for your use case:

The client credentials grant is suitable for machine-to-machine authentication.

Activity icon

Replied to Trait Naming Convention

@pepsiisbetter There’s no hard and fast rule. Personally, a lot of traits I define end in “-able”. So I have traits like Sluggable, Publishable, Sortable, because these traits define behaviour that I can mix into multiple classes.

On the other hand, I do also have a handful of traits that don’t follow this rule, such as HasUuid, BelongsToWebsite, etc.

Don’t get too hung up on following a particular rule; just name things in a way that makes sense for your application. You should be able to read the name of something and instantly have an idea of what that class, method, trait, etc does.

Activity icon

Replied to How To Test A Failing Job Code

@ranx99 You’re mocking the wrong object. If you’re trying to test the handle method is called on your job when a bad file is passed to it, then mocking the job class itself isn’t going to help you.

Instead, you need to mock the file, have it trigger an exception, and then assert your failed method is called instead.

Activity icon

Replied to What's The Benefit Of Moving Controller Methods To A Model?

@jeroenvanrensen I don’t really understand what you mean by “create the method two times”? The method’s defined once, and used where ever it’s needed?

Activity icon

Awarded Best Reply on What's The Benefit Of Moving Controller Methods To A Model?

@jeroenvanrensen If you’re inserting related data, then it’s nicer to add a method to the parent model as the foreign key will be automatically set. In your second example, you have to manually set the thread_id column value, whereas in the first it’s clear you’re adding a reply to a particular thread and that column value will be automatically set.

Activity icon

Replied to What's The Benefit Of Moving Controller Methods To A Model?

@jeroenvanrensen If you’re inserting related data, then it’s nicer to add a method to the parent model as the foreign key will be automatically set. In your second example, you have to manually set the thread_id column value, whereas in the first it’s clear you’re adding a reply to a particular thread and that column value will be automatically set.

Activity icon

Replied to Is It Good Or Bad If I Use Laravel's Before And After Middleware For Encrypt And Decrypt Every Request?

@prem_thakkar I’d ask why are you encrypting and decrypting requests and responses? If you‘re server your API via HTTPS then they’ll already be secure when transported.

Jul
05
4 days ago
Activity icon

Replied to Missing Methods In Handler.php

@brainmaniac If you’re not actually doing anything with the methods, you can omit them entirely from your application’s handler. Laravel will then use the definitions in the parent handler class provided by the framework itself.

Activity icon

Replied to Why Building Ecommerce Application From The Scratch

@fikri1510 You could say that about any web-based project. CMS software exists, so why do people still make new ones? Email marketing software already existed, so why did Spatie make Mailcoach? PHP frameworks already existed, so why did Taylor make Laravel? Project management software already existed, so why did the former 37Signals create Basecamp?

People create their own solutions because sometimes they think they can do better, or because creating something bespoke will better suit needs. For example, I created an online store from scratch for a Christmas tree seller a few years ago. Reason being, it was easier to create a simple store for what they need rather than pick something like Magento, need a server with stupidly high requirements and use less than 1% of the features that Magento offered.

Activity icon

Replied to Login Using Different Roles Or Different Tables?

@player4 Use the default guard to determine if a user is logged in or not. Then use authorisation to determine if they’re trying to access a route their role allows them to or not.

Jul
04
5 days ago
Activity icon

Replied to Why AWS Over Digitalocean?

@gthell They’re two totally different services. It’s comparing apples to oranges.

Activity icon

Replied to Laravel Create Products Orders For Each Shop In Api

@hamad_essa If this is some form of marketplace, then I’d create one order but then have some model for each shop that shows the products in the order they’re responsible for. The reason being, if I, as a customer, place an order, then I expect to then only see one order (with one order number) in my account; not multiple orders because I happened to order products from multiple vendors.

So maybe have the Order model contain the orders a customer has ordered, and then some form of “fulfilment order” that each shop gets sent instructing them what products they need to send and to who.

Activity icon

Replied to Is There A Package/boilerplate For A Multiple API Connector?

@apinto I’m not really familiar with what Zapier is or what it does, but you can use Guzzle to call third-party APIs. You can wrap configured Guzzle client instances for each API you intend to work with in a service class:

use GuzzleHttp\Client;

class FooService
{
    protected $httpClient;

    public function __construct(Client $httpClient)
    {
        $this->httpClient = $httpClient;
    }

    public function someAction()
    {
        // Use $this->httpClient to perform someAction on API
    }
}

You can then use a service provider to register the service in the service container with a fully-configured Guzzle client instance:

use GuzzleHttp\Client;

class FooServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(FooService::class, function () {
            return new FooService(
                new Client([
                    'headers' => [
                        // Set any headers required for authentication
                        // Could be token, API key, etc.
                        // Each API will have different requirements
                    ],
                ]);
            );
        });
    }
}

Now, when you type-hint FooService in your application, it will be constructed with a fully-configured Guzzle client and you can start calling methods on it:

class FooController extends Controller
{
    public function fooAction(FooService $fooService)
    {
        $result = $fooService->someAction();
    }
}
Activity icon

Replied to Login Using Different Roles Or Different Tables?

@player4 Please, don’t store different user types across different tables. What you have done already (users table with multiple roles) is perfectly acceptable.

A user is a user. You don’t need to split different “types” across different tables. It just adds unnecessary complexity. If you have say, a “regular” user and an admin, and they’re in different tables, what happens when you want to elevate a user to an admin? What happens if you want to add a new user type, say a moderator? You then have to create migrations, guards, controllers and views just to support a new role.

So keep your application users in a single table, assign them roles, and then use authorization to determine what a user can do in your application based on their role(s).

Activity icon

Replied to Is There A Way To Decode A Laravel Passport Token Outside Of The Authenticating Server?

@alex29 That’s not what an OAuth token is for, though. OAuth is for requesting a token, and then having a token that allows the caller to call services.

If you need to store information in a token and be able to read information in the token itself, then it sounds like JWT would be a more appropriate solution.

Activity icon

Replied to Running A Query Multiple Times Inside Foreach Loop And Storing The Results In An Array.

I am trying to run a query multiple times with foreach loop

@ramniksingh Don’t 😬 That’s the very definition of the N+1 problem.

Jul
03
6 days ago
Activity icon

Awarded Best Reply on Adding Fields To Validated That Aren't Directly Validated

@xtremer360 I can’t say I’ve created a “pseudo” property like this in a request. But I set which columns are fillable and then use $request->validated() when creating/updating a model.

In your case you could either use $request->input() instead to get all request data and only set values for columns that are fillable (including your height column). If you’re absolutely adamant on using validated() for whatever reason, then you could fill your model with the validated request data, and then explicitly set the height value before saving:

$patient = new Patient($request->validated());
$patient->height = $request->input('height');
$patient->save();

Or, you could add your height value to the validated values:

$patient = Patient::create(array_merge($request->validated(), [
    'height' => $request->input('height'),
]));

Or, the simplest method, override the validated() method in your StorePatientRequest class if you’re sure you want the height value in there:

class StorePatientRequest extends FormRequest
{
    // Other form request methods like rules(), etc.

    public function validated()
    {
        return array_merge(parent::validated(), [
            'height' => $this->input('height'),
        ]);
    }
}

You can then use validated() as intended:

$patient = Patient::create($request->validated());
Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@xtremer360 I can’t say I’ve created a “pseudo” property like this in a request. But I set which columns are fillable and then use $request->validated() when creating/updating a model.

In your case you could either use $request->input() instead to get all request data and only set values for columns that are fillable (including your height column). If you’re absolutely adamant on using validated() for whatever reason, then you could fill your model with the validated request data, and then explicitly set the height value before saving:

$patient = new Patient($request->validated());
$patient->height = $request->input('height');
$patient->save();

Or, you could add your height value to the validated values:

$patient = Patient::create(array_merge($request->validated(), [
    'height' => $request->input('height'),
]));

Or, the simplest method, override the validated() method in your StorePatientRequest class if you’re sure you want the height value in there:

class StorePatientRequest extends FormRequest
{
    // Other form request methods like rules(), etc.

    public function validated()
    {
        return array_merge(parent::validated(), [
            'height' => $this->input('height'),
        ]);
    }
}

You can then use validated() as intended:

$patient = Patient::create($request->validated());
Activity icon

Replied to Is There A User System Package ?

If signed in, it becomes a verified user

@app_dev That makes no sense. What becomes a verified user? You don’t know the user until they log in.

I want to record all your moves.

Then use something that does this, like Google Analytics or Mixpanel. And be sure to include in your application’s privacy policy that you’re surveilling users.

Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@xtremer360 The problem is, you’re trying to get a mix of validated fields with non-validated fields. Laravel is working exactly as it should: it’s returning only the fields that were validated. The height field wasn’t part of the request nor was it validated, so it’s not going to be present through the validated() method.

Activity icon

Replied to Creating Own Changable Routes

@jeroenvanrensen Ah, OK. Sorry, I misunderstood! I thought you were wanting users to be able to customise the whole URL structure (including the /admin part). Sorry!

Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@xtremer360 This is why I prefer to explicitly set fillable columns instead of having everything fillable by default.

Activity icon

Replied to Is There A User System Package ?

@app_dev What do you mean by “user package”? A package to do what with users exactly?

Activity icon

Replied to How To Get The Last Login Of A User

@umairparacha What have you tried…?

Activity icon

Replied to Adding Fields To Validated That Aren't Directly Validated

@xtremer360 Are you specifying the fillable fields in the model? As if so (and feet and inches aren’t fillable) then they’ll just be discarded if you pass the request data to your model:

Patient::create($request->input());
Activity icon

Replied to Laravel Api With Session

is there any difference or I am missing something here!?

@adamoxy The difference is, you don’t use sessions in an API. APIs are stateless and you should be using token-based authentication like OAuth.

Activity icon

Replied to Laravel - Bind Session To User-Agent String And IP Address

@milosradic I still don’t really think that’s secure. As surely the same browser running on similar hardware is going to have the same user agent string. Not to mention that a user agent string can be “spoofed” just as easily as a cookie’s value can be copy-pasted.

Also, I don’t know off the top of my head, but Laravel’s cookies are encrypted and I think invalid somehow if it’s stolen. Like I say, I don’t know how it does it off the top of my head.

Activity icon

Replied to Creating Own Changable Routes

@jeroenvanrensen I’d be hesitant in letting user configure “application”-level routes such as the routes for your admin panel. What happens if your user creates a route for a page (say /foo) and then also sets the admin panel URLs to start with /foo? You’re going to have a conflict.

By all means, let the user have dynamic front-end routes, but keep the admin panel routes static. You could offer some configurability by letting the user set the path using a configuration value, a bit like how Nova does. But I wouldn’t make it a database-backed value that the user can change at will.

For the front-end routes, you can either have a “catch-all” controller like @bobbybouwmann suggests, or cache your routes and then register them in middleware. If you register routes in the $middleware property, they’ll be registered before the request is actually passed through the router.