audunru

audunru

Member Since 3 Years Ago

Oslo

Senior Content Advisor at Netlife Research

Experience Points 17,210
Experience Level 4

2,790 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 137
Lessons
Completed
Best Reply Awards 5
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.

26 Jun
3 weeks ago

audunru left a reply on Database Layout Ideas

There's also hasManyTrough: https://laravel.com/docs/5.8/eloquent-relationships#has-many-through

So if a user hasMany messages, and a message belongsTo a conversation, I believe you could get all the conversations a user has using hasManyThrough.

23 Jun
3 weeks ago

audunru left a reply on How To Use Update Method In ApiResource Routes ?

Well, it depends, but typically you'd have one request to fetch a bunch of posts (index), another to fetch a single post (show) and a third to update. Which would correspond to the user seeing a list of posts, clicking on a post to view a form and clicking submit to update.

audunru left a reply on I Cannot Use Auth::user() In Controller

Shouldn’t that be ‘Auth::user()->id’ ?

22 Jun
3 weeks ago

audunru left a reply on How To Use Update Method In ApiResource Routes ?

If your resource is /posts, you can GET and POST to /posts to retrieve all posts or create a new post. But to update a post, you should PUT/PATCH to /posts/123, where 123 is the ID. Could that be it?

20 Jun
4 weeks ago

audunru left a reply on API

If you just return the model from your controller, it will be converted to an array, and in the case of JSON requests, come back as JSON. I guess in theory you could write a middleware that would return any requested model this way. Many of the entry level Laravel tutorials show you how to return a model directly from a route, I guess you’ve seen that. So something like that, but for all models.

I think in reality, you would want to have more control over how each model is represented as JSON. That’s where Resources are useful. See https://laravel.com/docs/5.8/eloquent-resources

Also, controllers are a good place for authorization and validation (perhaps with the help of Policies and Requests), which may vary from model to model. And if your API will not only retrieve data, but also create, update, delete, and so on, I think you would need a controller either way. And then the “retrieve” part is usually very simple compared to create or update, for instance.

18 Jun
1 month ago

audunru left a reply on Eloquent CRUD Logging Solution

Tried to replicate your setup in 5.4, and I think it’s hard to debug because the data you want to log is set (or can be set) in many places. Maybe it’s just because I don’t have all the code, but that was my impression. I still think an observer would be nice to try, as they are dedicated to observing created etc events on models.

Imagine that your app does not have any logging a all, but creating, updating etc models work fine. I think that’s the situation you were in. You now want to introduce logging. Since you want to decide what data to log for each event (like the model name, authenticated user, action and the payload), and this data sometimes differs (like your country=UK example), I think it would be cleaner if the Observer (the class that does the logging) knows what the logging format should be, and not the controller or the model. (Long sentence, sorry).

In other words, the models retrieve and store data in the database. The controllers validate input and present data. The observer listens for events and knows what to do if anything happens, which in your case is to log.

You can access the current request from the observer, so when an event occurs and you need to log something, if there’s data in the request that you can’t find in the model, you could always get it from the request and log it as well.

It’s not that using events and a listener is wrong, you can still do that, but I suggest you try moving the logic of what to log from your model/controller to where the logging takes place.

14 Jun
1 month ago

audunru left a reply on Eloquent CRUD Logging Solution

So when you set “country” to “UK” in your last example, that’s where it fails? Are you sure you can modify the request like that? I would dd() the payload and check what actually happens there.

12 Jun
1 month ago

audunru left a reply on Eloquent CRUD Logging Solution

I’m referring to the Payload accessor and mutator, which looks to me like you do some data preparation before logging it.

audunru left a reply on Eloquent CRUD Logging Solution

Excuse me if I’m missing something, but why aren’t you using an Observer to observe the models you want to log, and then handle any data transformation you need done before logging in the observer class? See https://laravel.com/docs/5.4/eloquent#observers

audunru left a reply on How To Secure My API Without Setup OAuth?

I think you do want Passport, but use Personal Access Tokens. You will get an api key that you can use to authenticate your requests to your api, no need to worry about an authentication flow, refresh tokens, etc.

https://laravel.com/docs/5.8/passport#personal-access-tokens

Laravel also offers a simple API token system, described here: https://laravel.com/docs/5.8/api-authentication

But in my experience, just go with Passport to begin with. You have to do some work in both cases anyway, and Passport gives you all the commands you need to generate keys once you’ve set it up. Also, if you need multiple keys or something in the future, you’re ready for that situation.

08 Jun
1 month ago

audunru left a reply on Let Public Vue SPA To Store Data On Laravel API (authenticated In Some Way)

I’m thinking you could generate a long, random string when you send the email. Store this in a table that will contain appointment ids and the random strings. The link in the email will include the random string, and when the server receives the request to set up the new appointment, you would only allow it if the string is in that table and matches the original appointment. So basically you’re saying “if you know the secret for appointment X, I will allow you to schedule a new time for it”. Don’t include any personal info in the email or the form, and I think you’d have a good enough “security through obscurity” system.

07 Jun
1 month ago

audunru left a reply on Laravel API Returns A View 404 Error Instead Of JSON Error

You probably have debug set to true, you should try with it set to false if you want to see what error you would get in production. It’s in the environment file (though I guess you knew that). :-)

05 Jun
1 month ago

audunru left a reply on Laravel API Returns A View 404 Error Instead Of JSON Error

Just tested with the app I'm working on right now, and without Accept: application/json in the request, I'm getting HTML back when there's an error.

This is the latest version of Laravel (5.8.20), nothing special in the controllers or Handler.php to check if the request wants json or not. So I think you should check with Postman or something similar if you're getting JSON errors back when you request JSON.

HTML:

https://i.imgur.com/oWXnhRh.png

JSON:

https://i.imgur.com/3irKyc8.png

04 Jun
1 month ago

audunru left a reply on Laravel API Returns A View 404 Error Instead Of JSON Error

When you make your request, are you using the "Accept: application/json" HTTP Header?

20 Mar
3 months ago

audunru left a reply on Laravel With Amazon SQS

Use two queues. Depending on how strict you are with keeping similar environments, you could use the database driver in development and SQS in prod. Or just two SQS queues.

The docs say: “When the job is actually handled, the queue system will automatically re-retrieve the full model instance from the database. It's all totally transparent to your application and prevents issues that can arise from serializing full Eloquent model instances.“

So you’ll get data from the environment that picks up the job as far as I understand it.

You could pass the environment setting to the job when dispatching it, and check that it matches when it runs, but I think two queues is cleaner.

19 Mar
3 months ago

audunru left a reply on Two Laravel Projects, API And Front (Web). How To "login" The User?

@LUDDINUS - Yes, Guzzle is pretty standard for making requests backend. You’ll see it in lots of tutorials.

01 Mar
4 months ago

audunru left a reply on Controllers Structure For API And "regular" Routes

Yes, definetely #3. That’s the default, recommended option, I would say. Your web route, the one that returns the blade view, will be very simple. But the API route will most likely deal with authorization, validation and so on, so there’s good reason why you want that in two different classes.

27 Feb
4 months ago

audunru left a reply on Nuxt SSR + Laravel API Nginx Conf Advice

There’s nothing unusual about a combo like this. Have you looked at the documentation? It explains how to setup Nginx on Laravel Forge as a proxy for node: https://nuxtjs.org/faq/nginx-proxy

audunru left a reply on Relationship With 3 Tables

Can you please explain how these relationships work in real life. Eg. “A store can have many brands”. Since you’re having trouble with your code it’s difficult to understand what you’re trying to achieve from the code alone.

25 Feb
4 months ago

audunru left a reply on Best Way To Handle Huge Insertion In Laravel Considering Both Timeout And Memory Issue

@ssquare Sorry, didn't get any notification about your reply. The already processed jobs are completed, they do not take up resources from jobs that are not processed. Yes, even though you dispatch new jobs from Job[1], this does not make Job[1] bigger/more resource intensive.

16 Feb
5 months ago

audunru left a reply on Consume Same API For Both Web And Mobile Or Not?

Again, I would do what you originally suggested. Use ApiControllers to comunicate with database. Use WebControllers to return blade views, then load data from ApiControllers in your Vue app. Fewer things that can break.

audunru left a reply on Best Way To Handle Huge Insertion In Laravel Considering Both Timeout And Memory Issue

@SSQUARE - When you dispatch a job from a job and it goes into the queue, the first job does not wait for the 2nd job to finish.

15 Feb
5 months ago

audunru left a reply on Best Way To Handle Huge Insertion In Laravel Considering Both Timeout And Memory Issue

Create a job that gets a chunk and prosesses it. Say rows 0-100. Just enough so that it doesn’t time out or use too much memory. Once the processing is over, dispatch a new job from the first job, but give it the index it should start from (101). Could that work?

14 Feb
5 months ago

audunru left a reply on Consume Same API For Both Web And Mobile Or Not?

I would do what you’re suggesting. You will typically have very few controllers for the blade views, as once the Vue app is loaded you will most likely use vue-router from there on. You will have the benefit of having fewer controllers to send and receive data, and your API tests will verify that the web and mobile clients can expect similar results as they’re both hitting the same endpoints.

audunru left a reply on Socialite Can't Login With Google

That’s great. Just wanted to say that for existing users, you’re relying on the email address only to log them in. A Google Account is not necessarily a @gmail.com address, and it can change. For instance, my company changed its domain name and since we use GSuite it became very obvious which services relied on the email and which ones didn’t. So what you want is to lookup the google_id when logging in Google users, not the email.

13 Feb
5 months ago

audunru left a reply on Eager Load Pivot Model Relations

I think I have the same setup in my app. I have Product and Sale models, which are related through a pivot model. In order to get eager loading working, I found this on Github: https://github.com/laravel/ideas/issues/1089#issue-309827982

Here's how it works in my app:

app/Database/EloquentBuilder.php

<?php

namespace App\Database;

use Closure;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\RelationNotFoundException;
use Illuminate\Database\Eloquent\Relations\Pivot;

class EloquentBuilder extends Builder
{
    protected function eagerLoadRelation(array $models, $name, Closure $constraints)
    {
        try {
            return parent::eagerLoadRelation($models, $name, $constraints);
        } catch (RelationNotFoundException $e) {
            // The eager loading request is not a relation - is it a pivot?
            if (head($models)->{$name} instanceof Pivot) {
                $relations = [];

                foreach ($this->filterEagerLoad($name) as $key => $value) {
                    $relations[substr($key, strlen($name) + 1)] = $value;
                }

                $this->getModel()->newCollection(array_pluck($models, $name))->load($relations);

                return $models;
            }

            throw $e;
        }
    }

    private function filterEagerLoad($name)
    {
        return array_filter($this->eagerLoad, function ($relation) use ($name) {
            return $relation != $name && starts_with($relation, $name);
        }, ARRAY_FILTER_USE_KEY);
    }
}

app/BaseModel.php:

<?php

namespace App;

use App\Database\EloquentBuilder;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    public function newEloquentBuilder($query)
    {
        return new EloquentBuilder($query);
    }
}

app/Sale.php (just the start):

class Sale extends BaseModel
{
    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['sold_at'];

    protected $fillable = [
        'sold_at', 'buyer_name', 'shipping_gross_price',
    ];

    public function company()
    {
        return $this->belongsTo('App\Company');
    }

    public function products()
    {
        return $this->belongsToMany('App\Product')->using('App\ProductSale')->withPivot('gross_price');
    }

app/Http/Controllers/SaleController.php (just the index method):

    public function index(FilterSales $request, Company $company)
    {
        abort_unless(Auth::user()->can('view', $company), 403);

        $sales = $company->sales()
            ->year($request->sold_in)
            ->ordered()
            ->with('products.sales.pivot.product')
            ->get();

        return SaleResource::collection($sales);
    }
11 Feb
5 months ago

audunru left a reply on Forge & Digital Ocean - Package Updates

The message means something has already been installed that requires a reboot.

09 Feb
5 months ago

audunru left a reply on Laraval 5.7.* - Vue Js Authentication Issue

This sounds like a CORS issue. I would read up on it. Here’s an article about CORS, Laravel and a package from Spatie that may help: https://murze.be/handling-cors-in-a-laravel-application

audunru left a reply on Forge & Digital Ocean - Package Updates

Make it predictable for users. Schedule it to minimize downtime. Eg. don’t do first day of month if that’s when they all do their reporting... Do it manually, so you can decide if it’s really needed if something could break. Have a staging environment where you upgrade first. Keep backups but IMO you don’t need to power off to take a snapshot. Instead verify regularly that in case of a complete disaster during upgrade you can get up and running quickly. Ubuntu has Livepatch for kernel upgrades without reboot.

05 Feb
5 months ago

audunru left a reply on Laravel 5.6 - Backup MySql Database To S3?

What does the local .sql file look like? I think it should contain the same error from mysql? If it doesn't, then there's something wrong with your upload. Maybe it was uploaded to S3 at some point when there was an error, and now it's not being uploaded. So perhaps comment the unlink() line and check your local file.

Perhaps you should dump() or dd() the value of $command before you start the process. Just to make sure that your command indeed contains all the values that mysqldump needs. Because that's what it's complaining about.

29 Jan
5 months ago

audunru left a reply on Separate Users Tables. One For Normal Users With Socialite And The Other One For Admins With Laravel Out Of The Box Authentication.

I'm thinking your code will be cleaner and more secure if you use the defaults as much as possible. If you have two tables, there are more places in your code where you could make your app less secure than the alternative.

I've never used a payment gateway in Laravel, sorry. Think you should ask that as a separate question.

audunru left a reply on Separate Users Tables. One For Normal Users With Socialite And The Other One For Admins With Laravel Out Of The Box Authentication.

You don't have to have two tables. You could use one table, with the default name "users", and put both your Socialite registered users and admins. I've never used two tables like you're asking, but I imagine you would have to write a good amount of code to get around the fact that Laravel expects the table to be called "users" and that there's just one table... For instance, I'm not sure how you would get Passport to handle API authentication with two tables.

You could use a relationship on your User model like role() to specify whether a user is admin or not.

Actually, with this setup, whether you're a Socialite user or use username+password does not determine whether you're an admin or not. That's what the user role does.

18 Jan
6 months ago

audunru left a reply on What Is The Main Purpose Of Developing REST API?

I followed https://laracasts.com/series/incremental-api-development when I wrote my first API in Laravel. It might be a bit dated because I think Resource was added to Laravel later.

I use Passport for authentication. I don't think it's mentioned in that series, but I saw @dunsti already posted a bunch of links which mentioned it. You should definitely use it.

audunru left a reply on Dusk Environment

Since you're asking about environments and databases, I think it's worth mentioning that if you start your app with php artisan serve, then the app will probably be using your local environment, and consequently not your test database.

So if you specify in.env.dusk.local that Dusk should use a testing database, any model you create using model factories etc in your tests will be saved to the testing database. But when you visit pages during the page, complete a form and submit, you're accessing the environment used by php artisan serve, so that's why you're not seeing data in your development database.

So basically this is not like running vendor/bin/phpunit, where you can specify a different database in phpunit.xml and everything, even http tests, will be run against your test database.

At least that's as far as I've understood it. I hope someone can prove me wrong, because it's very confusing. I see someone has tried to work around this issue here, but I tried it briefly and I don't think the code works as is with the latest Laravel 5.7. https://medium.com/@deleugpn/running-serve-automatically-prior-to-laravel-dusk-9eedf295bbd6

audunru left a reply on What Is The Main Purpose Of Developing REST API?

  • Open up your app so your customers can access their data and use it in new ways. After all, it's their data.
  • Allow other applications (developed by you or someone else) to interact with your existing application
  • Allow others to develop new applications on top of your application
  • Comply with local regulations that may or may not require you to allow access to customer data through an API (think PSD2 for banking in the EU or public access to government data if it's a government application)
  • Stop using HTML templates rendered server-side, start using client side React/Vue/etc applications that fetch data from your API
  • Make the API the only way to access data in your app, so that you consume your own API as well as let others access it from the outside. If not, you'll have to maintain an internal API as well as an external API.
30 Dec
6 months ago

audunru started a new conversation Multiple Scopes

Wondering how to apply multiple, optional scopes in my controller in the cleanest way.

The frontend can make a GET request like /api/v1/company/1/products or /api/v1/company/1/products?purchased_in=2018&keyword=festivus, and my ProductController.php currently looks like this:

    public function index(FilterProducts $request, Company $company)
    {
        abort_unless(Auth::user()->can('view', $company), 403);
        $validated = $request->validated();

        if (isset($validated['purchased_in'])) {
            $products = $products->year($validated['purchased_in']);
        }
        if (isset($validated['keyword'])) {
            $products = $products->search($validated['keyword']);
        }

        return ProductResource::collection($products->get());
    }

I have other functions where the number of available scopes is even greater, so I'm thinking there must be a cleaner way to chain these together even though the frontend may not always specify all a purchased_in or keyword, and so on.

21 Dec
6 months ago

audunru left a reply on Incrementing A Column Other Than Primary Key

@WILK_RANDALL - Yeah, that feels better. It won't be a big issue, I'm sure. At least the unique index on the products table ensures that no two products belonging to the same company will have the same code.

audunru started a new conversation Incrementing A Column Other Than Primary Key

I'm looking into how I can auto-increment a column in my database other than the primary key.

Here goes:

In my app, a Company can have many Products. A Product belongs to only one Company.

A Product has a primary key, but a "code" as well, which is an unsigned integer starting at 1. If there are two companies with 5 products each, both companies will have products with the codes 1, 2, 3, 4 and 5.

Products can be soft-deleted, so if product with code 5 is deleted, the next new product should have code 6.

Codes should be auto-generated. After a Product has been stored, the code cannot be changed.

My Company model has this function that I use to add new products.

    public function addProduct(Product $product)
    {
        $product->code = Product::withTrashed()->max('code') + 1;

        return $this->products()->save($product);
    }

The problem with the code above is that in the event that two users are adding products at the same time, potentially the same code (max + 1) could be returned, giving one of them an error. It also does not feel good to set the code in the Company model instead of the Product model.

The migration for my "products" table ensures that a single Company cannot have two products with the same code (see the unique index):

        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('code')->unsigned();
            $table->string('description');
            $table->integer('company_id')->unsigned();
            $table->unique(['company_id', 'code']);
            $table->timestamps();
            $table->softDeletes();
        });

I use mariadb as the database but I'm open for suggestions if there is some other database that can solve this at the database level.

26 Jun
1 year ago

audunru left a reply on Run Php Artisan Command Before Mix Build

Hi @zshan63 sorry for the late reply.

Generally I think php artisan vendor:publish is most commonly used to copy eg. configuration files so that they will become part of your codebase. You typically run the command once, make necessary changes to the files that have been published, and then commit the files to your version control system (eg. Git).

Therefore I can't really see why you would want to include that command in your webpack.mix.js

My original question concerns running shell commands that need to be run ever ytime something changes, specifically generating JS language files when the Laravel translation files change.

18 Apr
1 year ago

audunru left a reply on Clear Cache Before Deploy?

Thanks, I will try on next deploy and report back.

15 Apr
1 year ago

audunru left a reply on Clear Cache Before Deploy?

I think perhaps that's where it fails. Included some more lines from the failed deployment log:

  - Installing axn/laravel-laroute (1.2.0): Downloading (connecting...)                           Downloading (0%)                                      Downloading (30%)                 Downloading (60%)                 Downloading (90%)                 Downloading (100%)
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover

In ProviderRepository.php line 208:
                                                                              
  Class 'LaravelBA\LaravelJsRoutes\LaravelJsRoutesServiceProvider' not found  
                                                                              

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

audunru left a reply on Clear Cache Before Deploy?

Laravel 5.5, btw.

audunru started a new conversation Clear Cache Before Deploy?

I recently replaced a composer package with another (laravelba/laravel-js-routes to aaronlord/laroute). Removed the old one with composer remove.

On deploy I get this error.

@php artisan package:discover

In ProviderRepository.php line 208:
                                                                              
  Class 'LaravelBA\LaravelJsRoutes\LaravelJsRoutesServiceProvider' not found  
                                                                              

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

I've encountered it before, and clearing bootstrap/cache and redploying fixes it. Which leads me to believe clearing/removing the cache should be part of my deploy script. Does anyone know exactly what needs to be cleared/deleted, and if so, is there a artisan command to achieve this?

Here's my deploy script, maybe there's something there I should fix.

cd /home/forge/feedleback.com
php artisan down --message='Feedleback is being updated' --retry=180
git pull origin master
composer install --no-interaction --no-dev --prefer-dist
php artisan migrate --force
php artisan clear-compiled
php artisan config:cache
php artisan route:cache
php artisan cdn:push
php artisan queue:restart
php artisan up
php artisan opcache:clear
26 Dec
1 year ago

audunru left a reply on Run Php Artisan Command Before Mix Build

And the other command I was able to use WebpackShellPlugin. Here's what I ended up with:

const mix = require('laravel-mix');
const WebpackShellPlugin = require('webpack-shell-plugin');

mix.webpackConfig({
    plugins: [
        new WebpackShellPlugin({ onBuildStart: ['php artisan routes:javascript'], onBuildEnd: [] }),
    ],
    module: {
        rules: [
            {
                // Matches all PHP or JSON files in `resources/lang` directory.
                test: /resources(\|\/)lang.+\.(php|json)$/,
                loader: 'laravel-localization-loader',
            },
        ],
    },
});

mix.sass('resources/assets/sass/app.scss', 'public/css')
    .react('resources/assets/js/app.js', 'public/js')
    .browserSync({
        proxy: 'localhost:8000',
    });

if (mix.inProduction()) {
    mix.version();
}

audunru left a reply on Run Php Artisan Command Before Mix Build

OK so the second command I was able to remove because the author has created something specific for webpack... https://github.com/rmariuzzo/laravel-localization-loader

audunru started a new conversation Run Php Artisan Command Before Mix Build

I have a couple of php artisan commands that I'd like to run before my javascript is compiled. So I learned about then(), but that happens after the build. Any suggestions?

Here's my webpack.mix.js

const mix = require('laravel-mix');
const { exec } = require('child_process');

mix
   // Kind of like this, but exactly the opposite...
    .then(() => {
        exec('php artisan routes:javascript');
        exec('php artisan lang:js --no-lib resources/assets/js/translations.js');
    })
    .sass('resources/assets/sass/app.scss', 'public/css')
    .react('resources/assets/js/app.js', 'public/js')
    .browserSync({
        proxy: 'localhost:8000',
    });

if (mix.inProduction()) {
    mix.version();
}
09 Mar
2 years ago

audunru left a reply on Forge Password On Digital Ocean

OK. Thanks. Maybe I changed the password, deleted the email and forgot to save the new password to my password manager. I'll just change it on the server, then.

audunru started a new conversation Forge Password On Digital Ocean

I have a server on Digital Ocean and I use Forge.

I've added my public key so I can ssh to the server using ssh [email protected] in the Terminal.

I reset the root password from digitalocean.com, so I can su, enter the password and do things like apt-get upgrade, reboot, etc.

So far so good.

My question is. Am I supposed to have a password for the forge user on my server as well? From googling it looks like I should have received an email with the password when the server was created through Forge, but I don't have it anymore.

20 Oct
2 years ago

audunru left a reply on In Which Order Should Authentication, 404s, Etc Be Checked?

Authentication (the 1st step) is handled by the auth:api middleware btw, so that check is run before the method.

audunru left a reply on In Which Order Should Authentication, 404s, Etc Be Checked?

Looks reasonable. Here's what I have so far

    public function update(Site $site, $id, Request $request)
    {
        $feedback = Feedback::find($id);

        // Check authorization
        $this->authorize('update', $feedback);

        if (!$feedback) {
            return $this->respondNotFound();
        }

        $validator = Validator::make($request->all(), [
            'fields' => 'required|array',
            'fields.vote' => 'in:yes,no',
            'fields.comment' => 'string|nullable|max:2000',
            'fields.url' => 'string|max:2000',
            'fields.hide' => 'boolean'
        ]);

        if ($validator->fails()) {
            return $this->respondUnprocessableEntity(trans("messages.validationFailed"));
        }
        if (isset($request->fields['url'])) {
            $feedback->fill(array_merge(
                $request->fields,
                $this->parseUrl($request->fields['url'])
            ));
        } else {
            $feedback->fill($request->fields);
        }

        if (!$feedback->save()) {
            return $this->respondInternalError();
        }
        return $this->respond(array(
            'message' => trans("feedbacks.feedbackUpdated")
        ));
    }

The only question that remains is how to deal with authorization and 404s. Right now, a 404 can't really happen because authorize() will not be able to check authorization for something that does not exist.