MarkRedeman

MarkRedeman

Member Since 4 Years Ago

Groningen, The Netherlands

Student Applied Mathematics at Groningen, The Netherlands

Experience Points 46,575
Experience Level 10

3,425 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 244
Lessons
Completed
Best Reply Awards 34
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

05 Oct
3 years ago

MarkRedeman left a reply on Invalid Argument Supplied For Foreach()

@anikkhan can you do a die dump (dd($errors->all);) of your $errors variable. I expect that something is going wrong there since that's the only place in your view wit a foreach.

If that's not the problem: can you elaborate on when and where you get the error?

MarkRedeman left a reply on Jobs, Events & Listeners

There are multiple advantages and disadvantages of using jobs / commands. One of the advantages is that you can easily reuse a command for example @mehany mentioned that you can use the same RegsiterUser job to register a user both on your registration page and on your administration page. There are two other nice advantages of using jobs / command (I'm going to call them commands from now on). When using commands you often use a CommandBus to dispatch, or handle, the command. Laravel is shipped with a default implementation of the bus, another implementation is Tactician (If you want to read more about the command bus then you should read their documentation, it's pretty good :) ). Using the command bus has the advantage that you can use middlewares that are executed before your command is handled. For example I could have a logging middleware that logs the name of each command and the name of the user that is currently logged in whenever a command is handled by the command bus. Another middleware example is a transaction middleware which would look something like this:

<?php

use Illuminate\Database\DatabaseManager;

class UseDatabaseTransactions {

    /**
     * DatabaseManager
     */
    private $db;

    /**
     * Use the
     */
    public function __construct(DatabaseManager $db)
    {
        $this->db = $db;
    }

    /**
     * Wrap the execution of a command inside of a database transaction
     *
     * @param  $command
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($command, $next)
    {
        return $this->db->transaction(function() use ($command, $next)
        {
            return $next($command);
        });
    }

}

By using this middleware whenever a command has made changes to the database, but throws an exception later on, then the state of the database will be reverted.

Middleware can be a really nice tool to have and will act on all commands.

Another nice advantage is that Laravel has the ShouldQueue interface. By adding this interface to your command it will be automatically put on the queue. This is great if your have a command whose only responsibility is notifying some service. As an example: at a current project I have a NotifyWebmaster($companyId, $email) command that adds a webmaster account to our Intercom app. This command is placed on the queue so that the user does not have to wait for a response of the intercom api.

In one project we only used commands inside of our controllers which made our controllers very thin and easily understandable. But it came with the disadvantage that in order to add a new feature you had to write some additional boilerplate code that would not have been necessary without the commands. In the end I personally belief this was worth it since it added much more consistency to our codebase.

Ross Tuck has a really nice presentation about this concept called Models & Service Layers; Hemoglobin & Hobgoblins , you should probably go and watch it. :)


I haven't gone into whether a command should return something, which is a topic of its own. If you're interested in this topic you should look up CQS (Command Query Seperation) and CQRS (Command Query Responsibility Segregation)

04 Oct
3 years ago

MarkRedeman left a reply on Jobs, Events & Listeners

An event is something that has happened. For example you could have a UserRegistered event or a UserSubscirbedToPlan event.

A job is something that you want to happen (in other communities instead of jobs we often talk about commands). Most of the time a job / command produces events. For example you could have a RegisterUser job, or a SubscribeUserToPlan job. When these jobs don't fail then they produce UserRegistered and UserSubscirbedToPlan events, which, for example, you can listen to in your event listeners such that you can make sure that the user receives an email.

Events and jobs can be a great tool to communicate the intent of your application. Often when you only look at the events that are produced by your application you can already have a good idea about the goal of your app. As to when you should use a job and / or a event: I often dispatch a new event whenever something special happens and when as a result some other process should start. So when a user has registered, then:

  1. The user should get a welcome email
  2. A new account should be opened on our billing service (Stripe for example)
  3. Send our support team an email notifying them about the new customer

I use a job when I want to clearly show my intent of some action or when I have some kind of action that I want to be available both on our webpage and on a cli tool. However this mostly depends on the type of application you are working on and on what workflow you and your team prefers.

18 Sep
3 years ago

MarkRedeman left a reply on Running PHPUnit With Homestead Is Really Slow

I haven't seen that error message before. I always use the database that has been configured on my virtual machine. Perhaps you can seed the database on your vm and then run the tests on your local machine after you've finished seeding.

Personally I tend to run my unit tests using my local machine. Since these tests don't require any infrastructure these tests should easily pass when running them on a machine that only has php installed (so no database etc). Since you probably are already using composer to create a new Laravel application you'll have php installed so that shouldn't be a problem.

When using integration tests I either configure my application to use the database (and any other services required by the app) on my homestead machine (by setting DB_HOST for example) or if that's to much trouble I just run the tests on the vm (but only after all my unit tests have passed).


@ohffs @bugsysha I will try to do some analysis this weekend on why homestead seems to be so slow. I expect that my homestead is slow because my laptop has too little ram.

MarkRedeman left a reply on Running PHPUnit With Homestead Is Really Slow

@bencarter78 I think you misunderstand what I was trying to say, what happens when you run the tests outside of your vm?

In my case I have the following results:

cd ~/Projects/MyApp

vendor/bin/phpunit # takes 2.6 seconds
homestead ssh
cd MyApp
vendor/bin/phpunit # takes 16 seconds

MarkRedeman left a reply on Running PHPUnit With Homestead Is Really Slow

@bencarter78 I have the same issue. Running tests from my local machine takes 2.7 seconds while running the tests while being sshd to homestead takes 16 seconds. Both times the same database is used (a mysql database stored in homestead).

In order to run the tests from your local machine while using the database that's available on homestead you should change the DB_HOST value to point to your homestead's ipadress. (In my case my .env includes DB_HOST=192.168.10.10)

16 Sep
3 years ago

MarkRedeman left a reply on DomCode 2015

I bought my ticket yesterday. :D

13 Sep
3 years ago

MarkRedeman left a reply on Package Dependency And Namespacing

@jrean you can also create a new intreface YourUserPackageInterface and tell your users to implement the interface on their User model.

Another option is to typehint the AuthenticatableContract or CanResetPasswordContract interfaces since many User models will use those interfaces. This has the advantage that you are only relying on the Illuminate\Contracts\Auth namespace. You can also add an option to your configuration file where you let the user specify the FQCN of their User model. This is how Laravel's AuthManager creates an EloquentUserProvidre.

I don't think guessing the namespace and then assuming that the model is $namespace + "\User" is a good option since some projects might have renamed their User model to (for example) Account.

27 Aug
3 years ago

MarkRedeman left a reply on Whats's The Proper Way To Loop Through An Array For An Api In Laravel 5.1

Hi @raygun,

There are a couple of different ways how you can do this. I will first show some examples where we're only using normal PHP behavior.

First you could create an $resulst array and then pass all of the posts into that,

$results = [];

foreach (Post::all() as $post)
{
    $results[] = [
        'id' => $post->id,
        'marketname' => $post->subtitle,
    ];
}

return ['results' => $results];

Note that since the foreach is a oneliner the curly braces are not needed, however most php developers keep the curly braces for readability.

You could also use array_map making the whle expression a oneliner:

return ['results' => array_map(function($post) {
    return [
        'id' => $post['id'],
        'marketname' => $post['subtitle'],
    ];
}, (array) Post::all())];

Note that I first converted the Eloquent collection to an array. Instead of doing (array) Post::all() you could also do Post::all()->toArray(). The array_map example can be pretified if we use some features from Laravel,

return ['results' => Post::all()->map(function(Post $post) {
    return [
        'id' => $post->id,
        'marketname' => $post->subtitle,
    ];
})];

Here we used the map method of the Illuminate\Support\Collection object, here you can find some of its documentation.

One warning: it might be slow to return all posts in your database (it of course depends on the size of your project) I would recommend to use pagination when you have more than 25 posts in your table (both for speed and user experience). See the documentation about pagination for more info.

26 Aug
3 years ago

MarkRedeman left a reply on Code Decoupling And The Reasons Why It Is Needed?

Another thing is that if you are working on a team and you write decoupled code it is much easier to read each other's code since you don't have to understand the whole "big picture" of your app in order to understand how a small part of your app (not written by you) works.

If your code is highly coupled then you will have to look in lots of different files in order to understand how something works.

25 Jul
3 years ago

MarkRedeman left a reply on EloquentUserRepository Must Be Compatible With UserContract::create

Do you still get the same error? Can you show your complete EloquentUserRepository and UserRepository?

MarkRedeman left a reply on EloquentUserRepository Must Be Compatible With UserContract::create

Just a quick tip: you can post readable code on this forum if you use three backticks, like so:

\`\`\`
class SomeClass {}
\`\`\`

The code that you've shown looks ok. So I'm not sure what's going wrong now. Can you elaborate?

MarkRedeman left a reply on Doing Something When A User Logs In

There is nothing wrong with modifying the postLogin() method or with not using the AuthController at all, if for example the authentication process in your application is really different to the authentication process of an ordinary application.

If you don't wish to modify the postLogin() method, then one thing you could do is create an event listener. This event is fired internally by Laravel and sends a $user object and a $remember boolean.

Here is a quick example:

class LoginListener {
    /**
     * Handle the login event
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  bool  $remember
     * @return void
     */
    public function handle(User $user, $remember) {
        // Do stuff
    }
}

MarkRedeman left a reply on EloquentUserRepository Must Be Compatible With UserContract::create

Your EloquentUserRepository probably implements the UserContract interface, what this means is that each of the public funcitons inside of this UserContract interface must be present with the exact same parameters in your EloquentUserRepository.

In this case your code will probably look something like this:

<?php

namespace App\Repositories\Backend\User;

interface UserContract {
    public function create($input);
}

class EloquentUserRepository implements UserContract {
    public function create()
    {
        // do stuff
    }
}

But as you can see, the interface expects an $input parameter whereas your EloquentUserRepository does not. This means that your EloquentUserRepository is not implementing your interface and is therefore not compatible with the interface.

MarkRedeman left a reply on Where Is The Laravel Framework 5.2.dev Tagged Version?

You can use, "laravel/framework": "dev-master", which will require the master branch.

MarkRedeman left a reply on Mongo Db Issue With Illuminate Html Provider Class

Your composer.json contains some errors. There should be only 1 require statement, you have three. Also you did not specify a version for jenssegers/mongodb. Try this composer.json and do a composer update.

{ 
    "name": "laravel/laravel", 
    "description": "The Laravel Framework.", 
    "keywords": ["framework", "laravel"], 
    "license": "MIT", "type": "project", 
    "require": { 
        "php": ">=5.5.9",
        "laravel/framework": "5.1.",
        "laravelcollective/html": "5.1.",
        "jenssegers/mongodb": "~2.1"
    }, 
    "require-dev": { 
        "fzaninotto/faker": "~1.4", 
        "mockery/mockery": "0.9.", 
        "phpunit/phpunit": "~4.0",
         "phpspec/phpspec": "~2.1" 
     },
      "autoload": { 
        "classmap": [ "database" ], 
        "psr-4": { "App\\": "app/" } 
    },
    "autoload-dev": { 
        "classmap": [ "tests/TestCase.php" ] 
    }, 
    "scripts": { 
        "post-install-cmd": [ 
            "php artisan clear-compiled", 
            "php artisan optimize" 
        ],
        "pre-update-cmd": [ 
            "php artisan clear-compiled" 
        ],
        "post-update-cmd": [ 
            "php artisan optimize" 
        ],
        "post-root-package-install": [ 
            "php -r "copy('.env.example', '.env');"" 
        ], 
        "post-create-project-cmd": [ 
            "php artisan key:generate" 
        ] 
    }, 
    "config": { "preferred-install": "dist" }, 
}

MarkRedeman left a reply on Best Javascript Learning Resources

Yes codeception will work, though the tests that test your javascript need to be acceptance tests since the functional tests won't execute javascript.

Phantomjs will also work.

MarkRedeman left a reply on Mongo Db Issue With Illuminate Html Provider Class

Did you do a composer dumpautoload? If that didn't work, can you show us your composer.json?

MarkRedeman left a reply on Mongo Db Issue With Illuminate Html Provider Class

No problem, there probably are tons of articles that mention the HTML and FORM facades. You can find supported version of those services at the Laravel Collective.

MarkRedeman left a reply on Mongo Db Issue With Illuminate Html Provider Class

What version of Laravel are you using? The HTMLServiceProvider isn't available in Laravel 5.0 and higher, see the upgrade guide.

MarkRedeman left a reply on Best Javascript Learning Resources

Since you'll basically be validating your html pages it doesn't really matter what tool you use for end to end testing. For example you could use Behat with Selenium. You can also use Ruby, Python or whatever, as long as you're comfortable with the language and / or testing library.

24 Jul
3 years ago

MarkRedeman left a reply on Understanding Method Injection

In general yes. More importantly I think using repositories in combination with Eloquent is not useful. There was a discussion on repositories a while back which you might find interesting.

I was asking about how you're instantiating your repositories because I suspect that you do not yet fully understand why people use dependency injection and how it works. With dependency injection you can automatically instantiate classes and inject the dependencies of its constructor, for example:

<?php
class DependencyB {};
class DependencyC {};

class SomeClassWithDependencies {
    public function __construct(DependencyB $b, DependencyC $c)
    {
        // do stuff with $b and $c
    }
}

// plain old php:
$a = new SomeClassWithDependencies(new DependencyB, new DependencyC);

// Using Laravel's Service Container to automatically inject dependencies
$a = App::make('SomeClassWithDependencies');

So instead of being explicit on what to inject we can use Laravel's service container to automatically inject them. However it is important to note that you can't just do $a = new SomeClassWithDependencies since php does not know how to inject the dependencies.

MarkRedeman left a reply on Understanding Method Injection

Why are you extending an eloquent model in your EloquentFriendRepository? Also how do you instantiate your repository?

MarkRedeman left a reply on Best Javascript Learning Resources

@AlnourAltegani I've used Mocha as a testing framework and Should.js as a assertion library to test some simple javascript projects.

Here is an example repo that you might find useful.

MarkRedeman left a reply on API Folders

@stueynet you can use,

Route::group(['prefix' => 'api/v1', 'namespace' => 'API\V1'], function()
{
    
});

See the documentation.

23 Jul
3 years ago

MarkRedeman left a reply on Testing Class Dependending On Illuminate\Http\Request State

Are you familiar with mocking? You can use Mockery to mock the Request class such that you can test you class with different request states.

13 Jul
3 years ago

MarkRedeman left a reply on Using Auth In Service Provider To Get User Object

You can use Auth::user() and Request::user() in a view, however for those who are not fans of facades sharing or using a view composer might be a better solution.

Personally I tend to use a view composer that is called whenever I extend my master.blade.php template. This is a bit more flexible than using view()->share() since you might have some templates that do nothing with user data.


@reny410 I'm currently working on a blog post explaining Laravel's life cycle. It isn't finished yet, but if you want you can check it out here. I will try to finish before next week.

10 Jul
3 years ago

MarkRedeman left a reply on I Have A Phpunit Testing Error,please Anybody Tell Me Why This Occurred?

@Ishatanjeeb it could be that it's a bug because you're using the development version of Laravel, though I'm note sure. Did you try updating your composer dependencies?

I asked about a nondefault mail driver (Laravel supports smtp, mail, sendmail and some others) because the error message indicates that something is wrong with the Mailer class (it should have a setLogger method but phpunit says it's undefined). If doing a composer update doesn't work, can you show us the file vendor\lar avel\framework\src\Illuminate\Mail\Mailer.php? It should have a setLogger method.

MarkRedeman left a reply on Difficulties Undestanding The Handle Method Of The EncryptCookies Middleware

Here is the same middleware, but more verbose:

public function handle($encryptedRequest, Closure $next)
{
    $decryptedRequest = $this->decrypt($encryptedRequest);
    $response = $next($decryptedRequest);
    $encryptedResponse = $this->enrypt($response);
    return $encryptedResponse;
}

MarkRedeman left a reply on Using Auth In Service Provider To Get User Object

It is because, like @jakeharris , when the boot method of a service provider is being called, the user is not yet authenticated. The view composer that @jakeharris mentioned is executed before a view is rendered (or a specific view if you wouldn't use a wildcard).

If anyone wants I can write an explanation about how and when a service provider's register and boot methods are called.

Also a tip for anyone using view composers if you use a wildcard, view()->composer('*', $closure); then that means that the closure is called whenever a view is rendered, this means that when you have a blade template that includes 3 other blade templates then the closure will be called 4 times (once for the "master" blade template and once times for each of the three sections included in the master template). This could mean that (if you have quite a lot of sections and the closure isn't very efficient) your app can get quite a lot slower.

MarkRedeman left a reply on I Have A Phpunit Testing Error,please Anybody Tell Me Why This Occurred?

  • What version of Laravel are you using?
  • Are you using a nondefault mail driver?
  • Could there be anything else that you can think of that caused the error? Did you (maybe) change the Illuminate\Mail\Mailer class?

Also there is a type in your code in the AppMailer at the sendEmailConfirmationTo method there is $this->t0 = $user->email which should be $this->to = $user->email (0 vs o).

MarkRedeman left a reply on Cartesian Product In Laravel

@Sonu can you elaborate on how your input looks like and what you want your output to look like?

Here is the most trivial cartesian product of two sets:

<?php

/**
 * Maps two arrays into their cartesian product,
 * cartesianProduct : A x B -> { ($a, $b), $a in A, $b in B }
 * @param array $first A
 * @param array $second B 
 */
function cartesianProduct($first, $second)
{
    $product = [];

    foreach ($first as $a) {
        foreach ($second as $b) {
            $product[] = [$a, $b];
        }
    }
}

If you want to be able to make cartesian products of an arbitrary amount of sets then the same can be implemented using recursion.

If you need more performance you could also use [SplFixedArray]s since the size of a cartesian product is known before the product is made.

MarkRedeman left a reply on I Have A Phpunit Testing Error,please Anybody Tell Me Why This Occurred?

@Ishatanjeeb can you show both your test and the code under test?

MarkRedeman left a reply on My Phpunit Tests Returns Risky_tests

@sandeepseshadri can you show the code that you're testing? (and if you do not use the default phpunit.xml file also that file)

Here is the documentation about risky tests.

Basically a test is seen as risky when:

  • A test does not test anything, so for example if there are no assertions in your tests (useless test)
  • A test that indicates that it uses some part of your code also uses a different part of your code (Unintentionally Covered Code)
  • Either your test or the code that you're testing has a print statement, or any other statement that has an output (Output During Test Execution)
  • A test takes to long to execute (more than 1 second by default) (Test Execution Timeout)
  • Your code uses globals (Global State Manipulation)

I think it's most likely that your test either takes to long to run or that it has an output somewhere.

04 Jul
3 years ago

MarkRedeman left a reply on How To Create A Custom Facade - It's Hard To Find The Right Info

@fsdolphin before you learn how to use and create facades, it's a good idea to understand how autoloading in combination with psr4 works.

So your composer.json file contains,

"psr-4": {
    "App\\": "app/",
    "Acme\\": "app/Acme"
}

If you do a composer dumpautoload then this tells composer that any time it needs to find a class named App\Something\MyClass then it will include the file located at app/Something/MyClass.php and if your app needs a class named Acme\Facades\Search it will include the file located at app/Acme/Facades/Search.php.

The files you showed in your previous post are in the Acme namespace, however if we take the SearchServiceProvider as an example then you said that it is located at app/Search/SearchServiceProvider.php, while its FQN (Fully Qualified Name) is Acme\Search\SearchServiceProvider, hence Laravel (composer) will try to find the file at app/Acme/Search/SearchServiceProvider.

This is why you get the error, Class 'Acme\Search\SearchServiceProvider' not found.

MarkRedeman left a reply on Packages Support

@Codenator81 you might want to take a look at Cartalyst. They provide framework agnostic packages on a subscription basis, where I think most packages are easily integrated into Laravel.

03 Jul
3 years ago

MarkRedeman left a reply on Setting Up The Job Pipeline In The Dispatcher In L5.1

@rikh you can create a new service provider that configures the dispatcher, here is an example I've used:

namespace App\Providers;

class BusServiceProvider extends ServiceProvider {

    /**
     * Bootstrap any application services.
     *
     * @param  \Illuminate\Bus\Dispatcher  $dispatcher
     * @return void
     */
    public function boot(Dispatcher $dispatcher)
    {
        $dispatcher->pipeThrough([
            UseDatabaseTransactions::class,
            Log::class,
            AuthorizeIfAvailable::class,
            SanitizeIfAvailable::class,
            ValidateIfAvailable::class,
        ]);

        $dispatcher->mapUsing(function($command)
        {
            $command = get_class($command);

            return str_replace('Command', 'Handler', $command) . '@handle';
        });
    }
}
02 Jul
3 years ago

MarkRedeman left a reply on Are Repositories Really The Way?

As more have said I don't think switching an implementation is an advantage of using repositories. For me the benefit of using a repository is that, if implemented correctly, its only responsibility is persistence and as @thepsion5 has shown, when you first design an interface for your repositories, then it is easy to decorate them.

However using repositories in combination with eloquent objects can be quite annoying, since you're basically passing all method calls to your eloquent objects. As a consequence both your repositories and your eloquent classes are responsible for persistence. Ideally each class should have its own responsibility, making it easier for you to choose which object you need to use.

I think Shawn McCool's article on repositories gives a good explanation on how an ideal repository should work.

MarkRedeman left a reply on Event Sourcing Library, Looking For A Contributor To Set Up A Lumen Example

@RayRutjes Yeah the concept of event sourcing is incredibly simple and intuitive (in my opinion) so it would be nice to have a couple of different (and complete) implementations of the architecture needed to do event sourcing efficiently.

I will try to make some time in the coming weeks to check your framework.

Also have you seen the Governor Framework? Just wanted to drop the link in case no one's seen it before.

MarkRedeman left a reply on Event Sourcing Library, Looking For A Contributor To Set Up A Lumen Example

Could you briefly explain the differences between your package and Broadway?

I think event sourcing is an awesome technique, so I wouldn't mind making a lumen example project.

29 Jun
3 years ago

MarkRedeman left a reply on Developing Your Packages In Laravel 5

@tomicakorac you can use $this->app->register('Acme\ServiceProvider'); to register a different service provider from your own service provider.

22 Jun
3 years ago

MarkRedeman left a reply on Where I Wrong ? Npm Install - Error

@ValsiS Try running it as sudo:

sudo npm install --global gulp

MarkRedeman left a reply on Seeding Polymorphic Pivot Tables

@Ruffles you could do something like this:

private function randomInsert() 
{
    $this->polyTables = [
        Table2::class => Table2::lists('id'),
        Table3::class => Table3::lists('id'),
        Table4::class => Table4::lists('id'),
    ];

    $type = array_rand($this->polyTables);
    $id = $this->faker->randomElement($this->polyTables[$type]);
    return [
        'tableable_id' => $id,
        'tableable_type' => $type
    ]
}

Basically you can first choose the class that you want to insert and then choose the corresponding id. This means that the polymorphic relationships are uniformly distributed.

20 Jun
3 years ago

MarkRedeman left a reply on Why Is This Happening

@csuarez can you tell us what you're running the application on? Are you using a vm (Homestead?), Mamp, Wamp or anything else?

What happens when you run the application by only using php artisan serve?

MarkRedeman left a reply on Use PasswordBroker On Controller

@AlexMunoz you'll have to do something like this:

App::call([$this, 'sendPasswordResetEmail'], $email);

This way Laravel will try to determine the parameters needed for sendPasswordResetEmail and inject the dependencies (while still using the default $email parameter).

However I advice you to just use $this->sendPasswordResetEmail($email, $this->password); since it's much easier to understand (you don't have to know anything about App::call() when reading the statement).

Generally method injection is a nice trick if you have some a class that calls methods of other classes without knowing their interface beforehand. For example calling the handle method of self handling commands / jobs. Since in this case you know that you will need a PasswordBroker it is much easier to just use constructor injection.

MarkRedeman left a reply on Use PasswordBroker On Controller

@AlexMunoz how and where do you call the sendPasswordResetEmail? You will have to provide the method with an PasswordBroker instance as Laravel or php won't magically inject the necessary dependencies (Laravel will inject the dependencies of your constructors and some methods, but only when you use the Service Container to either make the instance (constructor injection) or call the method (method injection)) .

19 Jun
3 years ago

MarkRedeman left a reply on Laravel Testig Request Setting Header

@Jaoued it took me some time to figure out, but you will need do prefix HTTP_ before your header key. This is because when a Request object is constructed the contents of $server are inserted in a ServerBag object, which has a getHeaders() method that will return all headers based on some criteria, one of which is that all keys which are prefixed with HTTP_ are returned as headers, as you can see here.

I will change my previous post to reflect that you need to prefix the headers with HTTP_.


@tzookb I'm not sure if you're still have a question or if you've solved the problem, can you elaborate?

MarkRedeman left a reply on Laravel Testig Request Setting Header

@tzookb if you're asking how to set the header when you do a post request in your test, then you can do the following (assuming you're using Laravel 5.1):

$this->post('blogs', ['title' => 'awesome blog post'], ['Authorization' => 'Bearer' . $token]);

So in the third argument you can pass your headers. The same goes for the put, patch and delete methods. The get method takes the headers as a second argument as there is no post data.

If you're not using Laravel 5.1 then you can use the call method which takes the header data as the 6th argument, below you can see the public interface of the method.

/**
 * Call the given URI and return the Response.
 *
 * @param  string  $method
 * @param  string  $uri
 * @param  array   $parameters
 * @param  array   $cookies
 * @param  array   $files
 * @param  array   $server
 * @param  string  $content
 * @return \Illuminate\Http\Response
 */
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
18 Jun
3 years ago

MarkRedeman left a reply on Laravel 5.1 - Get Injected Controller Middleware

@roccobenditz You would need to have an instance of your controller in order to get the associated middleware. The route:list command does this by creating an instance of the controller and getting its middleware, you can see that here.

I still don't understand why you would like to get the middleware that fired your event. Furthermore in my opinion it would be more appropriate to throw an exception instead of firing an event, since not having enough permission can be quite exceptional.

Anyway: in order to get the middleware that have been setup by your controller you would need to create an instance of said controller. You could do something like this (based on the code used by the list routes command):


$actionName = $route->getActionName();

if (!empty($actionName) && $actionName !== 'Closure') {
     $segments = explode('@', $actionName);

     $controller = App::make($segments[0]);
     $middleware = $controller->getMiddleware();
}