martinbean

martinbean

Senior Developer at Visualsoft Ltd

Member Since 5 Years Ago

Newcastle upon Tyne, UK

Experience Points
577,055
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
540
Lessons
Completed
Best Reply Awards
770
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
577,055 XP
Sep
25
2 days ago
Activity icon

Replied to Laravel Project Using Onion Architecture

I need to apply or convert the Laravel structure to the Onion Architecture

@krishbala96 Do you? Why do you “need” to convert it? Because you’ve read some article on the Internet that said you should?

Activity icon

Replied to PHP Best Setting For 1gb File Upload..

@ap3twe PHP only has a finite amount of memory. The “best” setting is to upload large files how they’re meant to be uploaded: in parts. Look into multipart uploading; services like Amazon S3 support it.

Activity icon

Replied to Having Several Repositories Attached A Controller

@rffred I haven’t used “datatables”, but if it works by loading all of the rows from a table then yeah, you’re going to have a bad time.

Sep
24
3 days ago
Activity icon

Replied to Having Several Repositories Attached A Controller

@rffred You still haven’t answered why you think Eloquent queries are “slow” compared to “raw” queries… when Eloquent just uses the query builder in Laravel to construct queries in the same manner if you did DB::table('example')->get().

If you’re just starting out, learn to walk before running. Start with the basics. Look at design patterns like repositories when you know what they’re for and can see a use case for them, and not because some stranger on the Internet’s said you “should” use them.

Sep
21
6 days ago
Activity icon

Replied to How To Use Different Model For Authentication Other Than User To Register/login In Laravel Passport?

@dr24 I literally gave you the config for that. The above says, for the passport guard, use the advertisers provider.

I suggest maybe reading up on authentication and Passport so you understand what’s going on in the configuration file.

Activity icon

Replied to Obfuscating URLs Securely

@lfcallif That’s just security through obscurity, i.e. not secure at all.

You can use a different column for routing than your primary key. You can add a second column to your model that holds a UUID if you want to use UUIDs, or a slug, or some other unique, generated value. You haven’t really told us what your system does so unable to give you any solid recommendations.

Also, I’m curious as to why you think hashids are not secure? They’re absolutely secure so long as you don’t expose your seed value.

Activity icon

Replied to How To Use Different Model For Authentication Other Than User To Register/login In Laravel Passport?

@dr24 Configure a custom user provider in your config/auth.php file that uses your Advertiser model for the model key instead, and then specify that provider for your Passport guard:

'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'advertisers',
    ],
],

'providers' => [
    'advertisers' => [
        'driver' => 'eloquent',
        'model' => App\Advertiser::class,
    ],
],
Activity icon

Replied to Having Several Repositories Attached A Controller

@rffred I fail to see what a repository is going to solve here. Both your repositories and Eloquent models generate database queries; there’s nothing inherently non-performant with Eloquent.

So ask yourself: what will repositories actually solve, if anything? Because it’s always a crappy path when you start. First you create a repository for an Eloquent model; then you need to get a paginated list rather than all records; then you need to eager-load relationships; and some time later you find you’re just re-implementing Eloquent, but it only has a small percentage of the functionality Eloquent has, as you just keep stuffing methods in your repository classes to accommodate each and every use case in your application.

Activity icon

Replied to How Do I Dockerise This Cloned Laravel App?

@nickcourage Your Dockerfile and docker-compose.yml file should be in the same directory as your Laravel application; not in a subdirectory.

Sep
20
1 week ago
Activity icon

Replied to How Do I Dockerise This Cloned Laravel App?

@nickcourage You can add commands to your Dockerfile to install your Composer dependencies. You can use the official Composer Docker image to do this:

# Grab the composer executable from the Composer Docker image
COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer

# Install Composer dependencies
COPY composer.json composer.lock /yourworkdir/
RUN composer install --no-autoloader --no-interaction --no-progress --no-scripts && composer clear-cache

# Add app files and generate autoloader
COPY . /yourworkdir/
RUN composer install --no-interaction --no-progress --optimize-autoloader

The reason for running composer install is a tip I picked up from Jess Archer from this Tweet: https://twitter.com/jessarchercodes/status/1281111908154662914

Sep
15
1 week ago
Activity icon

Replied to Problem With Uploading Big Files With Laravel To S3

@t_avsec You will need to use multi-part uploading to upload files more than a couple of megabytes in size. AWS has a tutorial on exactly this: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html#s3-example-photo-album-adding-photos

I use the same approach to let me users upload videos on a video on demand platform.

Sep
14
1 week ago
Activity icon

Awarded Best Reply on Socialite - Best Practices

@edalzell You shouldn’t be doing look-ups based on the email address. This is actually a security vulnerability as if I know there is a user with the email address [email protected] in your application’s database, I can temporarily change the email address on a Google account to that, go through your application’s Socialite flow, and then be (wrongly) logged in as the user with that email address.

Instead, you should allow your application users to be able to connect their social accounts. Save the user information you get back from the third party source (i.e. Google) and then associate it with your user by the ID you get back from Google. This way, your users are free to change their email addresses and not break the “connection” with the third party accounts.

When a user tries to log in with Google, if you find that account in your database then you know a user has associated it with their account and you can log the corresponding user in. If you don’t find an account, prompt the user to register with Google instead. You want separate flows in case people use different email address for different services (like I do). If this is the case, you don’t want to be creating new user accounts because a user’s forgotten to log in and associate it with their account on your application first.

Activity icon

Replied to Socialite - Best Practices

@edalzell You shouldn’t be doing look-ups based on the email address. This is actually a security vulnerability as if I know there is a user with the email address [email protected] in your application’s database, I can temporarily change the email address on a Google account to that, go through your application’s Socialite flow, and then be (wrongly) logged in as the user with that email address.

Instead, you should allow your application users to be able to connect their social accounts. Save the user information you get back from the third party source (i.e. Google) and then associate it with your user by the ID you get back from Google. This way, your users are free to change their email addresses and not break the “connection” with the third party accounts.

When a user tries to log in with Google, if you find that account in your database then you know a user has associated it with their account and you can log the corresponding user in. If you don’t find an account, prompt the user to register with Google instead. You want separate flows in case people use different email address for different services (like I do). If this is the case, you don’t want to be creating new user accounts because a user’s forgotten to log in and associate it with their account on your application first.

Activity icon

Replied to It's Possible To Get Routes URIs And Names And Show Them In Listboxes?

@davidsi02 You don’t need to write the routes out somewhere. You can just use the Route::getRoutes method like @laracoft says. If you write routes somewhere, they’re only going to get out of date.

Sep
13
2 weeks ago
Activity icon

Awarded Best Reply on No Application Key - Github Action For Laravel

@giacholari You can put a hard-coded key in your phpunit.xml file, rather than generating one each time.

As long as it’s a unique key used solely for the purpose of running automated tests, then there’s no problem with this.

Activity icon

Replied to No Application Key - Github Action For Laravel

@giacholari You can put a hard-coded key in your phpunit.xml file, rather than generating one each time.

As long as it’s a unique key used solely for the purpose of running automated tests, then there’s no problem with this.

Activity icon

Replied to Great Coding Fonts

@pschubu Pick a font. Stick with it. Don’t worry about what Jeffrey or anyone else is using.

I don’t get people who worry about what font they’re using, as if it’s going to have a dramatic, tangible impact on their work. Pick a font that has initial appeal, and you’ll find you’ll get used to it like a pair of comfortable slippers.

Activity icon

Replied to Allow User Login Only If Active - Laravel 7

@boby You’ve already been given the answer.

In your authenticated method, log the user out and redirect with an error message if the user is inactive:

public function authenticated(Request $request, $user)
{
    if (! $user->active) {
        Auth::logout();

        return redirect('/')->withError('Please activate your account before logging in.');
    }
}
Sep
11
2 weeks ago
Activity icon

Replied to Laravel Passport How To Logout User?

Passport adds an OAuth server to Laravel applications. You don’t “log out” when using OAuth-based authentication.

Activity icon

Replied to What Are The API Testing Types?

@vistadigit The “best practice” for testing is, to just test.

Sep
09
2 weeks ago
Activity icon

Replied to TDD How Do You Test Backend And Frontend

@charrua Yeah, feel free to organise your tests like that, but the approach doesn’t really change between testing the “front” and “back” of your application :)

Just write feature tests that make requests and either test for a success or error response:

$this
    ->actingAs($admin);
    ->post('/admin/products', $validData)
    ->assertSessionHasNoErrors()
    ->assertRedirect();
$this
    ->actingAs($admin);
    ->post('/admin/products', $invalidData)
    ->assertSessionHasErrors(['fields', 'that', 'should', 'fail', 'validation']);
Sep
07
2 weeks ago
Activity icon

Awarded Best Reply on Adjust Laravel Hashing Algorithm

@oswin Laravel’s hasher is component-based. This means you can create your own hasher implementation and bind it to the container so that the built-in authentication uses your algorithm instead of one of the built-in ones.

You’ll need to extend the HashManager in a service provider to add your custom hasher:

HashManager::extend('custom', function () {
    return new CustomHasher();
});

The CustomHasher class will need to conform to the Hasher interface.

Once you’ve created your custom hasher implementation, you can tell Laravel to use it by updating your config/hashing.php file:

return [

    'driver' => 'custom',

    // ...

];
Activity icon

Replied to Cart Json Laravel

@bobson Why just you actually model your cart properly? Instead of just chucking a JSON blob in your database.

It kinda defeats the point of using a relational database such as MySQL or PostgresQL if you don’t use it to store relational data.

Activity icon

Replied to TDD How Do You Test Backend And Frontend

@charrua I’m not sure what difference “backend” and “frontend” makes; tests just perform actions and then assertions. Doesn’t matter if you’re testing a “front” end route or a “back” end route.

Sep
05
3 weeks ago
Activity icon

Replied to Laravel And APIs

@wallyj Use Guzzle for making HTTP requests in PHP. It’ll make your life a lot easier.

Sep
03
3 weeks ago
Activity icon

Replied to Command From My Code

@nevakil Artisan is a CLI helper. Its commands are meant to be, well, ran on the command line.

If you have logic that you want to execute from either a HTTP controller or a CLI command, wrap it up in a job or something that you can call from both contexts.

Sep
02
3 weeks ago
Activity icon

Replied to Bug/Fix Warranty Period.

@extjac It Depends™. Discuss it with your client what they require.

If I’m developing something and it’s getting installed on their servers, then very little time if any at all. There’s nothing stopping them tinkering with the codebase once it’s set up, so you can then find yourself fixing bugs in code or configuration that’s no longer your own.

Aug
29
4 weeks ago
Activity icon

Replied to Game Server Service Using Laravel

@mekaboo Consider the entire point of game servers. They need to be fast as possible. For this reason, I wouldn’t use Laravel but something more suited to fast responses, such as Node.js. It seems you’ve already found something suitable in Babylon.js, so not sure why you’re not looking to “import” that into Laravel?

Activity icon

Replied to Implementing API Authentication And Security

isn't it possible to generate token without relating any user in users

@enthusiast14 Well exactly who are you authenticating if not a user? That’s the entire point of OAuth: to allow users to give access to a trusted client (such as your Android app). So if you have no users, why do you need tokens?

Aug
28
4 weeks ago
Activity icon

Replied to Laravel Mulit Auth System

@devkhaled94 Don’t. Just don’t. Users are users. Don’t create multiple models and guards for different “types” of users.

Give users a role and then use authorisation to determine what routes they can access and actions they can perform.

Aug
27
1 month ago
Activity icon

Replied to Laravel And APIs

@wallyj This is OAuth. Read up on it. You’ll be getting an authorization code and then swapping that for an access token.

Activity icon

Replied to Remove Global Scope On A Model Instance

@j0wz Like I say, I’ve treaded this ground before and it caused more problems than it solved. When I rebuilt the second version of my CMS, I just kept my models simple and instead accessed models through relations on the “root” model (in my case, Website).

So, to fetch articles for a website, a simplified example of the controller would look like this:

class ArticleController extends Controller
{
    public function index(Website $website)
    {
        $articles = $website->articles()->latest()->paginate();

        return view('website::article.index', compact('website', 'articles'));
    }

    public function show(Website $website, Article $article)
    {
        return view('website::article.show', compact('website', 'article'));
    }
}

It’s still on Laravel 6, so I have custom middleware that checks that the requested article for the show action belongs to the website, but in Laravel 7.x you can use automatic scoping for this:

// Website routes
Route::group([
    'as' => 'website.',
    'domain' => '{website:domain}',
    'namespace' => 'Website',
], function () {
    // Website articles
    Route::get('articles', '[email protected]')->name('article.index');
    Route::get('articles/{article:slug}', '[email protected]')->name('article.show');
});

This means your models are just models and you can then query them without worrying about global scopes:

// Find published articles for every website
$publishedArticles = Article::published()->get();

You can also use policies to further check users are only accessing resources they’re allowed to see:

class ArticlePolicy
{
    public function update(User $user, Article $article)
    {
        // Check user is associated with website that article belongs to
        return $user->websites->contains($article->website);
    }
}
Activity icon

Replied to HTML U.I For Smart TV

@bosspogs No. Like I said a month ago, it would help if you told us what TV you’re trying to develop on, and follow their guides for creating web apps.

Activity icon

Replied to Calculating Totals In Model

@ollie_123 Well like I say, you shouldn’t be calculating the amounts on the fly any way. Calculate when the order’s created.

If you have an accessor that calculates a total and you change the price of a product, that’s going to affect old orders where the order was placed when the product was the old price.

Activity icon

Replied to Api Login With Passport

@masterenv You should not be passing usernames and passwords as part of URLs. This is massively insecure!

Instead, use Passport as it was intended: create a client for the other app, and allow that app to request tokens for your users.

Activity icon

Replied to Remove Global Scope On A Model Instance

@j0wz The “clean” way is to not use global scopes like this. I did it in the first version of my multi-tenant CMS and it was a pain. Because you have to remember to do it everywhere: controllers, jobs, console commands, etc. And as you’ve found, it becomes even more gnarly when you have relations with the scope applied. It’s more hassle than it’s worth.

Aug
26
1 month ago
Activity icon

Replied to Restructuring Models And Parent Model

@xtremer360 Can you give a bit more context? It’s a bit difficult to get your head around when it’s just A, B, C, etc. and you’re asking for tips on how to refactor them.

Activity icon

Replied to Calculating Totals In Model

@ollie_123 Your Invoice model would have a has-many relation with an InvoiceLineItem model. The line item model would then store a description of the line item, quantity, unit price, and total for that line. You can have a foreign key pointing towards a product or whatever.

But again, don’t rely on any data from the associated product table (i.e. price) because if you change the price of the product and your invoice uses that to calculate any totals, then those amounts will change, which you don’t want. Capture data at the time you create the invoice. Another scenario is if you completely delete the product—if your invoice is pulling data from the relation then your application is going to throw a 500 error when a customer tries to view an invoice and it’s referencing data on a model that no longer exists.

Aug
25
1 month ago
Activity icon

Replied to Trying To Builld And LMS Systen

@joshmanhuwa It’s probably important to get an idea of what you’re wanting to build before you actually start writing any code.

Activity icon

Replied to Calculating Totals In Model

@ollie_123 Just a note: if you’re dealing with anything financial (invoices, orders, etc) be sure to calculate any taxes, totals, etc at the point of creation and save them as values in the row itself.

The reason: if you update any calculation logic, amounts on historical invoices and orders shouldn’t change.

Activity icon

Replied to Adjust Laravel Hashing Algorithm

@oswin Laravel’s hasher is component-based. This means you can create your own hasher implementation and bind it to the container so that the built-in authentication uses your algorithm instead of one of the built-in ones.

You’ll need to extend the HashManager in a service provider to add your custom hasher:

HashManager::extend('custom', function () {
    return new CustomHasher();
});

The CustomHasher class will need to conform to the Hasher interface.

Once you’ve created your custom hasher implementation, you can tell Laravel to use it by updating your config/hashing.php file:

return [

    'driver' => 'custom',

    // ...

];
Activity icon

Replied to How I Can Scrape Articles Body

@muhammednasser Do you have permission from the blog owner to scrape their content…?

Activity icon

Replied to Store Inventory

@msslgomez I’m sure I answered a pretty similar question a little while back. My advice was to create a table that holds stock level adjustments for products. The table would essentially be a ledger, with a foreign key pointing to a SKU, and the quantity that was added/removed from stock.

Say 10 units of a SKU come in. You would add a row to your stock_level_adjustments table with the foreign key for the SKU and set some column, say quantity, to 10. If you get a delivery for 10 more of the same SKU, you would create another row. You can then get the current stock level by SUM-ing the quantity for a particular SKU:

$stockLevel = $sku->stockLevelAdjustments()->sum('quantity'); // 20

You can wrap this up into a method on your Sku model:

class Sku extends Model
{
    public function stockLevelAdjustments()
    {
        return $this->hasMany(StockLevelAdjustment::class);
    }

    public function stockLevel()
    {
        return $this->stockLevelAdjustments()->sum('quantity');
    }
}

When you make a sale, you would again create a new row, but this time with a negative value representing the number sold. So if someone buys three of the above SKU, you would create a stock level adjustment for that purchase:

$sku->stockLevelAdjustments()->create([
    'quantity' => -3,
]);

Now if you SUM the quantity column, you should get 17.

Activity icon

Replied to How Do You Handle Routes When Using SPA?

@ravish The question was asked three years ago…

Aug
24
1 month ago
Activity icon

Awarded Best Reply on Any Optimize Way For The Given Create Or Update Elquoent Record ?

@princeoo7 That’s very verbose to just update or create a record.

Create a route to rate a particular video:

Route::post('videos/{video}/rating', '[email protected]');

And then update or create the rating for the given video and authenticated user:

public function store(StoreRatingRequest $request, Video $video)
{
    $rating = $request->user()->ratings()->updateOrCreate(
        ['video_id' => $video->getKey()],
        ['rating' => $request->input('rating')]
    );

    return new RatingResource($rating);
}
Aug
23
1 month ago
Activity icon

Replied to What Are Some Good Resources To Learn And Read About Laravel ?

@ravish If only there were a video tutorial site specialising in Laravel that had a forum you could ask on…

Activity icon

Replied to Crazy ✨Closure

@konstruktionsplan Am I guessing this is a coding test for a new role…?

Activity icon

Replied to Simple API Login Without Using Passport

@briana You don’t “log in” to APIs. And you definitely shouldn’t be sending email addresses and plaintext passwords in the query string of requests; that’s a massive security issue.

Your system needs a way for mobile applications and other applications to authenticate. Well, this is example what Passport was created for. For example, from the auth code grant with PCKE section:

The Authorization Code grant with "Proof Key for Code Exchange" (PKCE) is a secure way to authenticate single page applications or native applications to access your API.

So, perfect for your use case. When your mobile application is authenticated, you will get an access token for the user that you can use to authenticate API requests as that user.

Use things that have been built to solve problems. 90% of problems have been solved already. There’s no reason to spurn a pre-built solution like Passport as then you make decisions like you have that actually make your application less secure. Passport has been installed tens of millions of times; it’s well tested and any major security issues will have been discovered by now.