Garet

Garet

Member Since 8 Months Ago

Experience Points
3,850
Total
Experience

1,150 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
21
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 1
3,850 XP
Nov
24
2 weeks ago
Activity icon

Replied to Issues Moving Sessions To Global Middleware Stack

I do indeed have a controller for switching the language, and redirecting back to the previous page. However switching language stores the chosen language in the session, so I have a middleware which retrieves the chosen language from the session. It's this middleware that doesn't work on 404 pages.

Anyway, I'm pleased to say I have it working now. I moved the session stuff back to the global middleware stack and it all works. I swear previously it didn't, but I also had cookies set to same_site="strict" which stopped the cookie being sent when redirected back from Microsoft Azure, and this was also clouding the issue.

Nov
23
2 weeks ago
Activity icon

Started a new Conversation Issues Moving Sessions To Global Middleware Stack

I have a language switcher on my app and it doesn't work on error pages (for example, 404's) because error exceptions don't go via the "web" route middleware.

I've moved the session classes to the global middleware stack which fixes the issue.

However I am utilising this middleware https://github.com/rootinc/laravel-azure-middleware which allows single sign on from Microsoft Azure.

The problem is that the callback from Azure is setting a couple of session values, which aren't persisting. As soon as I move sessions from the global middleware stack back into the "web" group it works correctly (but then breaks the language switcher on my 404 page).

I would have expected sessions to work everywhere if they're in the global middleware stack. What am I missing?

Nov
16
3 weeks ago
Activity icon

Replied to Logging: Changing The Format Of "message"

Hi Sloth, sorry I'm not sure what you mean?

I'm happy to format the message string myself if I could get access to the array passed into the logger, prior to it being converted to a string.

Activity icon

Started a new Conversation Logging: Changing The Format Of "message"

In config/logging.php I've setup a custom channel as follows:

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily'],
        'ignore_exceptions' => false,
    ],

    'activity' => [
        'driver' => 'daily',
        'path' => storage_path('logs/activity.log'),
        'level' => 'info',
        'formatter' => Monolog\Formatter\LineFormatter::class,
        'formatter_with' => [
            'format' => "%datetime%: %message%\n",
        ],
    ],

However what I would like to do is change the format of %message%

The only thing I ever intend to log to the activity log is an array, but I want to display it in the log as a string in a specific format.

How I would like to log to the activity log:

Log::channel('activity')->info(['key1' => 'value', 'key2' => 'value 2']);

Then I would like my log format to be:

2019-11-16T07:10:35.00+00:00; key1=value; key2="value 2"

I have tried using the tap attribute on the log channel configuration, and also extending the Mogolog LineFormatter class, but so far I have drawn a blank in terms of being able to format the message value as I want it.

Nov
15
3 weeks ago
Activity icon

Replied to Separate Front-end And Back-end Application With Single Codebase

@tykus that's actually a good solution, and would be taken care of at the webserver level instead of the application level.

The only issue there is whether the client is happy for the admin code to live on the public facing server, even though it's not accessible.

Activity icon

Replied to Separate Front-end And Back-end Application With Single Codebase

The application already does that, but the client wants to host the back-end internally on their network, and remove it from the public facing server that hosts the front-end

Activity icon

Started a new Conversation Separate Front-end And Back-end Application With Single Codebase

My question isn't how to create a front-end and a back-end for my application - I already know how to do that. In fact my question isn't really even Laravel specific, but since it's built in Laravel I thought I would ask here.

Basically I have built an application that has a front-end interface, and a back-end interface for admin users. My front-end functionality is organised into /app/Http/Controllers/Frontend and /resources/views/frontend and my back-end functionality is organised into /app/Http/Controllers/Backend and /resources/views/backend

My models are shared between the two different sets of controllers.

My routes are organised into namespaced routes accessible from two different domains, again one set of routes for front-end and one set of routes for back-end.

This works absolutely fine, however for additional security my client would now like to move the back-end functionality to a non-public facing server since it only needs to be accessed from within their network.

Because the models are shared between front-end and back-end I would prefer to keep a single codebase, and a single github repository.

What this means is that when the front-end code is deployed, someone would have to manually remove the admin routes from the routes file, and also delete the entire contents of /app/Http/Controllers/Backend and /resources/views/backend

Since the code will be deployed automatically, I don't want someone to have to manually adjust the routes and delete the above directories every time code changes are pushed to the repository.

Sorry if there is an obvious or easy solution to this, but I cannot think of one.

Thanks

Nov
14
3 weeks ago
Activity icon

Replied to Creating Global Variable From Service Provider

Thanks for your help @bobbybouwmann as always it is greatly appreciated.

Activity icon

Replied to Creating Global Variable From Service Provider

Ignore my last comment, config is indeed available in the error exception views!

Activity icon

Replied to Creating Global Variable From Service Provider

Thanks @bobbybouwmann I amended it to use config as you suggested because it seems like a better way.

However there is a snag. Now my error pages (for example 404 pages) don't have access to config whereas before they did have access to the service container. Do you know if there is a simple solution to that?

Nov
13
3 weeks ago
Activity icon

Replied to Creating Global Variable From Service Provider

@bobbybouwmann thanks, what I've ended up doing is ditching the Domains class and my service provider is as follows:

public function boot()
{

    $host = request()->getHttpHost();

    if (isset(config('domains')[$host])) {
        $this->domain = config('domains')[$host];
    }

    $this->app->singleton('domain', function($app) {
        return $this->domain;
    });
}

Then I can access the domain configuration everywhere, including in blade templates, like:

$domain = app('domain');
echo $domain['name'];

Or

app('domain')['name']

I guess this is very similar to what you're suggesting, but is it an abuse of the service container?

Activity icon

Started a new Conversation Creating Global Variable From Service Provider

I'm creating a multi-domain application, so my application is served from multiple domains. Each domain has its own configuration like this:

app/config/domains.php

return [
    'www.domain1.com' => [
        'name' => 'UK',
        'default_language' => 'en',
        'languages_available' => ['en'],
        'email' => '[email protected]',
    ],
    'www.domain2.com' => [
        'name' => 'France',
        'default_language' => 'fr',
        'languages_available' => ['fr', 'en'],
        'email' => '[email protected]',
    ],
]

I want to be able to access a $domain variable from anywhere in my application that will give me the configuration for the current domain that is being used to access the application.

Here's how I've done it so far.

I've created a very simple Domain class which takes an array and converts it to an object as follows:

app/domain.php

class Domain {
    public function __construct($domain)
    {
        foreach ($domain as $key => $value)
            $this->$key = $domain;
        }
    }
}

Then I've created a DomainServiceProvider.php and in the boot method I do:

$host = request()->getHttpHost();

$this->domain = isset(config('domains')[$host]) ? config('domains')[$host] : [];

app->singletone('App/Domain', function($app) {
    return new Domain($this->domain);
});

Then in any of my controllers I can do:

class HomeController extends Controller
{
    public function show(Domain $domain)
    {

        if ($domain->name == 'UK') {
            // Do something here
        }

        // Return the view and pass $domain instance
        return view('show', [
            'domain' => $domain,
        ]);
    }
}
    

How does this seem? It works OK but I'm wondering if there is a more simple way? In particular is there a way og doing it without creating the Domain class which seems a little redundant.

Nov
12
3 weeks ago
Activity icon

Replied to What Are Your Next Steps After Learning The Tools With Laravel?

Similar to Sinnbeck, I had an old desktop application which ran on my PC and reminder me when things were due for renewal. It still worked, but I knew it could be better, so I re-wrote it in Laravel.

It took me a long time and was a big learning curve, but I'm glad I stuck with it. As I developed the application I added more and more features (for example, the ability to create other users, the ability to upload user avatar images, etc). Some of the features I didn't need but I kept adding them anyway, knowing that they would come in useful for other projects in the future.

Activity icon

Replied to Laravel And Wordpress

I do a lot of WordPress development and Snapey is correct, they are two different things. Your friend is comparing an apple with an orange.

WordPress is good if you want to setup a content managed website that's really easy for a non-technical user to update (particularly if you use a plugin such as Advanced Custom Fields). You can use an off-the-shelf theme or, as I prefer, build a theme completely from scratch (which requires a bit more work and skill).

However, WordPress is a bloated mess. Don't get me started on WooCommerce (WordPress' ecommerce plugin). If you only have experience with Laravel it would make you cry.

The thing is, if I wanted to build a 10 page website with the ability to create and update page content, upload and manage images and galleries, and edit navigation menus, I could use WordPress which does all of these things out of the box, or I could spend days/weeks creating this functionality in Laravel. As it happens I have written Laravel applications recently that do some of these things, but they still don't do it as well as WordPress does.

But with that said, I have built Laravel applications recently that are more suited to the framework, and the end result is an organised, well structured application. Whilst I could have built those applications in WordPress, they would have been a hodgepodge of code with an interface limited to the way WordPress does things rather than looking and functioning exactly as I want them.

If you built something in Laravel that was less secure, less SEO friendly and slower than WordPress, then I would suggest that this is down to your own skills rather than Laravel being "worse".

Nov
11
4 weeks ago
Activity icon

Replied to Best Way To Separate Config File For Development And Production, Without Using Env File!

@tykus - that sounds feasible but since all files in the config directory are automatically included, how would I include just the file specified in the .env ?

Activity icon

Started a new Conversation Best Way To Separate Config File For Development And Production, Without Using Env File!

I'd like to know the best way of separating a configuration file, so that I can have different configuration between development and production.

"Use the .env file!" I hear you say.

However, I'm talking about more complex configuration, rather than simple key => value pairs.

For example:

config/favorites.php

Containing:

return [
    'blueberry' => [
        'color' => 'blue',
        'size' => 'small',
        'goes_with' => ['yoghurt', 'icecream']
    ],
    'banana' => [
        'color' => 'yellow',
        'size' => 'medium',
        'goes_with' => ['peanut_butter'],
    ],
]

I might want the above file to contain different values between development and production. The only way I can think of at the moment is to have 3 files config/favorites.EXAMPLE.php, config/favorites.DEV.php and config/favorites.PROD.php and rename one of them depending on my environment. The DEV and PROD versions could be excluded from a repository using gitignore leaving just the EXAMPLE file in the repository.

But, is there a better way?

Nov
08
1 month ago
Activity icon

Replied to When To Use Config Variable Vs Accessing Env Variable Directly

OK, looks as though I'm doing it right! I had a feeling that caching the configuration would break things if using env directly

Activity icon

Started a new Conversation When To Use Config Variable Vs Accessing Env Variable Directly

I understand how both environment and configuration variables work (and can work together).

What I'm unsure of is when it's OK to access an environment variable directly.

Here's an example: let's say I want to restrict my application to a single IP address which might be different between development and production environments, so in my .env file I have:

RESTRICTED_IP=202.24.84.101

In my middleware I can then check for the IP address using:

if (env('RESTRICTED_IP'))

Alternatively in config\app.php I could create a variable like so:

'restricted_id' => env('RESTRICTED_IP', '')

Then in my middleware I would check for the IP using:

if (config('restricted_ip'))

Is the addition of the variable in the configuraton file superflous and should I just access the enviroment variable directly?

Nov
05
1 month ago
Activity icon

Replied to Cannot Cache Config, Your Configuration Files Are Not Serializable

Yes it was, in my own code :-s I fixed it now :-)

Activity icon

Replied to Cannot Cache Config, Your Configuration Files Are Not Serializable

Yes I did, still couldn't seem to track it down. I've found it now though, I did what this answer suggested on Stack Overflow: https://stackoverflow.com/a/56088580/1849981

Activity icon

Replied to Application Configuration In File Or In Database?

OK makes sense, thank you both

Activity icon

Replied to Cannot Cache Config, Your Configuration Files Are Not Serializable

Thanks, I've only installed 2 extra things in the vendor directory, and neither of them have config files that use closures :-(

Activity icon

Replied to Application Configuration In File Or In Database?

Isn't the database containing the API details and being compromised the same end result as the API details being in a config file and the web server being compromised? Otherwise this assumes that the database server could be compromised but the web server is immune.

I'm not trying to be argumentative, just trying to better my understanding. As it happens I'm going to move the API details to the .env file.

Thanks

Activity icon

Replied to Application Configuration In File Or In Database?

Out of interest what's wrong with storing the API credentials in the DB in plain text? If they are cached into a config file then they would presumabely be in plain text in the file?

Thanks!

Activity icon

Started a new Conversation Cannot Cache Config, Your Configuration Files Are Not Serializable

I have one Laravel project and when in production when I do:

php artisan config:cache

I get the following error:

Your configuration files are not serializable

I read that this is often down to callbacks being done in a configuration file, but I have double checked and there are no callbacks in my configuration files!

The full error is below. It makes reference to ConfigCacheCommand.php and Macroable.php, but these appear to be standard framework files.

Your configuration files are not serializable.

  at xxx\vendor\laravel\framework\src\Illuminate\Foundation\Console\ConfigCacheCommand.php:71
    67|             require $configPath;
    68|         } catch (Throwable $e) {
    69|             $this->files->delete($configPath);
    70|
 > 71|             throw new LogicException('Your configuration files are not serializable.', 0, $e);
    72|         }
    73|
    74|         $this->info('Configuration cached successfully!');
    75|     }

  Exception trace:

  1   BadMethodCallException::("Method Illuminate\Support\Collection::__set_state does not exist.")
      xxx\vendor\laravel\framework\src\Illuminate\Support\Traits\Macroable.php:77

  2   Illuminate\Support\Collection::__callStatic("__set_state")
      xxx\bootstrap\cache\config.php:832

  Please use the argument -v to see more details.
Activity icon

Replied to Application Configuration In File Or In Database?

Thanks for your reply @jaytee

Yes, I have a settings model and controller with a database table of key value pairs. Furthermore I specify a field type for each setting, so a setting can be a text box, number input, checkbox, etc.

I then have a settings service provider which retrieves the key value pairs from the database table, caches the results of the query, and then does:

Config::set('settings', $settings);

The above still seems to work even after doing php artisan config:cache in production.

Good call on the API credentials. It's got me thinking that especially where there are two sets of API credentials, sandbox and production, it would be better for these to go in the .env file.

Activity icon

Started a new Conversation Application Configuration In File Or In Database?

With a couple of Laravel apps that I've built, I've created a settings screen where the user can modify the configuration of the application via a GUI. Generally I also build in a permissions system which allows users access to different parts of the app, so the settings area would require the user to have the appropriate permission to access.

Settings include various things like notification email addresses, the default number of results to paginate by, the default date format, etc. If the app is linked up to a service such as MailChimp then it would contain the MailChimp API credentials.

I see that most people tend to include such settings in configuration files. I just wondered whether there is any downside to storing them in the database and providing access to them via an interface in the app? This seems to be much more user friendly if someone wants to change a setting and doesn't have the technical knowledge/ability to edit a config file.

Obviously doing it this way encourages a degree of "tinkering", but as I mentioned users need to be assigned the correct permission to access the settings screen, so it's not something that all users would be given the ability to do.

Any downsides to this approach?

Activity icon

Started a new Conversation Logging User Activity, Without Sensitive Data

I have a requirement to log all user activity made via my app.

I'm using a global middleware to do this and it's working fine. Currently I log the user's IP address, the user's ID (if authenticated), the request method, request URL, http status code and finally the contents of their request.

One thing that has come to light is that if the user enters a password, then their password is logged as plain text as part of the request. What I've decided to do is log the request data except password information, like so:

$request->except(['password', 'password_confirmation'])

Whilst this works, it obviously doesn't account for other sensitive information that could be included in the app in the future.

Is there a better way? Part of me thinks that logging the request information is wrong, but without this it's not possible to ascertain exactly what a user did.

Nov
03
1 month ago
Activity icon

Replied to Is It Safe To Disable VerifyCsrfToken Middleware On Login And Logout Pages ?

In a recent application I made the logout go back to the login page. However if the user leaves this open and tries to login later on, they get an "expired" page which is confusing to them.

I got round this by adding this to the head of my login view:

<meta http-equiv="Refresh" content="300" />

This automatically reloads the login page every 5 minutes, and the CSRF token is re-generated if it needs to be.

Oct
13
1 month ago
Activity icon

Replied to Make Supervisor See Config Changes Without Reload

I managed to figure out another way. First of all, I changed my Supervisor configuration so that it runs as the same user as the webserver (in my case on Ubuntu www-data and on Centos it would be apache). This wasn't the fundamental issue but it wasn't helping that Supervisor was running as root and sometimes creating cache files owned by root.

Secondly, in my controller where I do:

Cache::forget('settings');

I have added:

Artisan::call('queue:restart');

Which restarts the Supervisor process.

Oct
12
1 month ago
Activity icon

Started a new Conversation Make Supervisor See Config Changes Without Reload

Basically I have a set of configuration settings in a database table, which allows an admin user to change the settings via a control panel.

When the user updates the settings, the controller does:

Cache::forget('settings');

Then I have a SettingServiceProvider which caches the settings from the database table as config values like so

    $settings = Cache::rememberForever('settings', function () {

        // Check there is a settings table
        if (Schema::hasTable('settings')) {
            return Setting::all()->pluck('setting_value', 'setting_key');
        }

        return [];
    });

    Config::set('settings', $settings);

So then anywhere in my code I can do config('settings.some_value') to retrieve a setting.

However, a major issue that I've come across is that when queing jobs, the Supervisor process doesn't know when the config cache has changed. In order for it to recognised any changed settings, the Supervisor process needs to be restarted. The problem is, a regular user who changes configuration values via the applications settings controller won't have command line access to restart Supervisor.

Is there any solution?

Thanks,

Sep
23
2 months ago
Activity icon

Replied to Polymorphic Relationship And Accessing Method On Pivot Table

Yes there is a package for it, but since version 5.8 there are events fired for attach, detach and sync.

However in my case the deleting event seems buggy so I've had to revert to essentially calling my own custom event.

Activity icon

Replied to Wordpress And Woocommerce For A Laravel Developer?

I do a lot of work with WordPress and WooCommerce.

You're right, it's one hell of a mess compared with Laravel.

You'll also find some of the things you want to do require additional plugins which often carry an annual fee, so factor that in. There are some very basic and fundamental things that often still require a paid-for plugin with WooCommerce.

The problem with developing a web shop from scratch in Laravel is that you'll be reinventing the wheel, and things you might take for granted in WordPress like basic content management could become a big undertaking in Laravel. Furthermore, when the client decides to, for example, change their payment gateway, with WooCommerce you'd buy a $50 plugin, whereas with Laravel you'll probably have a couple of days development work to achieve the same thing.

I developed a complex web shop last year using CodeIgniter and the end result was really nice, but the client had very specific requirements. I've worked on other web shops where the client's requirements change daily or the client themselves like to tinker, in which case WordPress/WooCommerce is probably more appropriate.

I do love Laravel now though and WordPress, and especially WooCommerce, feel like they're held together with duct tape by comparison.

Activity icon

Replied to Multi Auth With Different Login Forms

In the end I went with a single users table for the purpose of authentication.

I then have separate profile tables for things like members, customers, etc which are related to a core user.

This is also quite good because then an admin user can also be a customer, etc.

The only snag is, I never did figure out how to have a separate login form. So now I use a single login form but redirect the user to different places depending on their profile type.

Activity icon

Replied to Polymorphic Relationship And Accessing Method On Pivot Table

Thanks @bobbybouwmann however I'm pretty sure it's meant to fire on the pivot model, as all of the other events (updated, updating, saving, etc) work.

I found an issue on GitHub: https://github.com/laravel/framework/issues/29631

I extended the MorphPivot class and applied a fix, at which point the deleting event works again. However, there were various other peculiarities, so I've given up using the deleting/deleted events for the time being.

Activity icon

Replied to Differentiating Between Model Traits And Controller Traits

Good thinking, thank you, that makes sense

Sep
22
2 months ago
Activity icon

Started a new Conversation Differentiating Between Model Traits And Controller Traits

I wondered what best practice is for differentiating model traits versus controller traits.

I have a bunch of methods used by various models so I have put them in a trait. Likewise, I have a bunch of methods used by various controllers so I also have them in their own trait.

I just wondered if the traits should be named in a particular way, or stored in different places, to make it clear one is for controllers and the other is for models?

Activity icon

Replied to Polymorphic Relationship And Accessing Method On Pivot Table

@bobbybouwmann Thanks, I did read about extending the Pivot class and I tried this before posting, but it didn't seem to make any difference. Anyway, I tried again with a clear head, and it now works! I can now do $field->pivot->doSomething() and the method gets called.

Now I have a slightly different issue, and that is the deleting event is not firing when I call detach on the pivot table, and according to the docs this should happen as of Laravel version 5.8.

My Page mode:

use Illuminate\Database\Eloquent\Model;

class Page extends Model
{
    public function fields()
    {
        return $this->morphToMany('App\Field', 'fieldable')->using('App\Fieldable')->withPivot(['id', 'field_value']);
    }
}

Here's my Field model:

use Illuminate\Database\Eloquent\Model;

class Field extends Model
{

    /**
     * Fieldables relationship
     * 
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function fieldables()
    {
        return $this->hasMany('App\Fieldable');
    }
}

And my Fieldable model

use Illuminate\Database\Eloquent\Relations\MorphPivot;

class Fieldable extends MorphPivot
{

    public $incrementing = true;

    public $table = 'fieldables';

    public function doSomething()
    {
        // Do something here
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function (Fieldable $fieldable) {

            dd("here"); // We never make it to here

        });
    }
}

When I do $page->fields()->detach($id) I'm expecting it to die and dump with "here" but it never makes it to the deleting event.

Sep
21
2 months ago
Activity icon

Started a new Conversation Polymorphic Relationship And Accessing Method On Pivot Table

I have created a model for a pivot table used by a polymorphic relationship, and just like you can access additional fields on the pivot table, I'd like to be able to access additional methods on the pivot model.

Let me explain further:

I have a model called field. A field can have various field_types, for example text, email, textarea, checkbox.

Various other models can have fields assigned to them, and a field can have a specific value for that model. For example you might assign a text field to a page model with the value of "Hello" and another text field to a different page model with a value of "Goodbye".

I'm using a polymorphic pivot table to achieve this.

Here's my field model:

class Field extends Model
{
    // A field can belong to many pages via the fieldables table
    public function pages()
    {
        return $this->morphedByMany('App\Page', 'fieldable');
    }

    // A field can also belong to many categories via the fieldables table
    public function categories()
    {
        return $this->morphedByMany('App\Category', 'fieldable');
    }
}

My page model then looks like this:

class Page extends Model
{
    // Get all of the fields that are assigned to this page, as well as the field_value specific to this page in the pivot table
    public function fields()
    {
        return $this->morphToMany('App\Field', 'fieldable')->withPivot('field_value');
    }
}

So with the above setup I can do the following:

@foreach ($page->fields as $field)
    @if ($field->field_type == 'checkbox')
        {{ $field->pivot->field_value ? 'Yes' : 'No' }}
    @elseif ($field->field_type == 'text')
        {{ $field->pivot->field_value }}
    @endif
@endforeach

This all works fine, but now I would like to access a method on the pivot item. To help with this I've created a model called fieldable as follows:

class Fieldable extends Model
{
    public function someMethod()
    {
        // Do something
    }
}

So now I'd like to be able to do the following:

@foreach ($page->fields as $field)
    @if ($field->field_type == 'image')
        {{ $field->pivot->doSomething() }}
    @endif
@endforeach

But I have no idea how to achieve the last step. I can access a method on the Field model but not on the Fieldable model.

Sep
16
2 months ago
Activity icon

Replied to Is Naming Columns With Reserved Words Problematic?

I know this is an old one, but I'm wondering whether using reserved words is considered OK or bad practice?

It's just that:

$menu->key

Is more eloquent looking than

$menu->menu_key
Sep
14
2 months ago
Activity icon

Replied to In A Job, Auth::user() Doesn't Work, But Request()->ip() Does! Why?

For testing I was manually running php artisan queue:work but then later on I setup Supervisor and the results are the same

Activity icon

Replied to In A Job, Auth::user() Doesn't Work, But Request()->ip() Does! Why?

That was my first thought, so then I switched from sync to database and tested it, and request()->ip() still works and returns the original user's IP address!

Activity icon

Started a new Conversation In A Job, Auth::user() Doesn't Work, But Request()->ip() Does! Why?

I've moved some of my functionality to jobs, in particular sending notifications and emails.

One thing I noticed right away is that in the handle() method (and subsequent blade view) Auth::user() returns null. This makes sense, because the code is passed away to the job and processed later on, so the job has no notion of a currently authenticated user.

However, request()->ip() does appear to be working and returns the IP address of the user who was responsible for invoking the job. How can this be? Similarly to Auth::user() I would have expected the job to not know what the IP address was for the user.

Sep
13
2 months ago
Activity icon

Replied to Sending Email Notifications - Use Events Or Jobs?

Thanks @topvillas

One argument for doing the check within the job itself, is if the job can be called from multiple places.

For example, a user can create another user from within an administration area, or a new user can register themselves from the front-end of the website. In either case, the admin should receive a notification if config('settings.notify_when_user_created') is true, and by putting this check in the job itself I'm not having to remember to do the check in two places.

Let me know what you think!

Activity icon

Replied to Sending Email Notifications - Use Events Or Jobs?

Thanks Snapey, makes sense.

Another question, let's say I have a job which only needs carrying out when a configuration value is set. Would you suggest that this check should happen inside the job or outside.

For example, let's say I have two configuration values for config('settings.notify_when_user_created') and config('settings.notification_email_address')

So in my controller I could do:

if (config('settings.notify_when_user_created')) {
    // Pass $user model and the notification email address to the job
    SendUserCreatedNotification::dispatch(
        $user, 
        config('settings.notification_email_address')
    );
}

or I could do:

SendUserCreatedNotification::dispatch($user);

...and then check the values of config('settings.notify_when_user_created') and config('settings.notification_email_address') within the job itself.

Which do you think is the correct approach?

Activity icon

Started a new Conversation Sending Email Notifications - Use Events Or Jobs?

My application is sending various email notifications when certain things happen.

For example, when a new user is created, I fire a UserCreated event. I then have a listener called UserCreatedNotification which sends the administrator an email to let them know.

I haven't used jobs as I didn't feel my application warranted having a queue, so I didn't want to setup Supervisor to continually process the queue (however I now realise that you can set the queue to sync which dispatches jobs immediately).

So now I'm wondering whether I should ditch the events and instead dispatch a job directly from the controller to send the notification. That would also give me the option of setting up queues in the future.

I could keep the events and dispatch the job from the event instead of directly from the controller, but since all of my events currently only send email notifications, this feels like an overkill.

Please let me know which seems like the right way! Thank you

Sep
05
3 months ago
Activity icon

Replied to Custom Route Model Binding, Good Or Bad?

Thanks both, Policies and Middleware is what I was missing, back to school for me!

Activity icon

Replied to Learning Laravel And Feeling Overwhelmed

I just thought I would update this thread several months on.

I've now built two projects with Laravel and I absolutely love it. It has been a huge learning curve but eventually all the pieces of the puzzle fit together. The other thing I've learnt is that there are often multiple ways to skin a cat, so personal preference often comes into play.

Eloquent is absolutely brilliant in terms of dealing with collections and not having to write your own queries, loops and manually create objects and multi-dimensional arrays. My only concern is whether queries could sometime be more optimal, and I feel because Eloquent hides much of what's going on under the hood, you're never quite sure. I saw in one of the tutorial videos the use of Telescope which I guess might help with this.

I sometimes run into confusion between Eloquent and Query Builder, and end up scratching my head when a method is available in one and not the other. I also still struggle to get to grips with when to use parentheses and when not to, and I find out by trial and error rather than having a solid understanding of when to use them and when not to.

But overall I'm glad I stuck at it and eventually saw the light. Thanks to everyone that offered encouragement!