kgp43

kgp43

Member Since 3 Years Ago

Experience Points 6,430
Experience Level 2

3,570 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 73
Lessons
Completed
Best Reply Awards 0
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.

16 Mar
4 days ago

kgp43 left a reply on How To Restrict/limit Resource Edit Without An Login System?

I made a simple "session compare", it does what I need.

I normally make an auth system for this type of thing, but this page must not require login/signup. Security is not hugely important either, so this will work fine i think.

        $conf = Configurator::findOrFail($id);
        
        if ($conf->session_id === Session::getId()) {
            return view('configurator.edit');
        } else {
            return redirect('/');
        }
15 Mar
5 days ago

kgp43 left a reply on How To Restrict/limit Resource Edit Without An Login System?

That might be a solution.

Maybe a better solution will be to save the Session ID in the configuration table and match current SESSION ID with the session ID saved in the table. If they match, then it must be the author and the system will allow access to edit the resource.

Now sure if there is a smart method do add that, or a more simple way. Laravel have so much stuff built-in, so I was hoping for something already built :)

kgp43 started a new conversation How To Restrict Resource Edit To Author Based On Session

Hi,

I do not have a login system enabled at the moment, and need to find a workaround, to limit who can edit a resource. Adding the login system is not an option atm.

As of now, all visitors can change settings of my resource (e.g. /configurator/5/edit). How can I make it, so only the creator can edit the resource? Maybe limit on session, but not sure how to do that. I know it will be impossible for them to edit it, after they close the browser - but that will be okay.

Any suggestions?

17 Feb
1 month ago

kgp43 left a reply on How To Access Functions Within A Model, In A View

Thank you very much guys

kgp43 left a reply on How To Access Functions Within A Model, In A View

Hmm... seems like the function I got does not belong to the model in the first place, since its not used to interact with my database. Models are only used for DB stuff, right?

kgp43 started a new conversation How To Access Functions Within A Model, In A View

Hi,

How can I access a function within a model? (in a view) I got this small function in my model, and I would like to access it in my view.

´´´ namespace App;

use Illuminate\Database\Eloquent\Model;

class Convert extends Model { protected $fillable = [ 'unit_type', 'unit_num', ];

public function pressure() {
    
    # Set base values
    # Base: 1 bar
    $base['bar'] = 1;
    $base['pa'] = 100000;
    $base['mpa'] = 0.1;
    $base['nmm2'] = 0.1;
    $base['psi'] = 14.5038;
    $base['ksi'] = 0.0145037738007;
    
    return $base;
    
}

} ´´´

Added this to my view, but it does not work:

´´´ {{ App\Convert::pressure() }} ´´´

12 Jan
2 months ago

kgp43 left a reply on Laracasts On Apple TV?

2 years later, still want this soo badly :)

I love watching coding video on my tv while coding on my laptop. Easy to pause the video with a click on the remote. Annoying to fumble with the phone to unlock and pause. Something like the Udemy app would be lovely i guess.

Seriously hope to see an Apple TV app someday.

10 Jan
2 months ago

kgp43 left a reply on Alter Table Auto_increment, Syntax Error

@VILFAGO - That worked :D Thanks a lot !

public function up()
{
    Schema::create('configurations', function (Blueprint $table) {
        $table->increments('id');
        $table->string('short_description');
        $table->text('long_description')->nullable();
        $table->text('internal_notes')->nullable();
        $table->string('tags');
        $table->boolean('active')->default(true);
        $table->timestamps();
    });
    
    # For mysql
    #DB::statement("ALTER TABLE configurations AUTO_INCREMENT = 14000");
    
    # For sqlite
    DB::insert('insert into sqlite_sequence (name, seq) values (?, ?)', ['configurations', 14000]);
}

kgp43 left a reply on Alter Table Auto_increment, Syntax Error

@VILFAGO - Getting same result. No errors, but ID still start at 1.

Recreating database.sqlite upon each test, so it's an empty table when I create the first record. Not sure if that is causing the problems, but dont think so.

kgp43 left a reply on Alter Table Auto_increment, Syntax Error

@REALRANDYALLEN - I tried that and it helped, some. No error but the ID still start at 1.

public function up()
{
    Schema::create('configurations', function (Blueprint $table) {
        $table->increments('id');
        $table->string('short_description');
        $table->text('long_description')->nullable();
        $table->text('internal_notes')->nullable();
        $table->string('tags');
        $table->boolean('active')->default(true);
        $table->timestamps();
    });
    
    # For sqlite
    DB::statement("UPDATE SQLITE_SEQUENCE SET seq = 14000 WHERE name = 'configurations'");
}

Think the syntax looks okay, at least according to that topic. I also found this one, same solution:

kgp43 left a reply on Alter Table Auto_increment, Syntax Error

Getting same error after removing ; Deleted the database.sqlite file before running the migration, so the database was fresh. Still same error.

public function up()
{
    Schema::create('configurations', function (Blueprint $table) {
        $table->increments('id');
        $table->string('short_description');
        $table->text('long_description')->nullable();
        $table->text('internal_notes')->nullable();
        $table->string('tags');
        $table->boolean('active')->default(true);
        $table->timestamps();
    });
    
    DB::statement("ALTER TABLE configurations AUTO_INCREMENT = 14000");
}

Error:

SQLSTATE[HY000]: General error: 1 near "AUTO_INCREMENT": syntax error (SQL: ALTER TABLE configurations AUTO_INCREMENT = 14000) {"exception":"[object] (Illuminate\Database\QueryException(code: HY000): SQLSTATE[HY000]: General error: 1 near \"AUTO_INCREMENT\": syntax error (SQL: ALTER TABLE configurations AUTO_INCREMENT = 14000) at /home/ec2-user/environment/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: HY000): SQLSTATE[HY000]: General error: 1 near \"AUTO_INCREMENT\": syntax error at /home/ec2-user/environment/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452)

The database is created, but the auto increment is not adjusted to 14000. I can add records to the table, but starting at 1

kgp43 started a new conversation Alter Table Auto_increment, Syntax Error

I'm trying to make my ID increment start at 15000, but getting an error - not sure why.

´´´ public function up() { Schema::create('configurations', function (Blueprint $table) { $table->increments('id'); $table->string('short_description'); $table->text('long_description')->nullable(); $table->text('internal_notes')->nullable(); $table->string('tags'); $table->boolean('active')->default(true); $table->timestamps(); });

    DB::statement("ALTER TABLE configurations AUTO_INCREMENT = 14000;");
}

´´´

I'm getting this error on a fresh sqlite database: ´´´ SQLSTATE[HY000]: General error: 1 near "AUTO_INCREMENT": syntax error (SQL: ALTER TABLE configurations AUTO_INCREMENT = 14000;) {"exception":"[object] (Illuminate\Database\QueryException(code: HY000): SQLSTATE[HY000]: General error: 1 near "AUTO_INCREMENT": syntax error (SQL: ALTER TABLE configurations AUTO_INCREMENT = 14000;) at /home/ec2-user/environment/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: HY000): SQLSTATE[HY000]: General error: 1 near "AUTO_INCREMENT": syntax error at /home/ec2-user/environment/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452) ´´´

It say syntax error, but all looks fine to me.

I searched a lot on Google and all guides told me, that the statement above is the correct way to do it. But why do I get this error then?

Hope one of you might be able to help me :)

, Kenneth

09 Jan
2 months ago

kgp43 left a reply on Class 'App\Nova\' Not Found

Thanks for the reply, I will rename the model as soon my head stop spinning :)

kgp43 started a new conversation Class 'App\Nova\' Not Found

I got this weird problem in Nova and I can't find my error - used a couple of hours trying to find the problem - no success :(

Hope one of you might be able to point me in the right direction.

This is the error I receive:

Class 'App\Nova\' not found {"userId":1,"email":"........","exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Class 'App\Nova\' not found at /home/ec2-user/environment/vendor/laravel/nova/src/Fields/BelongsTo.php:108)

I can add records to the table just find, but I get the error when I tried to Attach the record to another "item/record" using BelongsTo. I got like 10 other BelongsTo on the same page, and they all works find, expect the last one (of cause).

Got this in my "main" model:

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

Where "S" is the name of the "child-model".

I can add records to the "child-model" just fine.

Got this in my "S" nova resource:

BelongsTo::make('S', 'S')
    ->hideFromIndex(),

I'm so confused, specially when the rest works just fine.

18 Oct
5 months ago

kgp43 left a reply on How To Flash Toastr Error Message If Validation Fails When Using FormRequest?

Directly in the controller? Like so:

´´´´ public function update(UpdateUser $request) { $user = Auth::user();

    $user->name = $request->input('name');
    $user->email = $request->input('email');
    $user->phone = $request->input('phone');
    
    $user->save();
  
    Toastr::success('Changes saved', 'Success');
  
    return back();
  
}

´´´´

05 Dec
1 year ago

kgp43 left a reply on If Statement Within Form Input Value

The PHP solution will fix it nicely I think :) Thanks for the help.

kgp43 started a new conversation If Statement Within Form Input Value

Hi,

How should I hand this? (see code below). No value is being displayed, i guess because the if statement is within the " ".

<input type="text" class="form-control" value="
@if($product->salesprice > 0)
    {{ round((($product->salesprice - (($price->amount*7.5)+($price->shipment_cost/$price->purchase_num)))/$product->salesprice)*100) }}
@endif
" disabled>
03 Dec
1 year ago

kgp43 left a reply on How To Just Update One "cell" In My Table Without Getting Fields_required?

Hmm... sometimes does not work - or so it seems. It blank all other values.

Guess I got to review some of the code to see if something else is causing it.

kgp43 left a reply on How To Just Update One "cell" In My Table Without Getting Fields_required?

Ahhh.... i think "sometimes" will fit perfectly :D Thanks !

kgp43 started a new conversation How To Just Update One "cell" In My Table Without Getting Fields_required?

Hi,

I hope one of you might be able to help me with a problem. How can I update just one "cell" in my database-table?

I have tried to use the update method in my controller, but getting fields_required for the other ... stuff, the values I dont wanna update.

I try to update the "salesprice" in my ProductController:

public function update(UpdateProduct $request, $id)
    {

        $product = Product::findOrFail($id);
        
        $product->category              = $request->input('category');
        $product->part_number           = $request->input('part_number');
        $product->productname           = $request->input('productname');
        $product->internal_notes        = $request->input('internal_notes');
        $product->description           = $request->input('description');
        $product->salesprice            = $request->input('salesprice');
        
        $product->save();
        
        Toastr::success('Ændringer gemt', 'Handling udført');

        return redirect()->route('product.show', $id);
    }

My UpdateProduct request:

public function rules()
    {
        
        return [
            'category'               => 'required|max:255',
            'part_number'            => 'required|max:20|unique:products',
            'productname'            => 'required|max:255',
            'description'            => '',
            'internal_notes'         => '',
            'salesprice'             => '',
        ];
        
    }

I get what is happening, or so I think: My submit form only include one input, the "salesprice", that leave the rest (category, part_number and productname) empty, and thats why I receive the error.

I'm not sure how to get around it though.

Hope so get some nice input from you smart people :)

18 Oct
1 year ago

kgp43 left a reply on Same View For Multiple Layouts

Thanks, will look into that :)

kgp43 started a new conversation Same View For Multiple Layouts

Hi,

I'm working on a configurator for a product, it let the user configure some product settings, that is saved into a db table.

I got a public and members area and would like to give access to the configurator view in both areas (public and member).

How can I do that? My view extends a layout.

@extends('layouts.cp.app')

In this example the view extends the main controlpanel/member layout. But I also have a layout of the public area. I guess the extends will look like this:

@extends('layouts.home.app')

How do you normally handle views, when they are used in different layouts? Do you copy the view and just have two? But then you need to edit two files... i dont like that.

31 Aug
1 year ago

kgp43 left a reply on Parse Error: Syntax Error, Unexpected '?' In ...

Fixed it :)

sudo a2dismod php5
sudo apt-get install libapache2-mod-php7.1
sudo a2enmod php7.1

My complete upgrade, just incase someone else needs it:

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get purge -y php*
sudo apt-get install -y php7.1 php7.1-cli php7.1-fpm

sudo a2dismod php5
sudo apt-get install libapache2-mod-php7.1
sudo a2enmod php7.1

kgp43 left a reply on Parse Error: Syntax Error, Unexpected '?' In ...

I did the following:

kgp43:~/workspace (master) $ sudo a2dismod php5.6
kgp43:~/workspace (master) $ sudo a2enmod php7.1
ERROR: Module php7.1 does not exist!

tried with 7.1.8 as well, but same result. php -v show 7.1.8 as installed

kgp43 left a reply on Parse Error: Syntax Error, Unexpected '?' In ...

I can't do that, receive same error :(

In routes/web.php:

Route::get('/phpinfo', function(){
    phpinfo();
});

kgp43 started a new conversation Parse Error: Syntax Error, Unexpected '?' In ...

Hi,

I receive this error after upgrading to 5.5:

Parse error: syntax error, unexpected '?' in /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 233

I have read that the error is caused by not running PHP 7. I'm already running PHP 7.1:

kgp43:~/workspace (master) $ php -v
PHP 7.1.8-2+ubuntu14.04.1+deb.sury.org+4 (cli) (built: Aug  4 2017 14:30:23) ( NTS )

What can cause this error? I cloned my old github.

27 Aug
1 year ago

kgp43 left a reply on Problems With Bootstrap

Think i has an error in my webpack.mix.js file:

mix.sass('resources/assets/sass/app.scss', 'public/css');

mix.styles([
        'node_modules/metismenu/dist/metisMenu.min.css'
    ], 'public/css/vendor.css', './');
  
mix.scripts([
        'node_modules/metismenu/dist/metisMenu.min.js',
        'resources/assets/js/app.js'
    ], 'public/js/app.js', './');

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

I tried to combine all my js into a single file (app.js), but it did it work - or so it seems.

This include jquery and bootstrap:

mix.js('resources/assets/js/app.js', 'public/js');
mix.sass('resources/assets/sass/app.scss', 'public/css');

mix.styles([
        'node_modules/metismenu/dist/metisMenu.min.css'
    ], 'public/css/vendor.css', './');
    
mix.scripts([
        'node_modules/metismenu/dist/metisMenu.min.js'
    ], 'public/js/vendor.js', './');

// Put version on css and js, but only when in production
if (mix.inProduction()) {
    mix.version();
}

kgp43 left a reply on Problems With Bootstrap

No bootstrap file in the same directory as the app.js file. bootstrap-sass folder exists in node_modules folder.

Have been running:

npm install

package.json:

{
  "private": true,
  "scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },
  "devDependencies": {
    "axios": "^0.16.2",
    "bootstrap-sass": "^3.3.7",
    "cross-env": "^5.0.1",
    "jquery": "^3.1.1",
    "laravel-mix": "^1.0",
    "lodash": "^4.17.4",
    "vue": "^2.1.10"
  },
  "dependencies": {
    "font-awesome": "^4.7.0",
    "metismenu": "^2.7.0"
  }
}

Do i still have to install bootstrap using npm? I thought that was already included by default?

26 Aug
1 year ago

kgp43 left a reply on Problems With Bootstrap

That did not work either. Think it need to include the entire folder - no ./bootstrap.js file exists.

ressources/assets/js/app.js:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

//require('./bootstrap');
require('./bootstrap.js')

window.Vue = require('vue');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app'
});

kgp43 started a new conversation Problems With Bootstrap

Hi,

I got problems with bootstrap. The JS part is not imported into my template (or so it seems.)

I can do 'class="btn btn-primary"' just fine, so seems the css is working fine. However, my menu are not working correctly (using default bootstrap one).

This is the end of my app.js file:

.....

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app'
});

https://hydraulikskolen-kgp43.c9users.io/js/app.js:

Looks like the bootstrap is not imported?

18 Aug
1 year ago

kgp43 left a reply on {{ $company->address }}, {{ $company->zipcode }} {{ $company->city }}

I guess everything is ok then, I just thought it was possible to short it.

Something like this

{{ $company->address,  $company->zipcode $company->city }}

kgp43 started a new conversation {{ $company->address }}, {{ $company->zipcode }} {{ $company->city }}

Hi,

I have read the documentation, but was not able to find any help regarding my issue.

How can I optimize this code, for blade? (to shorten it)

{{ $company->address }}, {{ $company->zipcode }} {{ $company->city }}

Or is that the only solution?

15 Aug
1 year ago

kgp43 left a reply on Add Unique Company To Table And Make User-relation In Pivot Table

I get the error because of the rules i made, which is correct. But that's not really the functionality I want - not sure what to change.

public function rules()
    {
        
        return [
            'cvr'     => 'required|numeric|digits:8|unique:companies,reg',
        ];
        
    }

kgp43 started a new conversation Add Unique Company To Table And Make User-relation In Pivot Table

Hi,

I'm not sure how to solve this problem:

I got 3 tables:

  • users
  • companies
  • company_user

A user can add a new company to the database. Each company got a CVRnumber (reg.number) that has to be unique. A relation is added to the pivot table.

The problem is when adding a company to the table that already exists. I receive this error: "the cvr has already been taken". What I would like, is to skip adding the company, since it already exists, and just add the relation to the pivot table.

How do you guys suggest I handle that part?

Some of my code listed below:

Store method in my controller:

$company->owner_id = $user->id;
            $company->reg = $cvr;
            $company->name = $api['name'];
            $company->address = $api['address'];
            $company->zipcode = $api['zipcode'];
            $company->city = $api['city'];
            $company->country = 'dk';
            $company->phone = $api['phone'];
            
            $company->save();
            
            # Add to pivot table
            $company->users()->attach($user);
            
            # Status message
            Toastr::success($company->name.' blev tilføjet din konto', 'Succes');
            
            return redirect()->route('company.index');

FormRequest:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Brian2694\Toastr\Facades\Toastr;

use Auth;

class CreateCompany extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        
        return [
            'cvr'     => 'required|numeric|digits:8|unique:companies,reg',
        ];
        
    }
    
    # Error messages
    protected function formatErrors(Validator $validator)
    {
        
        $messages = $validator->messages();

        foreach ($messages->all() as $message)
        {
            Toastr::error($message, 'Failed', ['timeOut' => 10000]);
        }

        return $validator->errors()->all();
    }
    
}

, Kenneth

14 Aug
1 year ago

kgp43 left a reply on Change Request Input Before Validation

Thomaskim: Is it ok to use middleware for this kind of use? Or is there a better/smarter way? This was my first one :)

kgp43 left a reply on Change Request Input Before Validation

That worked, thanks :D

Summary:

Middleware:

<?php

namespace App\Http\Middleware;

use Closure;

class CVRNumber
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $request->merge([
            'cvr' => preg_replace('/\s+/', '', $request->cvr)
        ]);
        
        return $next($request);
        
    }

}

store method in my controller:

$this->middleware(CVRNumber::class);

Kernel:

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\TrimStrings::class,
        \App\Http\Middleware\CVRNumber::class,
    ];

kgp43 left a reply on Change Request Input Before Validation

Hmm... adding it to kernel and I get this error:

 FatalErrorException
Can't use method return value in write context
in CVRNumber.php (line 19)

Kernel:

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\TrimStrings::class,
        \App\Http\Middleware\CVRNumber::class,
    ];

CVRNumber.php is my middleware.

Is it considered bad practice, to use middleware for this type of thing?

kgp43 started a new conversation Change Request Input Before Validation

Hi,

I think I might do this wrong. I would like to remove all white spaces from my input request (only 1 field).

I created a middleware, probably stupid - don't know.

<?php

namespace App\Http\Middleware;

use Closure;

class CVRNumber
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        
        $request['cvr'] = str_replace(' ', '', $request['cvr']);
        
        return $next($request);
    }

}

And then added this to my controller:

public function store(CreateCompany $request)
    {
        
        $this->middleware(CVRNumber::class);
        .....

Not sure if that is the right way or not. It does not work though, no errors or anything - whitespaces are simply not removed before validation kicks in.

Any suggestions are welcome :)

kgp43 started a new conversation How To Verify Pivot Table Relations?

Hi,

First a little explanation about my app:

It's an ordering system for a company (primary B2B sales).

Users sign up with a personal account, since they are allowed to purchase goods for personal use and not only B2B. They can associate their account, with one or more companies, or keep it solely as personal account (B2C). Users can, after adding a business to their account, purchase goods for the company they represents - goods are shipped to the company. We phone the company upon first order, to verify the connection between our user and the company.

I got a pivot table named company_user. The pivot table is used to "attach" a connection between the user and the company (belongsToMany) - this (code) works great.

My question is: How can I add some kind of verification to the pivot table? How am I supposed to handle that part? Just add a 3rd column to the existing pivot table named "verified"? But...

What is the best way to handle this? How would you do it?

, Kenneth

13 Aug
1 year ago

kgp43 left a reply on How To Remove Empty Spaces From String When Using FormRequest?

I just read this topic: https://laravel-news.com/laravel-5-4-middleware

Adding TrimStrings middreware to App/Kernel.php solved my problem. All form data is now automatically trimmed :D

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\TrimStrings::class,

kgp43 started a new conversation How To Remove Empty Spaces From String When Using FormRequest?

Hi,

I got this simple FormRequest, that I use form input validation:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Brian2694\Toastr\Facades\Toastr;

use Auth;

class CreateCompany extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        
        return [
            'cvr'     => 'required|digits:8|unique:companies,reg',
        ];
        
    }
    
    # Error messages
    protected function formatErrors(Validator $validator)
    {
        
        $messages = $validator->messages();

        foreach ($messages->all() as $message)
        {
            Toastr::error($message, 'Failed', ['timeOut' => 10000]);
        }

        return $validator->errors()->all();
    }
    
}

I would like to remove all empty spaces before the validation. Exactly 8 digits are allowed.

The verification work great, when using exactly 8 digits (as planned). 8 digits followed by a space will fail though. Normally I would just do trim(), but not sure how to do that here :(

Hope one of you might be able to help me :)

, Kenneth

kgp43 left a reply on What Type Of Relations Should I Use?

Thanks and sorry for the late reply.

09 Aug
1 year ago

kgp43 left a reply on What Type Of Relations Should I Use?

Most of those topics that I read is 2 tables + 1 pivot table. But I need 3 tables + 1 pivot table, correct?

users companies notifications pivot

notifications table contain all the different type of notifications, such as: "newsletter", "sales", "new_products", "price_changes" etc.

Or should I add the notification type to the pivot table and remove the notifications table? A column named ... type? Containing the type of notification (newsletter, sales... etc).

kgp43 left a reply on What Type Of Relations Should I Use?

No, I did not try to search for "tree table".

I thought I had to search using an advanced word that I dont know... thats why I created this topic. To learn the name of the relation :)

kgp43 started a new conversation What Type Of Relations Should I Use?

Hi,

I'm not sure if "relations" is the right word, but let me try explain what I need to do.

I have these 3 tables that is related to my problem: companies, users and notifications.

A user signup to my app and can use it for different tasks. One of those tasks, are notifications. The user can choose what type of notifications we would like to receive from each company (if any), such as: new product releases, sales, newsletter etc. A user can set individual notifications-settings for each company that he is associated with. He might want to be notified when "Company A" has new product releases and sales, but he does not want the newsletter. Another user might have other settings.

How should I handle this and what is this type of.... method/function.... called? I was planning to add all the different "relations" to the notifications table, but not sure if that is a good idea or not.

Any suggestions how to keep track of all this?

04 Aug
1 year ago

kgp43 left a reply on How To Flash Toastr Error Message If Validation Fails When Using FormRequest?

This seems to work.

Is there a smarter way to post the error messages? Or can this be optimized in any way?

    protected function formatErrors(Validator $validator)
    {
        
        $messages = $validator->messages();

        foreach ($messages->all('<li>:message</li>') as $message)
        {
            Toastr::error($message, 'failed');
        }

        return $validator->errors()->all();
    }

kgp43 left a reply on How To Flash Toastr Error Message If Validation Fails When Using FormRequest?

Do you know how to get the error messages?