martinbean

Freelance Developer & Consultant at MCB Web Design

Hire Me

Experience

287,745

419 Best Reply Awards

  • Member Since 2 Years Ago
  • 291 Lessons Completed
  • 1 Favorite

27th July, 2017

martinbean left a reply on Whoops Something Went Wrong! • 17 hours ago

@marins Why not look at your error log and actually see what the error was instead of assuming it’s the user’s session no longer being valid? As Laravel should be handling session lifetimes for you to avoid this problem.

martinbean left a reply on Best Practice For Multi Auth? • 18 hours ago

@archiebango No, don’t create four database tables, models, and set of controllers and views and auth user providers. That’s just a massive overhead and maintenance headache.

Users are users. Add a role column or something to your users table and use middleware to determine what a user can see based on their role.

24th July, 2017

martinbean left a reply on Store Credit Card Information Into Database • 3 days ago

@Tyris No problem. Glad to help :)

23rd July, 2017

martinbean left a reply on Getting A Single Item From List Of Data • 4 days ago

@Lordgreymaul What’s the question/issue?

martinbean left a reply on Need Help With A Database Deisign. • 4 days ago

@skadimoolam That’d be a many-to-many relation, with an additional column on the pivot table to store the price a particular supplier offers for a particular product.

class Product extends Model
{
    public function suppliers()
    {
        return $this->belongsToMany(Supplier::class)->withPivot('price');
    }
}
class Supplier extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class)->withPivot('price');
    }
}

martinbean left a reply on Store Credit Card Information Into Database • 4 days ago

@Tyris As mentioned above, if you store credit card information then there are legal requirements you have to adhere to called PCI and hefty fines if you don’t.

If you use a payment processor like Stripe, credit card details are stored on their systems (and never touch your server), so the PCI compliance burden is on them and not you.

21st July, 2017

martinbean left a reply on How To Clean Code • 6 days ago

@Lina The first thing I’d to is format your code to follow the PSR-1 and PSR-2 conventions. It’s much easier to spot typos and the like in the code if it’s consistently formatted.

I’d then start moving the conditions to methods on models. So this massive `if statement:

if( Auth::user()->idRole == Config::get('app.ROLE_ADMIN') || Auth::user()->idRole == Config::get('app.ROLE_TRADER_DIRECTOR') ){

I’d then re-factor the massive `if statement where you’re checking if a user is an admin or trader director into a policy method:

class TradingAccountPolicy
{
    use HandlesAuthorization;

    public function create(User $user)
    {
        return in_array($user->idRole, [
            config('app.ROLE_ADMIN'),
            config('app.ROLE_TRADER_DIRECTOR'),
        ]);
    }
}

You can then use middleware to authorise the method instead:

public function saveTradingAccount(Request $request)
{
    // Replace second parameter with actual model
    $this->authorize('create', TradingAccount::class);

    // snipped
}

Validation can also be moved to a custom request class. So you could have a CreateTradingAccountRequest and type-hint that instead:

public function saveTradingAccount(CreateTradingAccountRequest $request)
{
    // snipped
}

I think checking the status code of the Guzzle request is redundant, as I believe a client or server exception will be thrown instead. Rather, make the call in a try / catch block:

try {
    $response = $client->post(config('app.EA_SERVER_URL').'storeTradingAccount', [
        'verify' => false,
        'form_params' => $request->only('idAccount', 'namedAccount'),
    ]);

    return redirect()->back()->withSuccess(trans('languages.added_account'));
} catch (ClientException $e) {
    return redirect()->back()->withError(trans('languages.internal_error'));
}

In fact, if you just want to display a generic error message if a Guzzle exception is thrown, then just let the exception handler handle it:

public function render($request, Exception $exception)
{
    if ($exception instanceof ClientException) {
        return redirect()->back()->withError(trans('languages.internal_error'));
    }

    return parent::render($request, $exception);
}

I imagine you’ll be calling that Guzzle client elsewhere in your application with the same base URI, so I’d create a custom client and then resolve that in your controller actions:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->singleton('your.client', function () {
            return new Client([
                'base_uri' => config('app.EA_SERVER_URL'),
            ]);
        });
    }
}

Finally, I’d then follow the convention for resourceful controller action names. So creating a trading account would be done via a `store method in a `TradingAccountControll class.

So taking into account the above, your controller could end up looking like this:

class TradingAccountController extends Controller
{
    public function store(CreateTradingAccountRequest $request)
    {
        $this->authorize('create', TradingAccount::class);

        $response = app('your.client')->post('/storeTradingAccount', [
            'verify' => false,
            'form_params' => $request->only('idAccount', 'nameAccount'),
        ]);

        return redirect()->back()->withSuccess(trans('languages.added_account'));
    }
}

Much leaner and easier to follow, I’m sure you’ll agree.

martinbean left a reply on Passing Sensitive Information Through Props? • 6 days ago

@AR I don’t see why not. If your Vue component needs to know what permissions a user has, you need to pass that somehow.

Even if the user managed to manipulate the property and re-initialise the Vue component, you should have server-side validation that again checks the user’s permissions and prevents the action the user’s trying to do.

martinbean left a reply on Passing Sensitive Information Through Props? • 6 days ago

@AR I’m not sure about that syntax. I think it should be something like this:

<productview can-edit="{{ Auth::check() && Auth::user()->can('update', $shop) }}"></productview>

martinbean left a reply on How To Achieve This On Laravel 5 Eloquent • 6 days ago

@jplans The full error message will also contain a file name and line number. So go there, and that’s where your problem is.

20th July, 2017

martinbean left a reply on How To Make Check Funchtion • 1 week ago

You should not be accessing the $_POST super-global. Read the request documentation on how to access submitted data.

martinbean left a reply on Difference Between A Trait And A Parent Class • 1 week ago

@mvww11 A trait is for bundling related methods that can be used by multiple classes; multiple classes that may already be extending one parent class.

martinbean left a reply on So, Do You TDD? • 1 week ago

@thebigk Writing tests doesn’t mean you’re a bad developer. They’re not training wheels. It’s automating what you do in a browser, where you manually click things on a page, fill out forms etc. It’s ensuring that logic is correct.

Again, it may take more time upfront, but will save you time in the long run by alerting you to any breaking code changes. How many times have you written something that’s had a knock-on effect on something else? A test suite will alert you of those instances sooner rather than later.

martinbean left a reply on Guzzle Http Post Request Not Working. • 1 week ago

@larafam If you’re getting 500 errors, then check your Laravel error log.

martinbean left a reply on Adding Polymorphic Taxonomies • 1 week ago

@maxnb I’m not sure I follow. Why do you need a polymorphic relationship? It seems you have terms that can be multiple “types”, so it’d just be a belongs to/has many relationship.

class Taxonomy extends Model
{
    public function terms()
    {
        return $this->hasMany(Term::class);
    }
}
class Term extends Model
{
    public function taxonomy()
    {
        return $this->belongsTo(Taxonomy::class);
    }
}
$taxonomy = new Taxonomy(['name' => 'Category']);

$taxonomy->terms()->create(['name' => 'Sports']);
$taxonomy->terms()->create(['name' => 'Politics']);
$taxonomy->terms()->create(['name' => 'Technology']);

Unless I’m misunderstood your intent?

martinbean left a reply on How Can I Use Guzzle To Make A Post Request To Vertifire API Using Laravel? • 1 week ago

@dimnks The keys in your data array aren’t write. You need to actually expand the data like this:

$request = $client->post('v2/serp/url', [
    'headers' => config('guzzleapi.vertifire_auth'),
    'data' => [
        'terms' => [
            [
                'term' => 'videos',
                'url' => 'wikipedia.org',
                'sep' => [
                    'search_engine' => 1,
                ],
            ],
        ],
    ]
]);

martinbean left a reply on How To • 1 week ago

@ujjwal Please put a bit of effort in to writing your questions if you’re expecting other developers to put effort into answering them.

martinbean left a reply on So, Do You TDD? • 1 week ago

@thebigk It takes time, but it’s worth it. Not thinking of tests as a “waste of time” is the first step.

Yes, it may take more time to write tests as well as code, but having that code tested saves you time in the long run as you build up a test suite that will tell you if you change something that breaks something else, something that happens and you may not pick up until that bug’s in production.

Also, writing tests makes you think about the code you’re writing, and leads to better code, instead of just writing lines of code to get a feature working. There’s also time saved as if you have a test, then you don’t need to open a web browser to manually test that the change(s) you’re making aren’t breaking things. You run a test, if it’s green, you carry on.

It took me years to get on board with testing, but I now get it. Once you stop seeing it as a chore and write your tests first instead of after writing a feature, you become more productive. Because we both know that stuff you leave until “later” never gets done.

So instead of thinking, “Urgh, have to write a test for this now” write the test, and have that drive the code you write. That’s why it’s called test-driven design.

martinbean left a reply on Issue, How To Use && Function • 1 week ago

@diadal Sure. Glad to help and see you’ve awarded yourself the answer.

martinbean left a reply on How To Pass Request Data To Mailable? • 1 week ago

@SeongjuneKim You should be able to pass multiple arguments to a mailable. I’m sure I’ve got a project where I do so. You’ll need to amend your constructor to take those arguments:

class Report extends Mailable
{
    public $content;
    public $from;

    public function __construct($content, $from)
    {
        $this->content = $content;
        $this->from = $from;
    }
}
Mail::to($user)->send(new Report($request->content, $request->from));

martinbean left a reply on Run Composer Commands From Controller • 1 week ago

@cjustado@gmail.com You can’t run a command from a Laravel controller as the framework won’t be installed. That’s what @tykus means by chicken and egg. You want to use Laravel to install Laravel.

19th July, 2017

martinbean left a reply on How To Pass Request Data To Mailable? • 1 week ago

@SeongjuneKim I’m not sure you can serialize a HTTP request instance like this, as things like any uploaded files would be lost.

Instead, pass the data as an array to your mailable:

class Report extends Mailable
{
    public $data;

    public function __construct(array $data)
    {
        $this->data = $data;
    }
}
Mail::to($user)->send(
    new Report($request->input())
);

martinbean left a reply on Conventions For Sharing Data Between Controllers And Views • 1 week ago

@neokris You need to think about the entities in your application. Once you have them modelled, creating controllers around them is easy.

Stop trying to clump the concept of “users” and “settings” together. If you have different names for them then that usually means they’re separate entities. There’s nothing stopping you having a controller for users, and a separate controller for settings.

If you follow the convention for resource controllers, then you would use an index() action for displaying a list of records, a show() method for showing an individual record, an edit() method for showing the form to edit a record, and then update() to handle the actual updating of a record.

If you have a separate controller for settings, then “re-using” method names doesn’t become an issue.

class UserController extends Controller
{
    public function update(UpdateUserRequest $request, User $user)
    {
        $user->update($request->all());

        // Redirect with success message
    }
}
class SettingsController extends Controller
{
    public function update(UpdateSettingsRequest $request)
    {
        // Update settings for current user
        // You can get current user with $request->user()

        // Redirect with success message
    }
}

martinbean left a reply on Detecting Variable Scope Issues • 1 week ago

@Kerren I’m struggling to understand what your code example is doing.

If you’re having scope issues, then it usually points to something being too “fiddly” that could do with a re-factor to simplify.

martinbean left a reply on Run Composer Commands From Controller • 1 week ago

Why would you want to do this?

If you have something that needs to be ran in a controller and a console command, then re-factor it into its own class.

class SomeClass
{
    public function someMethod()
    {
        // Do something
    }
}
class SomeController extends Controller
{
    public function someAction()
    {
        $something = new SomeClass;
        $something->someMethod();
    }
}
class SomeCommand extends Command
{
    protected $signature = 'some:command';

    public function handle()
    {
        $something = new SomeClass;
        $something->someMethod();
    }
}

martinbean left a reply on Issue, How To Use && Function • 1 week ago

@diadal && is a conditional operator, used in PHP, in things like if statements.

If you want to form an Eloquent query with two WHERE clauses, then you can just chain two usages of the where() method together:

$following = Following::where('target_id','=',Auth::id())
    ->where('user_id','=',$user->id)
    ->first();

$following->delete();

Also, you don’t need to assign the result to a temporary variable to call `delete. Again, you can just chain it:

Following::where('target_id','=',Auth::id())
    ->where('user_id','=',$user->id)
    ->first()
    ->delete();

martinbean left a reply on Array Validation: Retrieve Id Of Current Record For Except Rule • 1 week ago

@daniel.schreij If you have a controller action with parameters, then you can grab the ID from the route.

Say you have this action:

class SomeController extends Controller
{
    public function update(UpdateRequest $request, $id)
    {
        // Logic to update record
    }
}

You can do something like this in your form request class:

class UpdateRequest extends FormRequest
{
    public function rules()
    {
        return [
            'installed_trees.*.code' => [
                Rule::unique('trees')->ignore($this->route('id')),
            ],
        ];
    }
}

If you’re using route–model binding, the he `rou parameter will give you a model instance instead, so you’ll need to reference the primary key property instead:

Rule::unique('trees')->ignore($this->route('tree')->id),

martinbean left a reply on Is There Anyway To Know Which Which Query Runned While Inserting Through Eloquent? • 1 week ago

DB::listen(function ($query) {
    Log::debug($query->sql, $query->bindings);
});

martinbean left a reply on How To Use Request Instance To Store A File For An Array Of Input ? • 1 week ago

@abdullah71 You seem to be overcomplicating things.

If you have a HTML form with multiple file inputs like this…

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="problem_pdf[]" />
    <input type="file" name="problem_pdf[]" />
    <input type="file" name="problem_pdf[]" />
    <button type="submit">Submit</button>
</form>

…Then you can just access those files as an array in your controller like this:

class ProblemController extends Controller
{
    public function store(CreateProblemRequest $request)
    {
        foreach ($request->files->get('problem_pdf') as $file) {
            // Do something with each file
        }
    }
}

martinbean left a reply on Delay Execution Of An Event Listener By A Specific Time • 1 week ago

@thirdwunder I’m not sure I follow.

I’d dispatch an event when the CSV has finished uploading. The event would have a listener, to process the images contained in the CSV.

If CSVs have the possibility of containing already-uploaded images, then your listener can just do a quick check and not re-process it if it already exists.

protected $listen = [
    Events\CsvFileUploaded::class => [
        Listeners\ProcessUploadedImages::class,
    ],
];
class ProcessUploadedImages
{
    public function handle(CsvFileUploaded $event)
    {
        // I don’t know how you retrieve images in your CSV files
        foreach ($images as $image) {
            if ($image->alreadyProcessed()) {
                // Don’t process already-uploaded image
                continue;
            }

            // Add a job to your queue to process the new image
            dispatch(new ProcessImage($image));
        }
    }
}

Your listener listens for when a CSV file is uploaded, grabs the images from that file (you’ll need to add that logic), and then for each new image, adds a job to a queue to process that new image.

martinbean left a reply on Delay Execution Of An Event Listener By A Specific Time • 1 week ago

@thirdwunder That’s a very fragile approach. What if the CSV import does take longer than 5 minutes? Or fails completely?

Why not use events for their intended purpose? You want to process images after a CSV file’s been uploaded, so why not raise an event when that happens? Dispatch a `CsvFileImport event and then have a listener that goes off and processes the images in response to that.

This way, images are only processed after the CSV file has been uploaded. And if the CSV file is uploaded quickly, there isn’t a delay in processing images whilst your application waits for the arbitrary 5-minute delay to expire.

18th July, 2017

martinbean left a reply on How Would I Pull This Off With Bootstrap? • 1 week ago

@Doga A container has gutters. If you want to set a background colour, then wrap it all in another &lt;div&gt;:

<div class="section-wrapper">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-6">
        <p>Half-width column.</o>
      </div>
      <div class="col-md-6">
        <p>Half-width column.</o>
      </div>
    </div>
  </div>
</div>

You’d apply the background colour to .section-wrapper.

martinbean left a reply on How Would I Pull This Off With Bootstrap? • 1 week ago

@Doga “Centred” how? You’re using a fluid container, so the row’s going to occupy all of the horizontal space.

martinbean left a reply on Manipulate Data In Model • 1 week ago

@freshface Have you looked at the [documentation for Eloquent]?

Eloquent offers “accessors” that will allow you to define a method that would do this for you: https://laravel.com/docs/master/eloquent-mutators#defining-an-accessor

martinbean left a reply on Looking For A Starting Point Project • 1 week ago

@siyea You’re not going to find a “template” that fits your requirements. Laravel itself is a “starting point”.

martinbean left a reply on How To Retrieve The Current Users Id Who Has Logged In!!! • 1 week ago

@Naveena Can you just flesh out your original post with relevant information. Otherwise it’s just going to be a massive back-and-forth between you and other forum members, asking you questions trying to get to the bottom of your issue.

If Auth::id() is giving you hashes then it looks like you’ve modified Laravel’s authentication system somehow. So start there, tell us what changes you’ve made.

martinbean left a reply on PUT Won't Work, But POST Does Instead • 1 week ago

@Tangaye No. All you need to do is change the method attribute on your <form> tag to be POST, and then include the hidden input that tells Laravel it should be treated as a PUT request instead.

martinbean left a reply on PUT Won't Work, But POST Does Instead • 1 week ago

@Tangaye Most web browsers only support the GET and POST methods for HTML forms.

Instead, you’ll need to send a POST request, but also send a hidden input called `_meth (note the underscore) with a value of “PUT”:

<form action="{{ route('student.update', $student) }}" method="POST">
    <input type="hidden" name="_method" value="PUT" />
    <input type="hidden" name="_token" value="{{ csrf_token() }}" />

    <!-- Your other form fields -->
</form>

Laravel will treat this as a PUT request and not a POST request then.

martinbean left a reply on Multiple Databases In Laravel. • 1 week ago

@SimranKahlon I hope you’re not planning on having many customers if you’re creating a database per tenant.

martinbean left a reply on Make:auth With Multiple User Table • 1 week ago

@Tyris It is possible to create a foreign key for the company_id field so long as it’s nullable.

17th July, 2017

martinbean left a reply on Delay Execution Of An Event Listener By A Specific Time • 1 week ago

@thirdwunder Events are dispatched when something happens in your application, and listeners are supposed to handle those events when they occur, not at a later date.

I think you’re instead looking for a queued job, which can be delayed (https://laravel.com/docs/5.4/queues#delayed-dispatching).

However, wouldn’t you want thumbnails of uploaded images created as soon as possible? Therefore, I’m not sure why you want generation to be delayed?

martinbean left a reply on Is Spark Is The Best Way To Start A Project? • 1 week ago

@KodeCept Spark isn’t a just a Laravel starter kit, it’s a starter kit—built on Laravel—specifically for subscription-based, “software-as-a-service” (SaaS) apps.

So it really depends on the type of app you’re building. There’s no straightforward “yes” or “no” answer.

martinbean left a reply on Dynamic Generate Form From Table Structure Mysql • 1 week ago

@heefoow Loop over the schema and output a form field depending on the column type.

martinbean left a reply on Make:auth With Multiple User Table • 1 week ago

@Tyris Don’t create a model/table for each user “type” in your application system. It’s just a maintenance nightmare. What happens if you introduce a fourth user type to your system? Are you going to create another model and table?

Just add a role column to your users table that designates what type of user they are. Then, apply middleware to your routes to restrict access to users of certain types:

namespace App\Http\Middleware;

use Closure;

class VerifyUserIsOfType
{
    public function handle($request, Closure $next, ...$types)
    {
        if (in_array($request->user()->type, $types)) {
            return $next($request);
        }

        abort(403);
    }
}
Route::group([
    'middleware' => ['auth', 'type:partner/administrator'],
], function () {
    // Routes that only partners and administrators can view
});

martinbean left a reply on Shopping Cart Migration • 1 week ago

No one can really answer as we don’t know your shopping cart’s requirements, so therefore don’t know if you “missed” something or not.

martinbean left a reply on Sending Email With Laravel!! • 1 week ago

@issam90 Best way is to use an external service, like Mailgun or Amazon SES!!

16th July, 2017

martinbean left a reply on Require Only One Field Validation • 1 week ago

@michaellindahl I don’t really understand the issue. The required_without should be doing what you’ve described?

martinbean left a reply on Where Should I Put This? • 1 week ago

@lars6 Yeah, this is why I’m not a fan of the repository pattern, as I’ve never seen a “good” implementation of it because there’s just so many different ways of retrieving objects—such as paginated—that just means repositories end up stuffed full of inconsistent methods to satisfy each use case.

15th July, 2017

martinbean left a reply on Where Should I Put This? • 1 week ago

@lars6 Yes. That’s what a repository’s for. You have to do something in it. They don’t just work on their own.

The idea of putting something like…

public function all()
{
    return Animals::all();
}

…in a repository is so that your client code doesn’t depend on Eloquent. If you have a controller, then you’d have something like this:

class AnimalController extends Controller
{
    protected $animals;

    public function __construct(AnimalRepository $animals)
    {
        $this->animals = $animals;
    }

    public function index()
    {
        $animals = $this->animals->all();

        return view('animal.index', compact('animals'));
    }
}

Your controller class doesn’t interact with Eloquent directly, only your repository, which means you can swap a repository out with an alternative implementation (so long as it conforms to the same interface) or that you can take that controller class and import it in to another, non-Laravel application.

martinbean left a reply on Where Should I Put This? • 1 week ago

@lars6 Yup. Which means those methods too should be on the entity. A repository is a collection of objects that you’re accessing, but the repository is supposed to hide the implementation detail of where those objects are stored, i.e. it could be a relational database or an API or a file on the file system.

Edit Your Profile
Update

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