tag

tag

Member Since 5 Years Ago

Experience Points 52,520
Experience Level 11

2,480 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 255
Lessons
Completed
Best Reply Awards 23
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.

11 Nov
7 months ago

tag left a reply on Array Flatten

I just want to throw this out there, as the accepted answer takes the long way to get to what PHP basically gives you for free:

<?php

$data = [
    ['3101625668' => 98.0],
    ['3913126364' => 35.77],
    ['3913058204' => 25.33],
    ['3101372540' => 33.47],
    ['3913752741' => 40.0],
    ['3913120054' => 20.4],
    ['3913998755' => 26.8],
    ['3913861492' => 25.2]
];

$flattened = array_replace(...$data);

var_dump($flattened);

So what's going on here?

The documentation for array_replace() describes its behavior better than I can. But the important thing is that it takes N number of arrays as arguments.

But the argument I give it is using the PHP splat operator

This is identical to doing it the manual/hard way:

$flattened = array_replace($data[0], $data[1], $data[2], $data[3], $data[4], etc...);

The splat operator just says "use each element of the parent $data array as an argument for array_replace().

Then array_replace() takes care of the rest.

20 Oct
7 months ago

tag left a reply on "Can" Middleware And Route Resources?

Its kind of long, but basically it's a standard policy created by php artisan make:policy PostPolicy --model="Post"

And the authorization logic is simple:

class PostPolicy
{
        use HandlesAuthorization;

        /**
        * Determine whether the user can view the post.
        *
        * @param  \App\User  $user
         * @param  \App\Post  $post
         * @return mixed
         */
        public function view(User $user, Post $post)
        {
             return $user->id === $post->user_id;
        }

Etc....

19 Oct
7 months ago

tag left a reply on "Can" Middleware And Route Resources?

Sorry, yes. This was just a quick example with a typo. The plural conventions/keys I'm using are all correct in my code. But it's not working.

So what you are saying is if I define both

Route::resource('posts', PostController::class); in routes/web.php

and

Gate::resource('posts', App\Policies\PostPolicy::class); in the boot() method of the AuthServiceProvider, then that is all I need to do?

tag started a new conversation "Can" Middleware And Route Resources?

I was reading through the documentation for Authorization using Gates and Policies, and while you can do things like this:

Route::put('/post/{post}', function (Post $post) {
        // The current user may update the post...
})->middleware('can:update,post');

You can't seem to do something like this:

Route::resource('post', PostController::class)->middleware('can');

I've tried this doing Gate::resource(...) and registering a policy, but I can't seem to make it automagically apply the gate/policy to the resource.

Does anyone know of a way to do this?

20 Jun
1 year ago

tag started a new conversation How Do You Push A Script Onto A Stack Only If It Doesn't Exist Yet?

I have created a blade partial that acts as a color picker. It uses a JS color picker library to function.

Rather than include that color picker library at the global site level, I would like to pull it in with the partial, and push it onto my vendor stack, only when I've included the color picker form partial.

However, a given form might have several color pickers, and I don't want to push that JS library onto the stack multiple times. Is there a way to give a script that's being pushed a unique identifier or something so that it will only ever be pushed once?

Example:

@push('scripts', 'my-unique-key')
    <script src="/example.js"></script>
@endpush
30 May
2 years ago

tag started a new conversation Have To Constantly Manually Run Php Artisan View:clear To Get Views To Update

I am developing in a VM, and I've found that whenever I change a blade file, it never updates on the next page refresh. I have to manually call php artisan view:clear to get it to do this (5.4).

I suspect it has something to do with my VM settings. Maybe someone has some insight?

config.vm.synced_folder ".", "/var/www",
  :nfs => true,
  :mount_options => ['
       noacl,
       nolock,
       vers=3,
       udp,
       noatime,
       nodiratime,
       rsize=32768,
       wsize=32768'
  ]
25 Apr
2 years ago

tag left a reply on Try To Send Html From Controller Laravel And Data Tables

You should just be able to return HTML. Here is a working example from one of my projects

return Datatables::of($orders)
        ->addColumn('action', function ($order) {
            return '<a href="'.route('orders.edit', $order->id).'" class="btn btn-xs btn-primary"><i class="glyphicon glyphicon-edit"></i> Edit</a>';
        })
        ->make(true);

tag left a reply on Recommendations For Cloud-based Laravel Hosting (preferably Auto-scaling)?

Laravel Forge. It was created and is run by Taylor Otwell, who created Laravel.

https://forge.laravel.com/

18 Oct
2 years ago

tag started a new conversation Model Factories Creating Many To Many Relationships With Reusability

Here's a simple example. I have a Product model, and products have many Download objects. For testing purposes, when I create a new product from my model factory, I always want it to create a few Download objects and attach them. I like the portability of simply specifying:

factory(\App\Product::class)->create()

In my tests, and I don't want to have to do this every time I want to create a product to test with:

factory(\App\Product::class, 10)->create()->each(function($product){
    $downloads = factory(\App\Download::class, 10)->create();   
    $product->downloads()->attach($downloads->pluck('id');
});

I don't want to see these either, I want to be able to create them on-the-fly with a simple API like the factory method.

Save for creating a new helper function which acts as a pass-through intermediary to the factory helper, I don't see a way to utilize the model factories for these many to many relationships.

23 Aug
2 years ago

tag started a new conversation What's New In 5.3 Does Not Appear In The Laravel Skill

https://laracasts.com/skills/laravel

It's also not on the home page. Took a minute to actually find it.

13 Jul
2 years ago

tag started a new conversation Logging Model Save Queries In Database

I have the need to create an audit trail for what a user does in my application. I'm not really that worried about the selects, but really only the inserts/updates. I've created a BaseModel which all of my models extend. I've also created a table with an id, user_id, and a text column for the query. I want to save the query that was executed during the save for each model. I know there is DB::enableQueryLog(); but I'm not sure that's exactly what I want, since I only want the query executed in the save. I'd love to not do this in my controllers where the save's occur, and instead do it in the base model, or listen to BaseModel::saving or BaseModel::save. Any ideas?

16 Jun
3 years ago

tag left a reply on Elixir + Vue[ify] -> Lots Of Single Files Take Too Much Space

Rant....

I'm having similar issues trying to get a rather complex app to build assets efficient and correctly (using Vue & Vuetable as well, no less), and all this does is remind me how much I HATE front-end development. I don't mind working with JavaScript or CSS, but the build tools used to build non-trivial apps with them is a complete wasteland, including Elixir.

Here's what I've started doing:

  1. I put vue.js, vue-resource.js, vuex.js, lodash, and any other libraries I use on most pages together in one location, and define mix.scripts(['vue.js', ... etc], 'public/js/common.js').

  2. In that directory, I also put a bootstrap.js file that does things like call Vue.use(VueResource) and Vue.use(Vuex).

  3. That all then gets concatenated and minified (I think, not sure if mix.scripts() minifies in production....)

  4. I then include that common.js file in my main layout, as a separate script from the actual application script(s) on different pages.

  5. Now Vue is in the global space and accessible by any other scripts I include afterwards. Call it sloppy or wrong if you want, but this is the only sane way I've found to work with JavaScript...

  6. From here, I build additional per-page or per-module scripts WITHOUT importing dependencies, since Vue and Vuex are part of the global space. I simply start a script with

'use strict'

new Vue({
    ....
});

or

// Get vue table
require('vuetable/src/vue_table.js');

// Create a vue configuration for its columns and things
new Vue({
     ....
});

That specific script then gets babelified or whatever and then I just include that after the common.js file as needed.

Of course, then PHPStorm complains that it doesn't know where Vue is coming from because you're not directly importing it in your script, but that's the only alternative I've found to creating a single massive app.js file that only 10% of the code might be used on any given page...

So to summarize:

  1. Put all common/core lib files along with some bootstrapping together in one location and mix them together into a single common file
  2. Include that common script in your master blade layout.
  3. Create lots of individual scripts for individual pages so that you're not transferring 5mb worth of script for a page that might only need 5kb worth of script,
  4. Include those individual scripts in the individual blade templates as needed.

That eliminates the duplication issue.

Browserify might have a dedupe option like Webpack does, but who the hell knows if Elixir exposes it or even has access to it, or what you need to do to Gulp to get it work with Elixir even if it does... (as I said, JS build process is a god damn wasteland compared to working with PHP).

05 Apr
3 years ago

tag left a reply on DDD - Working With Repositories

@sherwin, I see. In that case, your domain model as you had presented it is fine. Though it seems like you might still want to wrap the individual REST resource APIs in some kind of service layer class (be it a repository, or something else), and then inject those into your aggregate root's repository. That way if the API ever changes, you have a layer of insulation where you can fix your mapping and return the same consistent objects from that service class (I'm using the term "service" here generically btw). This will also let you introduce a caching layer at some point, should you need one.

But yes, you'll likely need to make all necessary HTTP requests through your aggregate root's findById method so that the repository can be a single source of truth for what constitutes a valid, complete Customer w/ applicable relations. That's really the whole point: avoiding inconsistently constructed objects and missing dependencies.

31 Mar
3 years ago

tag left a reply on DDD - Working With Repositories

orders order/[customer_id] - for fetching the details of the orders but does not include the products of a specified customer product/[order_id] - for fetching the products within an order

This is not conventional REST API design. You're exposing a weird relation in your schema. It's expected to use /order{/order_id}, not /order{/customer_id}.

If you want a list of orders by customer, through your customer aggregate root, you would do:

/customer/{id}/orders

If you wanted a specific order, you would do:

/order/{id}

If you wanted products for a specific order, you would do:

/order/{id}/products

If you wanted the customer details for a specific order, you would do:

/order/{id}/customer

If you wanted a list of orders for a given product:

/product/{id}/orders

30 Mar
3 years ago

tag left a reply on Validate() Method On Controller Doesn't Flash Old Input

@tykus_ikus

Pretty sure you can just use old('title'), don't need the full request object.

tag left a reply on IOC Container Error Message

You shouldn't be trying to inject the XeroServiceProvider into your controller. You simply define in it in app.php like you've already done, and that's it. It will automatically boot and register any dependencies it needs.

Instead, in your controller, you want to type hint the specific kinds of Xeros, like XeroPrivate and XeroPublic etc.

BUT, that Xero library is doing it all wrong (they should be binding to a full namespace...), so you may not be able to just inject them. You will likely have to either register their Facades in app.php as well, or call $xeroPrivate = app('XeroPrivate'); from a controller, which is not ideal.

tag left a reply on Vue.js For Toggling Tabs In Forms

"Ideal" is a strong word....

Yes, it can be used to fairly easily/elegantly build a dynamic form wizard like you've shown, arguably more easily than jQuery. But so can Angular, React, and Backbone.

tag started a new conversation "Skills" Does Not Really Make A Whole Lot Of Sense

Take for example JavaScript:

https://laracasts.com/skills/javascript

Below the videos, it says:

A SKILL IS A RECOMMENDED PATH THROUGH LARACASTS TO LEARN ONE SUBJECT.

And each video says Step 1, Step 2, Step 3 etc...

Except Vue 0.12, Vue 1.0, React, and Elixir is not a sequence, series of steps, or "path", it's just a grouping of related videos.

Perhaps "Skills" should be renamed "Topics" or "Subjects", and the steps/path reference should be removed?

tag left a reply on Admin And User In The Same Laravel App Is A Bad Idea ?

If someone who is an admin does not log out and a user gets information they were not meant to get that is the admins stupidity

Irrelevant. Say an admin has the power to delete a user. You can blame the admin for staying logged in all you want, but at the end of the day, if a malicious user gets access to an admin account, it's you (the site operator) that pays the consequences for it.

Also, I don't think you understand what I'm saying.

Here's a normal Laravel authentication system:

  1. A single user table
  2. A single session table
  3. A single point of login with a "remember me" function
  4. A user who happens to have admin privs logs in with "remember me" and gets compromised later, now the whole site is in jeopardy.

A better system is this:

  1. A single user table
  2. Two separate session tables
  3. Two different logins (one general site login, and another for an admin area login)
  4. A user who happens to have admin privs logs into the general area with "remember me" and gets compromised later, no big deal, because their regular user session is not tied to access to an admin area.
  5. When they log into the admin area, they have no "remember me" function, must enter their password AGAIN (even if they're already logged into the general access area), and a totally separate session is created that will expire after 5 minutes of inactivity. Even if their cookie gets stolen, it's very likely going to be stale.

So an admin can have TWO sessions at once: one less secure but more convenient, for general access, and one more secure but less convenient, for sensitive access.

Laravel should provide that out of the box.

29 Mar
3 years ago

tag left a reply on Admin And User In The Same Laravel App Is A Bad Idea ?

The posts here are missing the key issue with single session behavior shared between Users and Admins: cookie theft.

It's fine to offer normal users a "remember me" feature that lets them auto-login after an indefinite period of time. This is a security risk for users who choose to use it, but it's not a security risk for your site.

However, a user who is an admin should have a session which is 100% separate from their normal user session. They should literally have to re-login and get a totally separate cookie and a totally separate session, and you should not offer "remember me", because you want admin sessions to expire very quickly (like after 5 minutes of inactivity).

I have been wanting Laravel to implement this kind of multi-session capability for a LOOONG time, as it's a vital piece of application security that a framework should be able to provide a decent out of the box solution for.

tag left a reply on Flexbox Bug On Mac/iOS

I don't have that problem with Firefox on OSX, but I do with Safari. I think the problem is your text is just missing a flex setting:

.Module__text {
  flex: 1;
}

tag left a reply on DRY Repositories Interfaces

DRY is not something to be followed dogmatically. Just because two repositories might share a similar interface, doesn't mean you need to DRY up the implementation, or even the interface definition for them.

Consider the all() method. It's quite conceivable that you want to do eager loading in your repositories (and you do most definitely want to keep eager loading hidden in your repositories, don't do eager loading outside of repositories), and what you eager load will be different from one model to the next. Thus you'll end up overriding the all() method anyway, so there was not much point to defining a generic shared method in a parent.

There's probably nothing wrong with creating a base interface provided you think your repository method signatures will be mostly the same, but you're not gaining much by adding that layer of abstraction IMO.

Really, the best thing to do is to design from the perspective of your application layer. Rather than trying to build a repository layer with an unknown set of behaviors, just let your application layer tell you what it wants. Maybe a certain model needs an all() method, maybe it doesn't. Maybe a different model needs a findByXYZ() method. By letting your application use-cases determine what your repositories should expose, you end up creating more focused interfaces, and you'll find that you likely don't have all that much code to DRY up in the first place.

That's one of the key things to learn: it's tempting to write code you don't need yet by building your service layers (e.g. repositories) first, but you should build your application layer first, let your application layer (the client) decide what API it wants to have, then build exactly that API, and apply DRY only in the areas you need it.

22 Dec
3 years ago

tag started a new conversation 5.2 Upgrade Problem, Class Illuminate\Auth\Guard Does Not Exist

I'm using the Guard class directly in a custom member loader that allows for integration with a legacy codebase, and after the 5.2 upgrade, that class is no longer found. I see no mention of what it was changed to, or how it was changed, in the upgrade guide.

22 Nov
3 years ago

tag left a reply on Listen To *any* Save/update/create Event For *any* Model?

Figured it out:

Had to dive deep into the source code to dig this one up:

Event::listen(['eloquent.saved: *', 'eloquent.created: *'], function() {
        //
 });

tag left a reply on Listen To *any* Save/update/create Event For *any* Model?

@jsartisan, please re-read my post more carefully.

tag started a new conversation Listen To *any* Save/update/create Event For *any* Model?

I want to listen for any time a model changes, and I don't care what model it is. I don't want to have to set up a listener for every model, so I'd like to be able to just listen to a generic Model::saved(...) event.

Does such a thing exist?

30 Oct
3 years ago

tag started a new conversation It's Quite Ironic That A PHP Framework Provides The Best Possible Front-end Workflow Tool...

I've been trying to learn modern JS and front-end workflow and I am having a shit of a time doing it because there are dozens of ways of doing it.

Gulp vs grunt vs bower. Webpack vs browserify. Different people recommend different module patterns:

require(...); import X from Y define(...., function())

Some people have all their examples in CoffeeScript. Some have all their examples in TypeScript. Ask 50 different developers what their gulp files look like, and you'll get 50 different gulp files.

Not to mention dozens of frameworks with varying degrees of completeness and stability... it's utterly maddening. If front-end development is the surface of a stormy sea, PHP is like the stable, calm, simple ocean beneath.

But what I've found interesting in all of this, is that Elixir is the most sane and simple front-end tool I've used yet, and it's built for use in a PHP framework...

02 Sep
3 years ago

tag left a reply on What Is The Simplest Way To Integrate One-way Legacy Authentication?

Question probably wasn't clear, but I'll post my solution anyway just in case anyone else needs to do something.

Basically I have an existing authentication system through an old Invision Power Board, which has an ibf_members table that I built a Member Eloquent model for since I wanted to keep the User model in reserve for when I finally replace ibf_members with proper Laravel users.

I wanted the Laravel application to know you're authenticated through the invision power board forum. So I built my own "member loader" that looks at the legacy auth cookies and legacy session database table, and if it sees a session for that Member, it just returns that Member (it's basically how Laravel's user loader works).

But, that only returns the member - Laravel still didn't know that member is technically authenticated, which means that the policy system wouldn't work.

So what I did was pretty straight forward:

  1. Went into config/auth.php and changed 'model' to Member::class
  2. Added AuthenticatableContract and Authenticatable trait to the Member model
  3. In my MemberLoader, I just use Auth::login($member) to force authenticate the member that I've manually determined is authenticated.
  4. Now I can call Auth::user() to get that member, and the policy system now has access to it.

Pretty awesome.

30 Aug
3 years ago

tag started a new conversation What Is The Simplest Way To Integrate One-way Legacy Authentication?

I want to take advantage of the new policy system in 5.1.11, but it seems like Laravel's auth user is heavily baked into it.

I have a legacy system that I'm running in parallel with Laravel 5, and that system uses its own auth + sessions system. At present I'm not using any Laravel 5 auth, but I am wrapping the legacy member table with an Eloquent model. I've built my own simple auth loader based on queries from the legacy system tables.

All I want is for the presence of a legacy session or auth cookie, to set that legacy member model as being logged in.

What's the easiest way to achieve this?

24 Aug
3 years ago

tag left a reply on Laravel 5.2 (What Features Do We All Want?)

Would like to see some built-in query caching, like this:

https://gist.github.com/jlem/43f719d668bdf50e4043

I like building out my own APIs in my models, based on interfaces.

Just like you can do

$user->posts
$user->posts
$user->posts
$user->posts
$user->posts
$user->posts

And still only incur one query, I would like to be able to do the same for any arbitrary method - especially those that use the query builder to invoke new queries.

And I strongly want to emphasize that time-based caching is NOT an option here. I am looking for the same registry-based single request caching that "loaded" relations have.

23 Aug
3 years ago

tag started a new conversation Do You Guys Follow Pure TDD, Or Do You Plan Out Your Target API Head Of Time?

I started off a project a while back to practice TDD and I realized that I immediately hit a wall. I wasn't sure what I even wanted to test, and when I finally did, I ended up with what I thought was a pretty awkward (but easily testable) API.

I've started working on a new library and this time instead of starting off with tests, I've decided to start off "sketching" what I want the public API be, then using that as a guideline for tests, and then letting the tests guide the actual implementation of that API.

Anyone else do something similar, or do you just dive right in with TDD without a gameplan first? If so, how do you go about deciding upon your public API?

17 Aug
3 years ago

tag left a reply on How Do You Parameterize WhereRaw() In The Query Builder?

@bimalshah72

Yes, I figured out my problem, you made the same mistake I did:

You can't put the '%' in the where clause, they have to go around the parameter before binding, like this:

$searchString = '%batman%';
 ->whereRaw("(CONCAT(clans.name,' ',ibf_members.members_display_name) like ?)", [$searchString]);

Also, the second argument apparently must be an array.

tag started a new conversation How Do You Parameterize WhereRaw() In The Query Builder?

I have this query:

        $query = DB::table('clan_teams')
                    ->select('clans.name', 'ibf_members.members_display_name')
                    ->leftJoin('clans', 'clan_teams.clan_id', '=', 'clans.id')
                    ->leftJoin('ibf_members', 'clans.leader_id', '=', 'ibf_members.id')
                    ->whereRaw("(CONCAT(clans.name,' ',ibf_members.members_display_name) like '%:search%')")
                    ->get();
```php

The purpose of the CONCAT statement at the bottom is to create a simple multi-faceted searchable string, but I need to parameterize the actual search string I use so that it's safe from SQL injection. 

But I can't find any information on how to do this with the query builder. Do I have to do a completely raw query?
16 Aug
3 years ago

tag started a new conversation Setting Eloquent Relations To Protected

I am trying to properly hide away the Eloquent signature of a model such that I can give it a proper set of interfaces, and one step I've taken is to set the relations to protected.

However, that causes a problem whereby whereHas(....) no longer works.

Given this query from the Member model:

    public function getClan(SectionInterface $section)
    {
        return $this->clans()->whereHas('teams', function($q) use ($section) {
            $q->where('section_id', $section->getID());
        })->first();
    }

If the teams() relation method on the Clan model is set to protected, this query can't work (which is to be expected I suppose).

My question is, does anyone have a recommendation for allowing these kinds of relation builder queries without actually exposing the relations publicly?

06 Aug
3 years ago

tag left a reply on Make Internal API Requests From Laravel To Separate Lumen Instance?

REST is not an HTTP convention. It makes no assumptions about the transmission protocol. It's used heavily with HTTP, yes, but it is not HTTP.

The requirement is this: I want to build a REST API to my data layer, as an entirely separate service.

For now, I want to consume it internally (not through HTTP - but still through the REST schema) via a Laravel app, but later, I may want to expose it to the web for consumption by other apps, or move the Laravel client app to another server entirely.

tag started a new conversation Make Internal API Requests From Laravel To Separate Lumen Instance?

Here's what I want to do:

  1. I want to create a simple REST API powered by Lumen, in a non-web accessible directory

  2. I want a separate Laravel project (living on the same server) to be a client that consumes the API.

  3. I want to consume that API via a common REST interface e.g. (GET /league/4/players)

  4. I DON'T want to make actual HTTP requests, because I don't want the overhead, the API won't even be HTTP accessible, and I want Lumen to return Eloquent models instead of JSON so that it's far easier for me to pass those models through to blade for rendering.

  5. EVENTUALLY I might make the lumen API web accessible with authentication so that you can set Accept headers to request application/json, but for now I want it to be internal only, and return native PHP code to Laravel.

Is there a way to do something like this between a separate Lumen and Laravel project?

http://laravel-tricks.com/tricks/internal-requests

Essentially I would create a request object that mocks the URI and request method in Laravel, but invoke that via the Lumen codebase's route dispatcher. Is it as simple as that, or do I need to find a way to get Lumen to go through it's boot process?

22 Jul
3 years ago

tag started a new conversation Override Group Middleware On A Per-route Basis?

Say I have the following route setup:

Route::group([
    'middleware' => ['one', 'two']
    'prefix' => '/some/uri',
    'namespace' => '/Some/Namespace'
], function() {
    
    Route::get('/whatever', [
        'middleware' => 'three'
        'uses' => 'SomeController@action'
    ]);

        // .... more routes

});

What ends up happening for the route is it that it now has has `one`, `two`, and `three` middlewares - this is fine as there are a few situations where you do want your middlewares to merge, but other times you want the route middleware to override the group middleware rather than marge with it.

Is there a way to tell Laravel to do this?
18 Jun
4 years ago

tag left a reply on The Future Of The Command Bus

I know that functionally they are the same, but the semantic name difference is crucially important. Clean, understandable architecture starts with semantically clear names, and "Jobs" implies a different purpose than "Commands".

tag left a reply on The Future Of The Command Bus

Dont mind, use Jobs directory as you used commands one, with same syntax for your classes.

The term "Jobs" has a completely different connotation than "Commands" did. The concept of a job is as different from the concept of a "command" as a model is from a controller. The name strongly implies that the command bus is no longer an architectural element of Laravel, and it is not intended to be used the way it once was.

I mean, technically I could do this, too.......

class UserRepository extends Model 
{
    public function index() {
        return $this->all();
    }
}
Route::get('/users', 'UserRepository@index');

But that would be silly, just as using "Jobs" as domain commands is also kind of silly.

08 Jun
4 years ago

tag started a new conversation Clean Way To Return Existing JSON String?

Many times I get data from file_get_contents(), which returns a JSON serialized string. I can't just do return Response::json(...) because it then re-encodes the string.

I want want to have to run json_decode() first, only to re-encode it with headers, but I also don't want to manually do:

header('Content-Type: application/json)
echo $data;
14 May
4 years ago

tag left a reply on Snake_case Or CamelCase

I prefer camelCase simply because it's easier to type

tag left a reply on Why Laravel Docs Not Good As Codeigniter

Am I the only one around here who was able to learn most of Laravel just from its docs? What wasn't explicitly given as an example, was easily inferred.

Then again, I read the entire documentation like a book so that I had a mental map of what was and wasn't documented, and if I forgot something specifically, I knew where to go look for it in the docs. The stuff that I just couldn't figure out from the docs, I learned from searches and just looking at the source code.

Laravel docs could be better, but I've never learned a framework as thoroughly as I've learned Laravel, specifically because the documentation was well organized and got straight to the point.

So, so, so many different frameworks start you off with off-topic examples instead of the simplest use cases first. There's a straight-forward logic to Laravel's that makes it easy to learn, and useful as a reference.

08 May
4 years ago

tag started a new conversation Change The Introduction Hero Image Call To Action To Point Directly To Laravel 5 Fundamentals

A lot of people always ask how they can learn laravel 5, and everyone always links to Laracasts.com, but rarely do they link directly here:

https://laracasts.com/series/laravel-5-fundamentals

I would suggest updating your home page and making the call to action painfully clear/obvious how to get started learning laravel 5 for free. Not only is that a powerful hook for people to segue into paying for more videos, it will help people know where to go to start off learning Laravel 5.

I know that "Laravel 5" fades into the hero image with a link to the fundamentals, but that assumes the user knows it's a link, and that they know to even wait for it.

I would preserve the tagline: "It's like Netflix For Developers", make it a tiny bit smaller, stop the changing of text/links so it's not as distracting, and then change the current call to action from "Start Learning Now" -> signup page to:

"Start Learning Laravel <$version> For Free" -> link to https://laracasts.com/series/laravel-5-fundamentals

20 Apr
4 years ago

tag started a new conversation Issue With Multiple Tests And AssertRedirectedTo()

I have two test classes. The problem I'm having is that the test in LoginTest passes when ONLY the LoginTest class is called. As soon as I introduce any other test class to the suite, it fails.

Examples below:

class LoginTest extends TestCase
{
    public function test_home_redirects_to_login_if_not_logged_in()
    {
        $response = $this->call('GET', 'http://site.dev');
        $this->assertRedirectedTo('login');
    }
}

And

class WhatTheHellIsWrongWithThisTest extends TestCase
{
    public function test_one_equals_one()
    {
        $this->assertTrue(1 == 1);
    }
}

When I include WhatTheHellIsWrongWithThisTest in the same test suite as LoginTest, I get the following error:

Failed asserting that Illuminate\Http\Response Object (...) is an instance of class "Illuminate\Http\RedirectResponse".

When I delete WhatTheHellIsWrongWithThisTest from the test folder, the test in LoginTest passes. I cannot understand why.

16 Apr
4 years ago

tag left a reply on Generics Equivalent In PHP

@Mythos33, unfortunately PHP does not have native generics, so you'll need an interface for each type of repository if you want to be able to type hint a specific type of Model. The only other option is to be less strict and allow anything that is a Model, as @Ruffles suggested.

13 Apr
4 years ago

tag left a reply on Laravel 5 Unit Testing

Just had the same problem. Documentation for laravel unit testing is really sparse and inconsistent :/

Here's how to test it, but there's an error I can't quite seem to solve:

$response = $this->call('POST', '/your-url', ['your' => '', 'form' => '', 'data' => '']);
$this->assertSessionHasErrors('your'); // True, assuming 'your' is required
$this->assertTrue($response->isRedirection()); // True
$this->assertRedirectedTo('/your-url'); // False, for reasons I can't understand

So the first three lines will at least help you test the input, but I can't test that it's properly redirecting you back to the page you posted from :/

tag started a new conversation How Do You Use PHPUnit To Test Request Objects?

I want to be able to test that given some input array, I get the expected MessageBag results out of a Request object, but there doesn't appear to be an easy way to do this.

Is the only way do something like this a full integration test and actually inspecting the $errors object of the view that gets returned?

07 Apr
4 years ago

tag left a reply on Repositories And Eagar Loading Relationships

Sure:

interface UserRepositoryInterface
{
      public function findAll($pagination = null);
      public function find($id);
      public function save(User $User);
}


class EloquentUserRepository implements UserRepositoryInterface
{
    /** constructor stuff here, inject the model etc **/

    public function findAll($pagination = null)
    {
        $query = $this->user->with('profile', 'role');

        if ($pagination) {
            return $query->paginate($pagination);
        }

        return $query->get();
        }
}

That's it. You simply always eager load `profile` and `role` because even if you don't need them, it does't really hurt THAT much to have them eager loaded (could run out of memory, but likely you'll be paginating anyway).

Basically, you just keep ALL eager loading confined to the repository methods - you deliberately tightly couple them else you break encapsulation.

tag left a reply on Repositories And Eagar Loading Relationships

Eager loading is an internal optimization - it is not necessary for relations to work, so you should not be exposing a public interface for it. You should simply do the eager loading within the EloquentWhateverRepository as eager loading is an Eloquent-specific optimization you need to worry about.

27 Mar
4 years ago

tag left a reply on [Off Topic] Mac Or PC For Development

@vincej

Ubuntu also has a great interface ( Unity )

Unity ran like dogshit on my old machine (and my colleague's machine) - I had to switch to Gnome. If I hit the start key to open up Unity app search by accident, I would have to wait ~10 seconds for it to open, and then after I closed it, the entire machine ran slower - as if it was trying to do some find * operation in the background...

Also, Unity would frequently use track of the menu bar for an application when you went full screen. I had to do a lot of process killing to close windows...

I had an i5 dual core, w/4gigs of RAM. I don't know what GPU it used (was my work computer), but it was a horrendous experience.