martinbean

Software Developer at Pitchero

Experience

312,095

451 Best Reply Awards

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

22nd September, 2017

martinbean left a reply on Getting Auth User Very Eatly In Bootstrap Process • 1 day ago

@gjm What handler is it you’re trying to push? As most third-party services, their SDKs will automatically push additional, contextual information if it’s available.

martinbean left a reply on Getting Auth User Very Eatly In Bootstrap Process • 1 day ago

@gjm If you have errors being thrown that early in your application, then I think you have more to worry about than if the user is logged in or not.

martinbean left a reply on Getting Auth User Very Eatly In Bootstrap Process • 1 day ago

@gjm How are you setting up the logging handler?

21st September, 2017

martinbean left a reply on Searching With Relationships Help!! • 2 days ago

@theUnforgiven Are you just wanting to search based on the passed data? Just add the data as where() to your query:

class VacancyController extends Controller
{
    public function index(Request $request)
    {
        $keywords = $request->query('keywords');
        $location = $request->query('location');
        $salary = $request->query('salary');

        $vacancies = Vacancy::query()
            ->when($keywords, function ($query) use ($keywords) {
                // Add WHERE clause to filter by keywords
            })
            ->when($location, function ($query) use ($location) {
                // Add WHERE clause to filter by location
            })
            ->when($salary, function ($query) use ($salary) {
                // Add WHERE clause to filter by salary
            })
            ->paginate();

        return view('vacancy.index', compact('vacancy'));
    }
}

martinbean left a reply on Insert Session() To Database After Login • 2 days ago

@Tyris If you’re wanting to create a cart for the user’s current session, then you could have a class that retrieves it or creates it if necessary:

class Cart
{
    public static function forRequest($request)
    {
        return static::firstOrCreate([
            'session_id' => $request->session()->getId(),
        ]);
    }
}

20th September, 2017

martinbean left a reply on Either Of Multiple Middleware • 3 days ago

@zagreus The auth middleware in Laravel allows you to specify multiple guards. It’ll loop through and try to authenticate with each. If authentication fails using all guards, then an “unauthenticated” exception will be thrown:

Route::middleware('auth:jwt,api_token')->group(function () {
    // Your protected routes
});

martinbean left a reply on Need Some Advice On What's Best Solution To Implement Import Class For All Models • 3 days ago

@t0ne What is it you’re actually trying to do? What is it you’re wanting to import, and to where?

martinbean left a reply on Filtering Your Repository • 3 days ago

@it-systemmanagement This is one of the reasons why I don’t like repositories. They’re just so hard to get right and then method names get inconsistent across them.

The way Martin Fowler describes the repository pattern is that it is a “collection” of objects. In the examples in his book Patterns of Enterprise Application Architecture, he then introduces the concept of filtering that collection with “criteria”. So the idea is not to have individual methods for different “queries”, but a matching() method that takes a list of criteria of objects you want to filter the collection down to. Usage that looks like this:

$repository = new PartnerRepository;

$criteria = new Criteria;
$criteria->push(new NameFilter('ACME'));
$criteria->push(new CountryFilter('USA'));

$partners = $repository->matching($criteria);

If you’re repository is operating on an Eloquent model, then these filter classes may manipulate the underlying query:

class NameFilter implements Filter
{
    protected $name;

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

    public function filter(Query $query)
    {
        return $query->whereName($this->name);
    }
}

The matching() method of the repository would then loop over the passed criteria, apply them, and return the results:

abstract class EloquentRepository implements Repository
{
    public function matching(CriteriaCollection $criteria = null)
    {
        $query = $this->query();

        if ($criteria) {
            $criteria->each(function ($criterion) use ($query) {
                $criterion->filter($query);
            });
        }

        return $query->get();
    }

    abstract protected function query();
}

Extending repositories will need to implement the query() method:

class PartnerRepository extends EloquentRepository
{
    protected function query()
    {
        return Partner::query();
    }
}

Of course, you can then add methods to your repository that automatically assemble the criteria, so you don’t have to do this in your controllers/elsewhere:

public function findByNameAndCountry($name, $country)
{
    $criteria = new Criteria;
    $criteria->push(new NameFilter($name));
    $criteria->push(new CountryFilter($country));

    return $this->matching($criteria);
}

But again, this starts going towards the initial problem of repositories just becoming full of numerous, inconsistently-named methods as you add methods to handle each permutation of “query” you need.

19th September, 2017

martinbean left a reply on Is There Any Way To Check Internet Connection On Web. • 3 days ago

@sam0081 Yes. If your website works you’re online.

martinbean left a reply on How To Decrypt Bcrypt Password • 3 days ago

@sam0081 That’s to be expected: bcrypt generates different hashes for the same input.

You can check the old password against the hash in the database like this:

if (Hash::check($request->input('old_password'), $user->password)) {
    // The old password matches the hash in the database
}

martinbean left a reply on Using Where Clause In Controller • 4 days ago

@aminbaig You shouldn’t really be doing queries in your controller. Instead, you should be calling methods on your models.

If you think about what it is you’re trying to do, this can drive out the names of your methods and which class to put them on. So products that are not ordered by the current user might give you:

class Product extends Model
{
    public static function notOrderedBy(User $user)
    {
        //
    }
}

You can then “tuck” the logic away for this in your model method, and call it in your controller:

public function index(Request $request)
{
    $products = Product::notOrderedByUser($request->user());
}

The implementation may look something like this:

public static function notOrderedBy(User $user)
{
    $orders = $user->orders()->with('products')->get();
 
    $orderedProducts = $orders->map(function ($order) {
        return $order->products->pluck('id');
    })->flatten();

    return static::whereNotIn($orderedProducts)->get();
}

This is assuming a User has many Order models, and an Order has many Product models.

martinbean left a reply on How To Add Accessors To Json Serialized Model On The Fly • 4 days ago

@Jdev What is it you’re want to “access”?

martinbean left a reply on Laravel Notification: Is It Similar To Webhooks? • 4 days ago

@aldryn.gutierrez Notifications are more for notifying users via email, SMS etc. A webhook would probably be a queued listener on an event (so the sending of the webhook doesn’t slow down the user on your application).

protected $listen = [
    Events\OrderCreated::class => [
        Listeners\SendOrderCreatedWebhook::class,
    ],
];

martinbean left a reply on How To Add Validator Name In Response • 4 days ago

@SyedAbuthahir What do you mean by “validator name”?

18th September, 2017

martinbean left a reply on .dev As New GTLD • 4 days ago

I’ve personally always used localhost.example.com for development URLs.

martinbean left a reply on Advice On Custom Function • 4 days ago

@Kiehlinit It’s not really a model unto itself. If permissions belong to a user, then I’d have put a method on the User model, which you’d then be able to call like:

Auth::user()->hasPermission('foo-permission')

You would then be able to call this in controllers, views, and any other PHP classes.

martinbean left a reply on How To Integrate Stripe Checkout With Laravel (5.4) Cashier? • 4 days ago

@ajck A token is exactly that: a tokenised version of the card details the customer provided. You get a token instead of card details (number, expiry, CVC etc). From there, it’s up to you how much you charge, so if I user POSTs the ID of a basic plan then that’s what you’d bill them for.

If you look at the Cashier docs, you’ll see that the charge() and invoiceFor() methods accept the amount to be charged. When creating subscriptions with the newSubscription() builder, you would pass the name of a plan in your Stripe account, and then Stripe will bill the user the price of that plan as set in your account.

15th September, 2017

martinbean left a reply on Clicks Per Post • 1 week ago

@Mike_91 You could also implement something like Google Analytics, which is much more refined at tracking hits from users.

martinbean left a reply on Clicks Per Post • 1 week ago

@Mike_91 Right? That‘s what you’re doing: incrementing a count every time the article’s loaded? What else are you expecting?

martinbean left a reply on Dynamic Routes And Route Names? • 1 week ago

@psyopus So a new page on URLs was adding to the Laravel documentation which seems to cover this very topic!

https://laravel.com/docs/5.5/urls#default-values

So you could use the route() helper as normal, and then set the “default” for the {locale} parameter:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\URL;

class SetDefaultLocaleForUrls
{
    public function handle($request, Closure $next)
    {
        URL::defaults([
            'locale' => $request->user()->locale,
        ]);

        return $next($request);
    }
}

martinbean left a reply on Please Convert Sql Raw Query To Laravel Eloquent • 1 week ago

@aqibali5107333 This isn’t a forum to get people to write Laravel code for you for free. Try yourself, and then feel free to post a question if you’re having a specific issue with the query builder.

martinbean left a reply on Update Laravel Using Bitbucket Pipelines • 1 week ago

@bashy Possibly a timestamp or something is updated. But either way, an update should not be ran on deployment, otherwise you’re no deploying the code—and library versions—defined in your source repository. And if you’re deployment process updates a dependency from version A to version B, how do you get that back in to your repository? Your repository is still going to have version A committed in the lock file.

martinbean left a reply on Dynamic Routes And Route Names? • 1 week ago

@psyopus All the Laravel helper functions are wrapped in if (! function_exists()) calls, so I think if you define the route() function in your application, it’ll use your’s instead of the one that comes with Laravel.

martinbean left a reply on How To Contact First_name And Last_name In Pluck Method Using The Relationship • 1 week ago

@wangchen What do you mean by “contacted” full name? Do you mean concatenated full name?

You’ll probably have to map over the collection instead:

$contacts = Account::find($account_id)->contacts->maps(function ($contact) {
    return trim(sprintf('%s %s', $contact->first_name, $contact->last_name));
});

14th September, 2017

martinbean left a reply on Update Laravel Using Bitbucket Pipelines • 1 week ago

@spyridonas It doesn’t matter. A minor update is still going to update your composer.lock file. When you deploy, you deploy files in a known state.

martinbean left a reply on Update Laravel Using Bitbucket Pipelines • 1 week ago

@bashy It’ll be their composer.lock file if they’re running a composer update.

martinbean left a reply on Inside Laravel Helper Twilio Funcion Env() Function Not Working • 1 week ago

You should not be using env() inside your application. You should instead be using config values.

Set a config value using environment variables in your config/services.php file:

'twilio' => [
    'sid' => env('TWILIO_SID'),
    'token' => env('TWILIO_TOKEN'),
    'from' => env('TWILIO_FROM'),
],

Then reference those in your application’s code:

$client = new Client(
    config('services.twilio.sid'),
    config('services.twilio.token')
);

martinbean left a reply on So Very, Very Lost In A Polymorphic Relationship • 1 week ago

@jgravois I might have misunderstood, but if you have a single polymorphic relationship, then how do you show a task that requires tools and a user?

martinbean left a reply on Update Laravel Using Bitbucket Pipelines • 1 week ago

@spyrosjeva You can’t do this, as it means your application is changing versions.

If you try and deploy one version, but then run composer update, then bugs may be introduced by an updated package. This is what a composer.lock file is for: it locks dependencies at known versions. Therefore, you should manually run composer update in your local environment, commit (so the new composer.lock file is committed), and then deploy.

martinbean left a reply on How To Set Up Relationship Between Two Models • 1 week ago

@flex A task has many comments; a comment belongs to only a single task.

Please read the Laravel documentation on one-to-many relationships, as it’s all explained in there.

martinbean left a reply on So Very, Very Lost In A Polymorphic Relationship • 1 week ago

@jgravois Yeah, it still doesn’t feel like a polymorphic relationship to me. Especially if a task needs techs and equipment or tooling.

If it’s some sort of booking/work allocation system, then you could have task assignees, and each assignee is then allocated to an item of equipment or tooling station. You’ll then be able to query your tasks and see who’s using what to work on those tasks, and also calculate their availability easier.

martinbean left a reply on Eagerloading Relationship, Maybe Polymorphic? • 1 week ago

@Thyrosis The “owner” relationship of a Thread would be the polymorphic relationship. Laravel determines what model to load through a combination of “type” and “id” columns. The type (by default) just stores the fully-qualified name of the model class.

Following the docs, your Thread model would have the following relation:

class Thread extends Model
{
    public function owner()
    {
        return $this->morphTo();
    }
}

Your threads table migration would then include:

$table->morphs('owner');

Which will create two columns: owner_type and owner_id.

Now, in your User and Character models, you’ll need to add the following relation:

class Character extends Model
{
    public function threads()
    {
        return $this->morphMany(Thread::class, 'owner');
    }
}

It might be worth wrapping that method up into a trait that can be added to the two models:

trait OwnsThreads
{
    public function threads()
    {
        return $this->morphMany(Thread::class, 'owner');
    }
}
class Character extends Model
{
    use OwnsThreads;
}

Now, when you query threads, you can eager-load the owner relationship, which will then be either a User or Character instance:

$threads = Thread::with('owner')->paginate();

foreach ($threads as $thread) {
    // $thread->owner will be either a User or Character
}

Hope this helps!

martinbean left a reply on So Very, Very Lost In A Polymorphic Relationship • 1 week ago

@jgravois Could you not have separate relationships for users, equipment, and tooling, rather than a polymorphic relationship?

I assume you’re modelling tasks of some description, each of which require a user/equipment/tooling combination to complete. Again, I assume equipment can’t be operated without a user, so it doesn’t make sense to shoe-horn them into a single relationship.

martinbean left a reply on Pagination Error • 1 week ago

@ramiawadallah Please put a bit more effort in to your questions.

Where are you getting this error? A class? A view? You need to give us more to go on to be able to help you.

martinbean left a reply on Dynamic Routes And Route Names? • 1 week ago

@psyopus I’d make locale a route parameter:

Route::get('/{locale}/home', 'HomeController')->name('home');

You’ll probably need to create a new helper function that automatically sets this parameter:

function locale_route($name, $parameters = [], $absolute = true)
{
    $parameters['locale'] = request()->cookie('locale');

    return route($name, $parameters, $absolute);
}

So in your controllers/views, you’ll need to use that instead:

<a href="{{ locale_route('home') }}">{{ trans('messages.home') }}</a>

martinbean left a reply on Database Seed With User Input • 1 week ago

@chitta I’d create a new console command (say user:create that takes user input, and then creates that user. Seeding is meant to be ran programmatically to quickly create data in database tables.

martinbean left a reply on Change Default Database In Middleware • 1 week ago

@koeeckho You should be setting database connection settings in your .env file. This should differ from environment to environment, rather than using code to detect when to connect to a “dev” database.

martinbean left a reply on How Do You Maintain Your Web App? • 1 week ago

Premature optimisation is the root of all evil.

13th September, 2017

martinbean left a reply on Reuse Form Elements In Create And Update Blade • 1 week ago

If you’re going down that route, then I’d maybe pass an “empty” model to your create view. Means you won’t have to do those ugly isset($post->title)-like checks in your views.

class PostController extends Controller
{
    public function create()
    {
        return view('post.create', [
            'post' => new Post,
        ]);
    }
}

martinbean left a reply on Undefined Variable: Category (View: E:\Laravel\project2\resources\views\pages\category.blade.php) • 1 week ago

@RahulG $data['category'] is not the same thing as $category.

martinbean left a reply on Undefined Variable: Category (View: E:\Laravel\project2\resources\views\pages\category.blade.php) • 1 week ago

@RahulG Error messages are meant to help you. The message tells you what the problem is: you tried to use a variable called $category but it doesn’t exist.

martinbean left a reply on Reuse Form Elements In Create And Update Blade • 1 week ago

I still use the Laravel Collective forms package, primarily for it’s form–model binding so I don’t have to pollute my Blade views with things like multiple @sections to populate form fields.

I’ll have a “form” template for whatever entity I’m editing, and then include that in both my create and edit views:

<!-- resources/views/admin/forms/product.blade.php -->
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
    {{ Form::label('name') }}
    <div class="form-controls">
        {{ Form::text('name', null, ['class' => 'form-control', 'required', 'autofocus']) }}
    </div>
</div>

<!-- And other fields -->
<!-- resources/views/admin/products/create.blade.php -->
@extends('admin.layout')

@section('content')
<h1>Add Product</h1>
{{ Form::open(['route' => 'admin.product.store']) }}
    @include('admin.forms.product')
{{ Form::close() }}
@endsection
<!-- resources/views/admin/products/edit.blade.php -->
@extends('admin.layout')

@section('content')
<h1>Edit Product</h1>
{{ Form::model($product, ['route' => ['admin.product.update', $product], 'method' => 'PUT']) }}
    @include('admin.forms.product')
{{ Form::close() }}
@endsection

12th September, 2017

martinbean left a reply on Order Status Tracking • 1 week ago

@memar Well an order would have a status and as @Dario says, you’d then have a has many relation for each item that makes up that order. So if a customer orders Product A and Product B, then you would have one orders record with an ID, and two order_items records with a foreign key pointing to the order they belong to.

The status (new, shipped, cancelled etc) would be a field on the orders table. You might want to have another order_history table that records when an order’s status changes though, so you can look back and see the date an order was placed, accepted, shipped etc.

martinbean left a reply on Order Status Tracking • 1 week ago

@memar I’m not sure what you’re asking. You mention order statuses, but then talk about line items.

martinbean left a reply on How Can I Build Modular Architecture In Laravel ? • 1 week ago

@ONDERSAHIN Organise your code into packages: https://laravel.com/docs/master/packages

Packages can include everything a “normal” Laravel application can contain, including controllers and routes.

martinbean left a reply on Web Hosting For Laravel • 1 week ago

@sheeping You’re not going to get anything decent for free. Any free hosting is going to have limits.

martinbean left a reply on Which Method To Use For Registration In Steps? • 1 week ago

@el3 You need to come up with the requirements really, before you can then move forward with a solution.

For example, what happens if someone closes their browser after step 1? Is step 3 actually required? Once you have the answers to these, that’ll tell you the approach to take whether you’re just storing the answer to each “step” in the session, or actually persisting values to the database.

martinbean left a reply on Web Hosting For Laravel • 1 week ago

I tried 000webhost but it has limited mb for project.

@sheeping A free web host has limits? Quelle surprise!

Of course a free web host is going to limit how may megabytes you can store (and problem transfer too). No one’s just going to give servers away.

Edit Your Profile
Update

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