martinbean

Senior Developer at MBL Solutions

Experience

435,305

598 Best Reply Awards

  • Member Since 3 Years Ago
  • 419 Lessons Completed
  • 1 Favorite

24th September, 2018

martinbean left a reply on Form Requests & WithValidator() • 7 hours ago

@matttonks11 If you look at the base FormRequest class, you’ll see there are methods to change where a user is redirected to if validation fails:

https://github.com/laravel/framework/blob/a168181f8188a4e6cd7d3f87b4f8f29a080172aa/src/Illuminate/Foundation/Http/FormRequest.php#L33-L45

martinbean left a reply on Best Way To Create An Activity Log • 7 hours ago

@petritr One approach would be to register some terminable middleware that dispatches a job after each request:

class LogRequest
{
    public function handle($request, Closure $next)
    {
        return $request($next);
    }

    public function terminate($request, $response)
    {
        LogRequestForAuditing::dispatch($request, $response);
    }
}
class LogRequestForAuditing
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $request;
    public $response;

    public function __construct($request, $response)
    {
        $this->request = $request;
        $this->response = $response;
    }

    public function handle()
    {
        // Log request and response in database, log file etc.
    }
}

You would want to do the actual recording after the response has been sent so the user isn’t waiting for a slow database connection or file stream or however you’re recording the request/response.

23rd September, 2018

martinbean left a reply on Modify Response In Middleware • 20 hours ago

@larafam You either modify the response content or you don’t.

If you tell us what it is you’re trying to do, we might be able to help more.

martinbean left a reply on Php Syntax Error Unexpected '}' Expecting ';' • 1 day ago

@haxordeveloper Because the semi-colon is in the wrong place. It should be after return factory(User::class)->create()->id.

martinbean left a reply on Php Syntax Error Unexpected '}' Expecting ';' • 1 day ago

@haxordeveloper The error message will have given you a line number.

Looking at your code, you’re missing a semi-colon on the line you create a user and fetch its id.

22nd September, 2018

martinbean left a reply on Bind A Url Param In The Service Provider? • 2 days ago

@shez1983 If you’re wanting to set a default parameter value for routes, you could do so using middleware. The Laravel documentation has an example of this in the URL Generation section: https://laravel.com/docs/5.6/urls#default-values

martinbean left a reply on Uploading Video Files In Background • 2 days ago

@techtailor The user needs to stay on the page to upload the video. You can upload it directly to S3, bypassing your application, but the user will still need to stay on that page until the upload completes (just like they would on YouTube or Vimeo or any other video uploading service).

Amazon has an example of using their JavaScript SDK to upload files to S3: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album-full.html

20th September, 2018

martinbean left a reply on Block American Express Cards Via Stripe API • 3 days ago

@aGandrass If you’re going to disregard the Radar rule route, then a Token object (whether created with JavaScript or PHP or any other language) has a card.brand property:

$token = Stripe\Token::retrieve($request->paymentToken);

if (strtolower($token->card->brand) == 'mastercard') {
    // Throw exception or something
}

martinbean left a reply on Using A Form Request For Validation With A Policy For Authorization • 4 days ago

@realrandyallen No problem. Glad I was able to point you in the right direction!

martinbean left a reply on Block American Express Cards Via Stripe API • 4 days ago

@aGandrass I’m not sure what “Radar for Teams” is. I have multiple Stripe accounts for my products, and each one has their own Radar rules.

martinbean left a reply on Block American Express Cards Via Stripe API • 4 days ago

@aGandrass Radar is built into Stripe. It’s not an “extra” product or something additionally charged for.

martinbean left a reply on Using A Form Request For Validation With A Policy For Authorization • 4 days ago

@realrandyallen Your “before” callback is checking if a user is an admin or not. You’re just returning the result of that call; if the user isn’t an admin that it’ll return false and make your request as forbidden.

From the authorization documentation:

If the before callback returns a non-null result that result will be considered the result of the check.

false is a non-null result. Instead, you should—again as per the documentation—only return true if the user is an admin to override policy checks:

Gate::before(function ($user) {
    if ($user->isAdmin()) {
        return true;
    }
});

If the user is an admin, it will allow them to perform any action. If not, it will fall back to checking your policies.

martinbean left a reply on Form Request: The Request User In Null • 4 days ago

@ederson What does your test look like?

19th September, 2018

martinbean left a reply on Block American Express Cards Via Stripe API • 4 days ago

@aGandrass Can you not create a Radar rule?

martinbean left a reply on Floats Vs Integers • 5 days ago

@InspiredPrynce Ha-ha, thanks! I’m glad I was able to help :)

martinbean left a reply on When To Break REST. • 5 days ago

@MickBee Yeah, Adam and I have pretty much the same approach to building applications: all actions is creating, updating, or deleting something—the problem is finding out what that something is. Also, the something doesn’t have to have a corresponding model or database table either.

martinbean left a reply on Laravel 5.7 - Change .env File Location For Production • 5 days ago

@pirmax Your configuration should be in the environment itself.

martinbean left a reply on Show Loading Spinner While My Controller Execute A Function • 5 days ago

@rory You can’t. Your controller would only return a response (view) once it’s finished executing.

Instead, you’ll need to have your controller return a view, and then do your execution via AJAX and have your loading indicator visible while you wait for a response from that AJAX request.

martinbean left a reply on Floats Vs Integers • 5 days ago

@InspiredPrynce I’ve updated my answer.

martinbean left a reply on Floats Vs Integers • 5 days ago

@InspiredPrynce Your code is working as expected. 49.98 is greater than 49.

18th September, 2018

martinbean left a reply on Need To Create A RESTful API. • 6 days ago

Should I complete Laravel 5.4 from scratch first?

@burnedfaceless If you’re contemplating building something with the framework, then getting to grips with it would be a good idea, yes. There are plenty of videos on this site on getting started and using Laravel.

17th September, 2018

martinbean left a reply on MySQL Vs ENV For CMS • 1 week ago

@bacordioroger If the admin is setting the values, then why not just put them in a configuration file (something like config/site.php)?

martinbean left a reply on Need Advice About Model Relations • 1 week ago

@t0ne There seems to be three entities at play here: User, Department, and Profile. So a user would belong to many departments.

If a user should have a profile for each department they belong to, then you could make the fields that make up a profile columns on the department_user pivot table. You could then create a custom Pivot class (see “Defining Custom Intermediate Table Models” at https://laravel.com/docs/master/eloquent-relationships).

martinbean left a reply on REST Authentication • 1 week ago

@nic For routes, I’d register just the ones you need (i.e. the POST endpoints) and Auth::routes() will also register GET routes that will return the HTML views.

For the auth guard, it will assume the web guard by default but again this can be overridden in the trait. For example, in the RegistersUsers trait: https://github.com/laravel/framework/blob/7fa362999586fb47e05ce4478b693c49714ffb3a/src/Illuminate/Foundation/Auth/RegistersUsers.php#L41-L49

martinbean left a reply on REST Authentication • 1 week ago

@nic Authentication and password reset in Laravel is provided by traits. If you open the traits, you’ll see the processes are broken down into discreet methods, including returning responses. So you’ll need to override the methods that return responses in your application’s controllers.

For example, in the RegistersUsers trait there’s a registered() method that you can use to return a JSON response.

martinbean left a reply on MySQL Vs ENV For CMS • 1 week ago

@bacordioroger It depends if the settings need to be configured by the end user or not.

If you do use the database, be sure to cache it so you’re not querying the database for configuration settings on every page load.

15th September, 2018

martinbean left a reply on Laravel + Vue.js MPA/SPA Hybrid Structure Suggestions And Thoughts. • 1 week ago

@Gabotronix A pattern for what? I don’t know what you’re building.

Building up pages that are a single Vue component in themselves just have all the drawbacks of an SPA with no upside. Either build an SPA, or build a “traditional” app where you navigate page to page, and dynamic functionality is added using multiple Vue components.

A Vue component is meant to be used for exactly that: components of functionality; not building entire pages.

14th September, 2018

martinbean left a reply on Using A Trait To Apply A Global Scope • 1 week ago

@russellwwest Be warned—by someone who has done this in the past—that this becomes a pain if you try and use your models in another context, particular console commands (where there is no session and therefore no authenticated user) and admin panels where you don’t want your models scoped by the current user.

martinbean left a reply on How Do I Make A Customer Support Chat With Laravel Pusher • 1 week ago

@Rextech03 Creating a real-time chat support application from scratch is a huge project. I’d be very surprised if you’re going to find someone who’s created a guide from start to finish for you to copy.

martinbean left a reply on Laravel + Vue.js MPA/SPA Hybrid Structure Suggestions And Thoughts. • 1 week ago

@Gabotronix I’m not sure what benefit this gives? You’re just making your website as reliant on JavaScript as a SPA.

martinbean left a reply on Should I Pass $request To Repository? • 1 week ago

Should all $request processing be done in the controller then pass params to the resource

@mnmnmn Yes. Otherwise your repository is coupled to HTTP requests and can’t be used in other contexts in your application, i.e. a console command, queued job etc.

You should only pass data to your repository that the methods need. This could come from a HTTP request, but should be passed as an array so it can be mocked or take its input from another source (i.e. command line parameters):

class FooRepository
{
    public function create(array $data)
    {
        // Create a Foo object with $data; add it to the repository
    }
}
class FooController extends Controller
{
    private $foos;

    public function __construct(FooRepository $foos)
    {
        $this->foos = $foos;
    }

    public function store(CreateFooRequest $request)
    {
        // Pass validated data to repository
        $foo = $this->foos->create($request->validated());
    }
}

martinbean left a reply on How Not To Repeat Your Code In All Controller Routes? • 1 week ago

@MartinZeltin Does every view need chats, a list of users, messages etc? They sound like something that is in a menu bar and could probably be loaded via AJAX, rather than passed to every Blade view in your application. That’s just going to be a pain to maintain.

martinbean left a reply on Plan To Put Project To APP_ENV QA, And Behave The Same As Production, Changes Needed? • 1 week ago

@joveice The environment can be anything you want. It’s just a string value.

martinbean left a reply on Plan To Put Project To APP_ENV QA, And Behave The Same As Production, Changes Needed? • 1 week ago

@joveice There’s nothing stopping you from creating new config entries that read their values from the environment:

<?php
// config/services.php

return [

    'someapi' => [
        'key' => env('SOMEAPI_KEY'),
        'secret' => env('SOMEAPI_SECRET'),
    ],

];

The environment should not be something user-configurable and change the configuration; it’s just the environment of your application (and a helpful label if you send errors to something like Bugsnag). The actual configuration should be set by the environment your application runs in. This concept is actually one of the “12 Factors App methodology”: https://en.wikipedia.org/wiki/Twelve-Factor_App_methodology#The_Twelve_Factors

13th September, 2018

martinbean left a reply on What Popular Video Hosting Services To People Use? • 1 week ago

@hdifen Vimeo allows you to restrict videos to play back on white-listed domains only. Amazon also allows you to upload and only allow access from specific IPs or using a signed URL.

martinbean left a reply on Plan To Put Project To APP_ENV QA, And Behave The Same As Production, Changes Needed? • 1 week ago

Test and have it all configured in the app instead of in the config files.

@joveice Why? Config files are for configuration. The clue’s in the name.

Besides, your configuration should be in your environment. If you have a QA server, then that server should have configuration variables for DB_HOST, DB_USER etc that makes your application connect to a QA database. You should then be able to move the code to another server (i.e. your production server) that has its own set of variables defined for DB_HOST and so on to make your application connect to a production database.

martinbean left a reply on Login To Another Social Account While Logged In • 1 week ago

@mlazuardy I mean you should have separate routes to connect a Facebook or Google account. Then once a user has connected an account, they can log in with it using the login routes.

martinbean left a reply on Stripe Error: Invalid Token Id: Tok_visa • 1 week ago

@shifoodew I think you need to have a quick re-read of the Stripe documentation before accepting people’s money: https://stripe.com/docs/api/php#create_charge

martinbean left a reply on Update Nova Metrics (event) • 1 week ago

@Jurer I don’t know what you mean by “3 dots”.

Your component should load the map when mounted, and then also set up an Echo listener for your order created event that would do the animation when an order is placed.

export default {
    mounted() {
        this.displayMap();

        this.setupOrdersListener();
    },

    methods: { 
        displayMap() {
            // Render map in component
        },
        setupOrdersListener() {
            Echo.private('orders')
                     .listen('OrderPlaced', (event) => {
                    // Do animation for new order
                  });
        }
    }
}

martinbean left a reply on Stripe Error: Invalid Token Id: Tok_visa • 1 week ago

@shifoodew Look at your Charge::create() code. You have hard-coded tok_visa in there. tok_visa is a test token.

martinbean left a reply on Guzzle HTTP Says Magic Request Methods Require A URI And Optional Options Array • 1 week ago

@skeith22 You’re performing the request but not returning the result to a variable. You need to work on the response, not the client instance itself:

$client = new Client();

$response = $client->post('POST', 'https://my-domain.com/', [
    'form_params' => [
        'action' => 'read'
    ],
    'headers' => [
        'Authorization' => 'Bearer 57aa62501a7fe0d3b71de5712cdb1998'
    ]
]);

return $response->getBody();

martinbean left a reply on Plan To Put Project To APP_ENV QA, And Behave The Same As Production, Changes Needed? • 1 week ago

@joveice It’s impossible to say as no one knows how much (if at all) you’re relying on the environment in your application.

martinbean left a reply on Errors Manager For Model/functions • 1 week ago

@xkill You should be validating data before it reaches a model, i.e. a form request if in a controller.

martinbean left a reply on Is Dingo Still Necessary For API Development? • 1 week ago

@pillaykm Dingo was never “necessary” for API development. You can quite easily create an API using resource routes and Passport as you say.

martinbean left a reply on Login To Another Social Account While Logged In • 1 week ago

@mlazuardy You should have a section in your user’s settings that allows them to connect their Facebook and Google accounts.

martinbean left a reply on PHP Sessions • 1 week ago

@PK_06 No. Laravel disables the PHP session handler and registers its own.

martinbean left a reply on How Do I Add Events On Route::resource? • 1 week ago

@zenakent Route::resource() registers routes that point to methods in a controller class. You’d need to dispatch the event(s) in your controller actions.

martinbean left a reply on Using Destructor In Eloquent • 1 week ago

@tyteck What is it you want to measure? You can use something like Laravel Debugbar to measure various parts of your application.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.