martinbean

martinbean

Senior Developer at Visualsoft Ltd

Member Since 5 Years Ago

Newcastle upon Tyne, UK

Experience Points
515,645
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
527
Lessons
Completed
Best Reply Awards
691
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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
515,645 XP
Feb
17
2 days ago
Activity icon

Replied to Eloquent Vs. Custom Query

@kiasaty I don’t want to sound mean, but it sounds like you’re working with a bunch of absolute amateurs and you’re not going to learn anything in this company.

I lie. You will learn: bad habits.

Feb
16
3 days ago
Activity icon

Replied to Users And Categories Have Many Services

@mmaged Well what have you tried so far…?

Activity icon

Replied to Eloquent Vs. Custom Query

they said that Eloquent queries are not efficient.

Eloquent uses the query builder under the hood…?

they said Eloquent is slow and there are a lot of joins in Eloquent queries.

Only if you write queries with joins.

Repository makes the sql query, then passes the result to Factory, then Factory maps the result to entity and returns the entity.

Well that’s wrong. A repository itself is supposed to return entities. Factories are being used entirely wrong there.

@kiasaty It sounds like your colleagues couldn’t be bothered to learn how to use Laravel/Lumen and Eloquent properly, and instead hand-rolling their own solutions with incorrectly-used design patterns.

Activity icon

Replied to Optional Route Generate Two Slashes URL

@joaohamerski Optional parameters can only occur at the end of a route URI.

Feb
14
5 days ago
Activity icon

Awarded Best Reply on Security Question

Now the question: if one knows the exact path to call, like http://<app_address>/storage/invoiceXXX.pdf could be able to download every document in there.

@giorg Right. So you need to use authorization.

Usually, you would store files in a non-public location, and then only return download responses if you have a logged-in user and you know that user has access to the file attempting to be downloaded:

class InvoiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->only('show');
    }

    public function show(Invoice $invoice)
    {
        // Check user owns invoice using policy
        $this->authorize('view', $invoice);

        // User can view invoice; return download response
        return response()->download($invoice->path);
    }
}
Activity icon

Replied to Security Question

Now the question: if one knows the exact path to call, like http://<app_address>/storage/invoiceXXX.pdf could be able to download every document in there.

@giorg Right. So you need to use authorization.

Usually, you would store files in a non-public location, and then only return download responses if you have a logged-in user and you know that user has access to the file attempting to be downloaded:

class InvoiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->only('show');
    }

    public function show(Invoice $invoice)
    {
        // Check user owns invoice using policy
        $this->authorize('view', $invoice);

        // User can view invoice; return download response
        return response()->download($invoice->path);
    }
}
Feb
13
6 days ago
Activity icon

Commented on Value Objects And Mutability

I love value objects. I blogged about them a little while ago: https://martinbean.co.uk/blog/2019/11/07/using-value-objects-in-projects/

Feb
12
1 week ago
Activity icon

Replied to Laravel Routes - Best Practices.

@pablot There’s no real concrete rules, but there are a handful of prevalent practices that make managing your routes easier in the long run.

With your example where you have a front-end marketing website and the application itself, a lot of businesses like that will have the marketing website on the www. subdomain (so www.radar.com) and then the application itself on an app. subdomain (i.e. app.radar.com). This allows you to separate your marketing website from the application itself, and scale both independently.

Other than that, the convention you’re following for businesses and offices is good. Use resource controllers (and nested resource controllers) as much as possible. If you build your application around resources as much as possible, it makes life so much easier!

Feb
05
2 weeks ago
Activity icon

Replied to Work With Model Data From Remote Source

@jjk If it’s just a case of a table in a remote database, then you could create an Eloquent model for that table and set the connection in that model class:

class RemoteCustomer extends Model
{
    protected $connection = 'remote';

    protected $fillable = [
        'id',
        'name',
        'address',
        'date_registered',
    ];
}
Jan
28
3 weeks ago
Activity icon

Replied to How To Create New Database For Every Session

@uksarkar Don’t create a database on demand like this unless you want your users to crash your server.

Instead, you could have interested customers create a demo account by clicking a button. You could have a server-side script then create a new database, migrate, and seed it using a queued job. When the queued job finishes, broadcast an event to the front-end and redirect the customer to their newly-configured demo account.

Make sure to have a scheduled task to clean up your created databases.

Activity icon

Replied to Laravel How To Get Currently Opened All Tabs In Browser ?

@ahkeravi You can’t have a PHP application read tabs from a browser running on a user’s computer. You definitely can’t take screenshots of what’s open in those tabs.

That would be a huge security vulnerability if any website could read your open tabs’ URLs and take screenshots of their contents, don’t you think…?

Activity icon

Replied to Upgrade Laravel 5.5 To 5.5.42

@sigalz https://laravel.com/docs/5.5/upgrade#upgrade-5.5.42

To upgrade the actual framework version, so long as you have "laravel/framework": "5.5*" in your composer.json file, it should just be a case of running composer update laravel/framework from the command line.

Activity icon

Replied to Domain Verification

@phpmuhammed What do you mean by, “a Twitter profile with the domain name”? Twitter profiles are made up of up to 15 alphanumeric or underscore characters; not domain names.

Activity icon

Replied to Is Service Pattern And Repository Pattern The Same?

@PyaeSone No, they’re not the same.

A repository is for accessing objects in a collection-like manner.

A service is a class with methods for executing business logic, that may be coordinate various other services (such as multiple repositories) to perform a single action or get a single result.

Jan
26
3 weeks ago
Activity icon

Replied to Change IP Address On Each Request To Avoid Ban While Scrape

@christopher Have you actually checked to see if you’re allowed to scrape Amazon? As I imagine you won’t be and it’s against their terms of use. Most websites prohibit scraping of their content due to copyright.

The fact that Amazon is banning your IP address suggests that Amazon doesn’t really want people scraping data en masse.

Activity icon

Replied to How To Avoid Duplication Of Code

@naveedali Mobile apps use APIs to communicate with web apps. You can’t embed a PHP application in an iOS or Android app that shares its codebase with an actual web app.

Jan
20
4 weeks ago
Activity icon

Replied to What Are You Using Laravel For?

I’ve worked with Laravel for about six years now (since the 4.0 beta) and have used it for applications big and small.

Present-day, I’m using Laravel for a large RESTful API that will be slowly replacing a legacy (15+ year) monolithic e-commerce platform. In my spare time, I use Laravel for a “proper” SaaS (a self-service video on demand platform) and a multi-tenant CMS (think Squarespace or Wix, but for a really niche market).

Jan
19
1 month ago
Jan
13
1 month ago
Activity icon

Replied to Slightly Different Versions Of PHP And Laravel.

@swimmer Use something like Homestead so that you have the same version of PHP (and other software) in a self-contained environment on each of your computers.

Ideally, you should have the same version of PHP (and things like MySQL) in your development environment as you do on your production server.

Jan
06
1 month ago
Activity icon

Replied to How To Secure Front-end And Back-end Project ?

@browniecoffee Security in what context? Application security? Server security?

You can never be too secure. There’s no magical threshold you can cross where your application goes from being “not secure” to “secure”.

Activity icon

Replied to Put File Into Storage Directly From The Content

@osukono Files are just bytes. If you’re getting an audio file from Google’s API, then you’ll be able to get the contents as a string and stream that to a file in your own application’s storage.

However, I’d check with Google first to see if you’re actually allowed to store their data on your servers.

Activity icon

Replied to How Can I Lock A Laravel Template?

We must be able to add a key and the template should work only if it has a legit key.

@hardbyte How do you expect that to work? PHP is just code executed by a server. Whatever “restrictions” you put on it, if you’re giving the code to a customer then there’s nothing stopping them just removing your license key-checking code.

Laravel products like Spark and Nova don’t ship with a notion of “license keys”. You need a purchase a license to be able to download the source code, but once downloaded there’s nothing stopping a nefarious user from just installing it in multiple projects on multiple servers.

Whatever limitation you put in, someone will crack it.

Activity icon

Replied to GetRouteKeyName Is Not Working

@oxbir If you’re getting a, “Trying to get property of non-object” error message, then it’ll also give you a file and a line number. That’s where your problem is.

Jan
04
1 month ago
Activity icon

Replied to How Would You Create A File On Amazon S3 And Write The Contents To It?

@vardhan_kspl I’m not sure what the problem is?

Create a file and keep a handle to it, then you’ll be able to stream contents to it: https://laravel.com/docs/6.x/filesystem#storing-files

Activity icon

Replied to Using Models

@randy_johnson Yes, you should be using models to represent “things” in your application. It’s much easier to work with than crafting raw SQL queries.

Using models will make your code leaner and easier to reason about, as you can see what your code is doing it and not how it’s doing it.

Activity icon

Replied to What Would Be The Best Way To Record Profits Per Transaction?

@dru If you have a transactions table that records transactions between two parties, then just have a profit column in that table?

Jan
03
1 month ago
Activity icon

Replied to Architecture Question: Multiple-Guards Or Permissions?

@splendidkeen Keep users as users. Don’t create multiple models to represent users, as then you’ll find yourself having to create multiple guards, controllers, views, and so on. It all gets a bit messy when you need a route where more than one type of user can access a single route. Also, what do you do if you need to add another type of user (say, a moderator)? Do you start creating new guards, etc?

Instead, use roles and authorisation to determine what a user can see and do in your application. It stands to reason a doctor can also be a patient (they’re human; they have ailments too). Are you therefore expecting them to register twice in your application…?

I can say with over six years’ experience building Laravel applications of all sizes, that having a single user model in your application will make your life a lot easier.

Activity icon

Replied to Domain Events Across Services

The stack and apps are no longer scalable and maintainable at current size/load and due to service additions, we are looking into making microservices for any new additions and overtime split existing services into separate microservices.

@cboxdk So the solution to one, unmaintainable app is to create many applications, each with their own infrastructure and scaling considerations, dependencies to keep up to date, etc with the added task of orchestration, authentication, etc between these services? I hope your company has lots of engineers, because micro services adds complexity rather than solves it.

In your scenario, some sort of messaging service is going to be needed. You post a message, and have n consumers read that message. But then you have the issue of, where and how long do you keep a message around if X number of consumers read and process the message, but Y number of consumers don’t (they’re offline, code error, etc). Kafta may be able to do this.

Webhooks is another option. You would have N webhook subscribers. A webhook is then attempted to be delivered to each subscriber. If a webhook fails to be delivered, it’s put in a queue to be tried again, using exponential back-off. This is what Stripe (and probably thousands of others services) do. But then you’ve got to add some sort of service discovery to make sure each service is subscribed the webhooks it needs to be.

Alternatively, if you’re dealing with domain events then you could just go full-on event sourcing. Events go into an append-only, read-only queue. Any consumer can receive these events (in order) and do whatever it needs to. If a service goes offline, it’ll just start receiving the events from the point it went offline in order.

Or you could just have a single app that raises events and listens to events that’s slightly better organised, maybe using a concept such as DDD.

Dec
30
1 month ago
Activity icon

Replied to How To Properly Extend Laravel Socialite?

@surendaran_cg This thread is over four years old. My (now-deleted) Socialite provider didn’t do anything that isn’t covered in the Medium article linked above.

Dec
29
1 month ago
Activity icon

Awarded Best Reply on Different Redirect For Custom Auth Guard

@mkarakaya Don’t create multiple tables for different user “types”. Just have users and use authorisation to determine what a user can see and do.

Dec
28
1 month ago
Activity icon

Replied to Different Redirect For Custom Auth Guard

@mkarakaya Don’t create multiple tables for different user “types”. Just have users and use authorisation to determine what a user can see and do.

Activity icon

Replied to How To Schedule A Nightly Reboot? (Forge + DigitalOcean)

I'd like to do a nightly reboot however as there's no good reason not to.

@sunscreem What is the good reason to do so…?

Dec
27
1 month ago
Activity icon

Replied to Cartalyst Vanished From Github

@awcode Try emailing the maintainers. You can find their email addresses on the Packagist page for the now-missing package: https://packagist.org/packages/cartalyst/collections

Dec
24
1 month ago
Activity icon

Replied to Json_encode

@davy_yg json_encode-ing a LengthAwarePaginator instance will call toArray on each item in the paginator’s collection. So if you have an array of models, it will call `toArr on each of those model instances.

You need to find out why toArray is messing with your attributes. You’ve probably got a mutator or something defined.

Dec
23
1 month ago
Activity icon

Replied to Are There People Who'd Like To Be A Mentor?

@lievikoff Happy to review any code posted here. There’s also https://codereview.stackexchange.com to get feedback on code.

Dec
20
1 month ago
Activity icon

Replied to ProductInventory

I cannot understand where all these comes from

@davy_yg If only you could Google "Laravel" and "old"...

Dec
19
2 months ago
Activity icon

Awarded Best Reply on Why My Facades Still Need Namespace?

@untymage Because facade classes still live in a namespace, and usually not the same namespace as the class you're using them. Also, I think you may be talking about aliases and not facades.

Take this example:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Storage;

class ImageController extends Controller
{
    public function store(Request $request)
    {
        Storage::put('uploads', $request->file('image'));
    }
}

You still need to import Storage because the image controller class is in the App\Http\Controllers namespace, but the Storage alias isn't; the Storage alias is in the top-level namespace.

Activity icon

Replied to Why My Facades Still Need Namespace?

@untymage Because facade classes still live in a namespace, and usually not the same namespace as the class you're using them. Also, I think you may be talking about aliases and not facades.

Take this example:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Storage;

class ImageController extends Controller
{
    public function store(Request $request)
    {
        Storage::put('uploads', $request->file('image'));
    }
}

You still need to import Storage because the image controller class is in the App\Http\Controllers namespace, but the Storage alias isn't; the Storage alias is in the top-level namespace.

Dec
18
2 months ago
Activity icon

Replied to Can I Easily Change The Emergency Logger Stream?

@consil I can't say I've had to do anything with "emergency" logging, but can you not change your logging channel to stderr?

// config/logging.php

return [

    'default' => 'stderr',

    // ...

];
Dec
16
2 months ago
Activity icon

Replied to HELP!!! My Clients Website Deposit Details Changed To Fake Details By Scammer

Shit. Sorry to hear that. Maybe best thing to do is to migrate to some more secure hosting setup

@bugsysha This sounds more like a poorly-coded application rather than the host. There's clearly some code that is vulnerable to attack. Moving hosts isn't going to fix that if that is indeed the issue.

Dec
15
2 months ago
Activity icon

Replied to Error In Student Mark DB Structure Insert And View

@abdulbazith Sorry, but I'm not on-call. I'll answer your question if I see it and have time to, not because I'm tagged.

Dec
04
2 months ago
Activity icon

Replied to Laravel's Future With PHP7.4

@kakashispfc Laravel is not going to adopt annotations, and it's not that strongly-typed.

If you want to use annotations and strong type-hinting, then Symfony and Doctrine may be more your taste.

Nov
28
2 months ago
Activity icon

Replied to Bind Laravel API Resources Interface

@zoroaster Why are you trying to inject a resource? You should be wrapping an object/collection of objects in a resource:

public function show(Product $product)
{
    return new ProductResource($product);
}

If you inject the resource class in the above example, how is it supposed to know which product object to wrap?

Nov
26
2 months ago
Nov
22
2 months ago
Activity icon

Replied to Request Naming Conventions And Structure?

@nakov Asking rhetorically. A request is part of the HTTP layer, which is part of your application layer.

Your domain does not care how it is invoked, be it a HTTP request, a console command, queued job, etc.

Your application layer should have controllers, requests, console commands, etc. Your domain layer should contain the models of your application, services, any repositories, etc.

Nov
21
2 months ago
Activity icon

Replied to Request Naming Conventions And Structure?

If you follow DDD then you will have the requests within your module

@nakov Surely requests belong in the application layer...?

Nov
08
3 months ago
Activity icon

Awarded Best Reply on 6.x Adding My Own 2FA Implementation - How To Intercept Auth?

@dlystyr Laravel doesnt offer 2FA out of the box, so youll need to implement your own solution Im afraid.

I dont know about newer versions, but Spark used to intercept a login by overriding the authenticated() in the LoginController. It would immediately log the user out, but put the user elsewhere in the session, and redirect to a page to accept the token. The token would be checked for the user in the session and if it matched, the user was re-authenticated and redirected back to where they wanted to go.

A simple implementation of that would look like this:

class LoginController extends Controller
{
    // Other methods

    public function authenticated($request, $user)
    {
        // Immediately log user out
        Auth::logout();

        // Store user elsewhere in session
        $request->session()->put('auth.id', $user->getKey());

        // Redirect to token form
        return redirect()->route('2fa.token');
    }
}
class TwoFactorController extends Controller
{
    public function showTokenForm()
    {
        return view('2fa.token');
    }

    public function verifyToken(Request $request)
    {
        // Retrieve user from session
        $user = User::findOrFail($request->session()->get('user.id'));

        // Verify token with third-party services
        if ($someTokenService->isValid($user, $request->input('token'))) {
            // Token was valid; reauthenticate user and redirect
            Auth::login($user);
            
            return redirect()->intended('/');
        }

        // Token was not valid; redirect back or show error
    }
}
Activity icon

Replied to 6.x Adding My Own 2FA Implementation - How To Intercept Auth?

@dlystyr Laravel doesnt offer 2FA out of the box, so youll need to implement your own solution Im afraid.

I dont know about newer versions, but Spark used to intercept a login by overriding the authenticated() in the LoginController. It would immediately log the user out, but put the user elsewhere in the session, and redirect to a page to accept the token. The token would be checked for the user in the session and if it matched, the user was re-authenticated and redirected back to where they wanted to go.

A simple implementation of that would look like this:

class LoginController extends Controller
{
    // Other methods

    public function authenticated($request, $user)
    {
        // Immediately log user out
        Auth::logout();

        // Store user elsewhere in session
        $request->session()->put('auth.id', $user->getKey());

        // Redirect to token form
        return redirect()->route('2fa.token');
    }
}
class TwoFactorController extends Controller
{
    public function showTokenForm()
    {
        return view('2fa.token');
    }

    public function verifyToken(Request $request)
    {
        // Retrieve user from session
        $user = User::findOrFail($request->session()->get('user.id'));

        // Verify token with third-party services
        if ($someTokenService->isValid($user, $request->input('token'))) {
            // Token was valid; reauthenticate user and redirect
            Auth::login($user);
            
            return redirect()->intended('/');
        }

        // Token was not valid; redirect back or show error
    }
}
Oct
29
3 months ago
Activity icon

Awarded Best Reply on Looking To Improve A Piece Of Code

@danieloplata You could create a custom SurveyCollection, and add a method to that class:

class SurveyCollection extends Collection
{
    public function areComplete(): bool
    {
        // Determine if all surveys are complete by rejecting
        // completed surveys and checking that collection is then empty
        return $this->reject(function (Survey $survey) {
            return $survey->pivot->completed;
        })->isEmpty();
    }
}
@if($surveys->areComplete())
    <div class="text-green-600">All surveys complete</div>
@else
    <div class="text-red-600">You still have surveys to complete</div>
@endif