martinbean

Software Developer at Pitchero

Experience

324,635

465 Best Reply Awards

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

24th November, 2017

martinbean left a reply on Generate A Secured Url • 21 hours ago

martinbean left a reply on How Can I Use Laravel Classes/traits?? Please Help • 21 hours ago

@Webiondev123 There’s nothing special about traits in Laravel. Traits are a PHP language construct. I think you’re better reading up on them if you don’t understand them: http://php.net/manual/en/language.oop5.traits.php

martinbean left a reply on Help Me Understand WithExceptionHandling() And WithoutExceptionHandling() • 21 hours ago

@thebigk The methods do exactly what they say on the tin: they run your tests with exception handling, or without.

Without exception handling is handy when doing HTTP tests, like:

$response = $this->get('/foo');

$response->assertSuccessful();

Your test is asserting the response status is successful, but you might get a 500. But by default, if you do get a 500 status you don’t know why. So if you disable exception handling, it will instead log that exception to the console for you to see why and then fix it:

$this->withoutExceptionHandling();

// If this throws a 500 error, it’ll now display in the console instead
$response = $this->get('/foo');

// This won’t be called, as the exception above will halt execution
$response->assertSuccessful();

martinbean left a reply on How To Name Polimorphic Table • 22 hours ago

@jimmy0699 You could go with something like user_content_views with the following columns:

  • user_id
  • content_id
  • content_type

And then use the created_at column to determine when they read/saw the message, notification, article etc.

martinbean left a reply on Define A Function Before The App Starts • 22 hours ago

@kaleopter That’s not how PHP works. You can’t keep a connection open between requests.

If it’s an API, then you hit a URL, retrieve the data, and the API request ends.

23rd November, 2017

martinbean left a reply on ProductController GetProduct() Method (Query) Problem • 1 day ago

@splendidkeen Suggestion would be to use resourceful controller names and route–model binding. So your ProductController should have a show() method, and could have a Product instance injected:

class ProductController extends Controller
{
    public function show(Product $product)
    {
        return view('product.show', compact('product'));
    }
}

I’m not sure why you’re querying a product by ID, running get() and then first() in that single-result collection. If you need to query a product by ID then use Eloquent’s find() method (or even better findOrFail() which will throw an exception if a row with that ID does not exist):

$product = Product::findOrFail($id);

Other than that, I don’t really understand your problem.

only the first Product of every business will be shown

If your route contains the business ID and the product ID, then surely you only want a single product returned?

martinbean left a reply on Php - Making A Class Instance That Has Dependencies In The Constructor • 1 day ago

What is the correct way of doing this?

@Leff7 To use the service container to resolve your dependencies. You shouldn’t be instantiating a controller from anywhere in your code though.

Instead, wrap your import logic into a class of its own, and then pull that class into where you need it:

class Importer
{
    public function __construct(Importable $data)
    {
        $this->data = $data;
    }
}
class ImportController extends Controller
{
    public function __construct(Importer $importer)
    {
        $this->importer = $importer;
    }
}
class ImportCommand extends Command
{
    public function __construct(Importer $importer)
    {
        $this->importer = $importer;
    }

    public function handle()
    {
        // Use $this->importer
    }
}

martinbean left a reply on Collections: First() Callback • 1 day ago

@defayeke You linked to the source code. You can see how it works from there.

  1. If no callback is given, it gets the first value from the array.
  2. If a callback is given, iterates over the array’s elements until the callback is true, and returns the element at that iteration.
  3. If the array has no elements, or the callback didn’t match any elements, the default value is returned (which is itself null by default).

So an example of it in use:

Given the array:

$array = [
    'apple',
    'banana',
    'orange',
];

$first_item_beginning_with_b = array_first($array, function ($item) {
    return starts_with($item, 'b');
}); // Will return 'banana' as that matches callback condition

martinbean left a reply on Changing The Bootstrap Version In Laravel 5.5 • 1 day ago

@ismael.m.desousa Change the version constraint in your package.json file:

"bootstrap": "4.0.0-beta.2"

martinbean left a reply on Create Slug + Id • 1 day ago

@zoldic You could generate the slug (minus the ID) and store it in your model when creating it, and then create a route pattern to find the thread by the combined ID and slug:

// Create pattern for {id}-{slug}
// {slug} can only be numbers, lowercase letters, or dashes
Route::pattern('threadSlug', '([0-9]+)-([0-9a-z-]+)');

Route::bind('threadSlug', function ($slug) {
    list($id, $slug) = explode('-', $slug, 2);

    return Thread::whereSlug($slug)->findOrFail($id);
});

22nd November, 2017

martinbean left a reply on Can't Properly Convert Raw SQL To Use Eloquent Query • 2 days ago

@fylyp90 No problem. Glad to have helped! :)

martinbean left a reply on Cart Session In A Stateless Environment • 2 days ago

@Devmaurice Not if it’s been made to work with sessions.

martinbean left a reply on Can't Properly Convert Raw SQL To Use Eloquent Query • 2 days ago

@fylyp90 It’s when you do a join and more than one table has the same column name. You just need to prefix the column with the table name:

->where('table_name.active', '1')

martinbean left a reply on Is There A Controller Naming Convention For An Acronym? • 2 days ago

@taf I’m in the singular controller names camp, so I’ll have things like ArticleController, EventController etc. My reasoning being, with the exception of the index() method, the other resource methods (create(), edit() etc) act on a single entity, so my ArticleController is controlling an article.

As for the issue of acronyms, I’ll still camelCase them. If you look at a new Laravel installation, you’ll see the Http folder is camelCased instead of being HTTP. It’s because if you were to then try to automatically snake_case that namespace or class name, you’d then get h_t_t_p or c_m_s_controller, which isn’t the intention.

Other than that, I echo other people’s thoughts: a “CMS controller” is definitely overly broad :)

martinbean left a reply on Cart Session In A Stateless Environment • 2 days ago

@Devmaurice You could either retrieve the cart based on the user’s ID (as I’m assuming the mobile apps send a token that’s related to a user) or when the cart is created, the client app saves that cart’s unique identifier and then makes any subsequent requests (i.e. adding a product, removing a product) against that ID.

martinbean left a reply on Do Not Want To Disable Middleware And Yet Get The Test To Green • 2 days ago

@thebigk Dump the response to see what Laravel’s giving you back:

$response = $this->post('/quiz/store', []);

$response->dump();

The test will halt and show you the raw response from that request, and you can diagnose the issue from there.

martinbean left a reply on Can't Properly Convert Raw SQL To Use Eloquent Query • 2 days ago

@fylyp90 I think it’d look more like this (untested):

$results = DB::table('tehnicki_pregledi')
    ->select('marka_naziv')
    ->addSelect(DB::raw('count(marka_id) as broj'))
    ->join('marke', 'tehnicki_pregledi.marka_id', '=', 'marke.id')
    ->where('active', '1')
    ->whereBetween('datum_pregleda', [
        '2017-01-01 00:00:00',
        '2017-02-01 00:00:00',
    ])
    ->groupBy('marka_id')
    ->orderBy(DB::raw('count(marka_id)'), 'desc')
    ->take(10)
    ->get();

martinbean left a reply on Laravel 5.5 On Cpanel Shared Hosting, Still Stucked With 500 Error, Now It Is The Time To 100% Solution • 2 days ago

i googled my question there was nothing except incomplete answers.

@igniter786 That’s because an infinite number of things can lead to a 500 error. A 500 error isn’t one specific problem, that’s why there isn’t one “100% solution”.

Instead, look in your error log and find out why your application is throwing a 500 error, and then fix that issue.

martinbean left a reply on Adding Data To A Model In A Query Scope • 2 days ago

So you would come from the Address model and look up the Users and bypass laravel's orm?

@bwrigley I’m not sure I follow. Yes, I’d go through the Address model, but the Address model is an Eloquent model, so there’s no “bypassing” of Laravel’s ORM.

21st November, 2017

martinbean left a reply on Adding Data To A Model In A Query Scope • 3 days ago

@bwrigley You either need to do the distance calculation (using the haversine formula) in the query, or sort your collection after the fact:

$addresses = Address::all()->sortBy(function ($address) use ($latitude, $longitude) {
    // Calculate and return distance here
});

martinbean left a reply on How Do You Work With Different Computer? • 3 days ago

One more thing is that I'm not so sure about heroku app. I heroku create on the other machine and I can't heroku open it on my machine.

@GTHell It’s because Heroku using the Git remotes to work out which Heroku app to open. When you create a Heroku app on one computer it will also set a Git remote called heroku (run git remotes to see this). When you clone your repository on another computer, it won’t have that remote set (again, run git removes and you’ll just have origin listed).

So you need to add the heroku remote (git remote add heroku https://git.heroku.com/your-app-name.git) on your other computers, and then you’ll be able to open your apps with heroku open.

martinbean left a reply on Video Freezes Until Mouse Moved • 3 days ago

I noticed the other day a message in the console saying playback was disabled without user interaction, so think it’s a Vimeo thing where they’re blocking auto-playing videos.

martinbean left a reply on Integrate Google Analytics Into Dashboard • 3 days ago

@theUnforgiven Yeah. Socialite’s got a Google provider.

You’ll need to request a specific scope (I don’t know which one(s) of the top of my head) to access their Analytics data, but once you have an access token you’ll be able to fetch things like page views and then render that data how you wish using a chart library.

martinbean left a reply on Database Structure • 3 days ago

@Uzenkov Have a look at polymorphic relations: https://laravel.com/docs/master/eloquent-relationships#polymorphic-relations

In your case, you would have a Client model with any common fields, but then morph to either a Person or Organisation model.

martinbean left a reply on Integrate Google Analytics Into Dashboard • 3 days ago

Basically just want to have a setting on their dashboard they enter the Google Analytics login details and ID or something then it reloads with their analytics data.

@theUnforgiven You‘re not going to be able to do that. Otherwise I could view-source on any site using Google Analytics, grab their tracking code, and be able to view their analytics data.

You’re going to need to authenticate with the user’s Google account via OAuth to be able to access their Analytics data I’m afraid.

20th November, 2017

martinbean left a reply on How To Scale And Optimize For Huge User Increase? • 4 days ago

@sirexzib I’d go through your app’s page and start eliminating duplicate queries (there’s four in your screen-shot). Then, look at commonly-occurring queries and look at caching them. That should start reducing the load on your MySQL database.

If you’re finding you’re still struggling, then look at maybe increasing the number of concurrent connections in your MySQL installation.

martinbean left a reply on How To Implement A Live Chat? • 4 days ago

Customer don't want to go with the live chat service because he spend a lot on other function already.

@GTHell Secure live chat systems aren’t easy to build. So your customer can either pay for an existing, tested live chat solution; or pay for one to be written from scratch that will need testing, may contain bugs, and ongoing development.

19th November, 2017

martinbean left a reply on Create Simple Admin Access (Logic Review) • 5 days ago

@taf Why are you trying to do something as important as user authentication from scratch for your first project? Especially when Laravel gives you great user authentication out of the box with things like session handling and automatically signed cookies for an extra layer of security.

Just run make:auth and then create some middleware that only allows your user account to access the protected routes. It can be as simple as:

class VerifyUserIsAdministrator
{
    public function handle($request, Closure $next)
    {
        if ($request->user()->email == '[email protected]') {
            return $next($request);
        }

        abort(403, 'User is not an administrator.');
    }
}
Route::prefix('admin')->namespace('Admin')->middleware(['auth', 'admin'])->group(function () {
    // Admin Routes...
});

16th November, 2017

martinbean left a reply on Best Way To Generate Page Titles? • 1 week ago

@Boubou I just define a section called title in my master layout, that defaults to the site name:

<!-- /resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html>
  <head>
    <title>@yield('title', config('app.name'))</title>
  </head>
</html>

I can then set it in Blade templates that extend this template:

<!-- /resources/views/home.blade.php -->
@extends('layouts.app')

@section('title', 'Home')

15th November, 2017

martinbean left a reply on Searching/Filtering/Sorting In Repositories • 1 week ago

I wouldn't want to put Eloquent queries in my controller!

@joshbrw Why?

martinbean left a reply on Searching/Filtering/Sorting In Repositories • 1 week ago

@joshbrw The “tranditional” definition of a repository is just to be able to access objects in a collection-like manner. So your repository classes would have a matching() method that takes criteria, and pulls out objects that, well, match the given criteria:

$results = $this->repository->matching($criteria);

This means that criteria isn’t “persisted” across usages. If a repository’s “adding” criteria with a addCriteria() method, then that’s more a query object and the developer’s not really understood the repository pattern.

It’s because of things like this that I’m just not a fan of the repository pattern at all. It introduces more problems than it fixes and repository classes just end up being full of inconsistently-named methods to get queries based on different criteria and for different contexts, i.e. fetching all results versus fetching results to be paginated.

martinbean left a reply on Bootstrap 4 Foreach Table Rows & And Individual Edit Modals • 1 week ago

@mwpdx If you read the Bootstrap documentation, I think this is the section you want:

http://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content

martinbean left a reply on Data Modelling And Business Rules • 1 week ago

@cjconnor24 You want to implement logic like that as close to your model as possible, because you may have multiple entry points where a booking can take place: a web UI, a PoS system, an API, and so on. If validation is separate from the model, then that’s a lot of places you need to duplicate your validation and keep in sync, and duplication’s bad for that reason.

Somewhere, you’d have a method that “books” a table at a restaurant, so you could put your availability checks in there:

class Restaurant extends Model
{
    public function bookTable(Table $table, DateTime $dateTime, int $guests)
    {
        if ($table->restaurant->isNot($this)) {
            throw InvalidTableException('Table does not belong to this restaurant.');
        }

        if ($table->unavailableAt($dateTime)) {
            throw new TableUnavailableException('Table is not available at the specified date and time.');
        }

        if ($guests > $table->capacity) {
            throw new TableOverCapacityException(
                sprintf('Table only has capacity for %d guests.', $table->capacity)
            );
        }

        return $table->bookings()->create([
            'datetime' => $dateTime->toDateTimeString(),
            'guests' => $guests,
        ]);
    }
}

Obviously this is a simplified example.

martinbean left a reply on Testing A Laravel Package • 1 week ago

@jvleeuwen A service provider just provides services, in that it binds things to the service container. So test that resolving something from the service container yields the type of object you expect:

$concrete = $this->app->make('Your\Interface');

$this->assertInstanceOf('Your\Concrete', $concrete);

martinbean left a reply on A Secret Pi Button On This Page • 1 week ago

@bantya It’s not so secret.

14th November, 2017

martinbean left a reply on Problem In Passing Role Through Route To Middleware • 1 week ago

@osama_mohamed The issue is with $perm->$role. The $perm instance doesn’t have a property called edit_shipment.

Instead of reinventing the wheel, I’d strongly consider looking at Laravel’s built-in authorisation component: http://laravel.com/docs/master/authorization

martinbean left a reply on Do NOT Update Chrome To 62 ! • 1 week ago

@shabany It’s not really a bug. The response is sent as text/html, so Chrome is actually rendering how it’s supposed to be.

martinbean left a reply on How To Use Database Engine's UUIDs With Eloquent? • 1 week ago

@Zini True. The reason I included it was in my application I have a trait that generates UUIDs on model creation as opposed to leaving it to the database itself:

namespace App\Concerns;

use Ramsey\Uuid\Uuid;

trait IdentifiesUsingUuids
{
    public static function bootIdentifiesUsingUuids()
    {
        boot::creating(function ($model) {
            $model->setAttribute($model->getKeyName(), Uuid::uuid4());
        });
    }
}

martinbean left a reply on How To Use Database Engine's UUIDs With Eloquent? • 1 week ago

@Zini There’s a $keyType property you need to set, so your model should look like this if you want to use UUIDs as primary keys:

class User extends Authenticatable
{
    protected $primaryKey = 'uuid';

    protected $keyType = 'string';

    public $incrementing = false;
}

13th November, 2017

martinbean left a reply on Architecture Question (user Belongs To Another User) • 1 week ago

@Laravelephant If a User can only be supervised by one other user, then you could add a supervisor_id column to the users table, and then define the relationship like this:

class User extends Authenticatable
{
    public function supervisor()
    {
        return $this->belongsTo(User::class, 'supervisor_id');
    }

    public function supervisingUsers()
    {
        return $this->hasMany(User::class, 'supervisor_id');
    }
}

10th November, 2017

martinbean left a reply on How To (properly) Use Form Requests + Policies + Resource Routes With Dependancies? • 2 weeks ago

@Quezler You can pass additional arguments to policies:

class EmployeePolicy
{
    public function create(User $user, Company $company)
    {
        return $user->can('update', $company);
    }
}
class CreateEmployeeRequest extends FormRequest
{
    public function authorize()
    {
        // Assumes company is in route, i.e.
        // /companies/{company}/employees
        return $this->user()->can('create', Employee::class, $this->company);
    }
}

9th November, 2017

martinbean left a reply on Gatekeeper • 2 weeks ago

8th November, 2017

martinbean left a reply on Controller Questions • 2 weeks ago

@archiebango Might be worth reading the Laravel documentation if you don’t understand what’s going on in that brief code snippet.

martinbean left a reply on Repository Pattern Vs Extended Model • 2 weeks ago

@CJJ I’ve been “practising” for 10 years now. I’ve yet to see a “nice” implementation of a repository. They always end up as classes bloated with inconsistently-named methods. Mainly because developers seem to think a repository is a place to use instead of models (it’s not) then have to create methods for every query combination that they just end up taking more time to maintain than the time saved “in case we decide to swap out Eloquent”.

This is not to mention that the prevalent “thinking” of what a repository should be among PHP developers isn’t actually what the pattern was intended for.

Repositories should be accessed as though it were a collection, and results filtered based on criteria. In one project, I had repositories where the data was coming from an API, and then criteria classes that mapped criterion to query string parameters. It’s usage looked like this:

class QuoteController extends Controller
{
    public function __construct(QuoteRepository $quotes)
    {
        $this->quotes = $quotes;
    }

    public function index()
    {
        $criteria = new CriteriaCollection([
            new CustomerCriteria($this->customer->getId()),
            new StatusCriteria('new'),
            new OffsetCriteria(0),
            new LimitCriteria(25),
            // and so on
        ]);

        $quotes = $this->quotes->forCriteria($criteria);

        return view('quote.index', compact('quotes'));
    }
}

So all repositories retrieved results by passing criterion to its forCriteria() method. Repeating queries could be wrapped up in methods on the repository class though:

class QuoteRepository extends Repository
{
    public function forCustomer(Customer $customer)
    {
        return $this->forCriteria(
            new CustomerCriteria($customer->getId())
        );
    }
}

And because the repositories were type-hinted, they could then be “wrapped” using the decorator pattern for say, caching:

class RepositoryServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(QuoteRepository::class, function ($app) {
            return new CachingQuoteRepository(
                new QuoteRepository
            );
        });
    }

    public function provides()
    {
        return [
            QuoteRepository::class,
        ];
    }
}

7th November, 2017

martinbean left a reply on So, How Do You Use Bootstrap 4, While Relying On Vue? • 2 weeks ago

@thebigk jQuery and Vue are two totally different libraries. Ones a JavaScript utility library, the other’s a library for building components. Besides, jQuery is installed and loaded by default in a new Laravel application: https://github.com/laravel/laravel/blob/master/resources/assets/js/bootstrap.js#L11

martinbean left a reply on Repository Pattern Vs Extended Model • 2 weeks ago

@giorgi What is an “extended” model?

@CJJ There is. Repositories always end up as messy classes stuffed full of inconsistently-named methods.

martinbean left a reply on Make Code Cleaner • 2 weeks ago

Would a switch statement not suffice?

class CampaignController extends Controller
{
    public function show(Campaign $campaign)
    {
        switch ($request->user()->type) {
            case 'user-type-a':
                $view = 'campaign.show.user-type-a';
                break;

            case 'user-type-b':
                $view = 'campaign.show.user-type-b';
                break;

            case 'user-type-c':
                $view = 'campaign.show.user-type-c';
                break;
        }

        return view($view, compact('campaign'));
    }
}

2nd November, 2017

martinbean left a reply on Image Gallery • 3 weeks ago

@Mike_91 You should save references of uploaded images to a database, and then let users picks a previously-uploaded image that way.

You really shouldn’t be letting them pick a file from a list enumerated from your actual file system as that’s just opening up an attack vector.

martinbean left a reply on Image Gallery • 3 weeks ago

to show him when clicking upload the local file system with my images

@Mike_91 I’m not sure I follow. Which “local” file system? You mean your server’s file system? If so, that sounds like a massive security risk.

Edit Your Profile
Update

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