ekrist1

ekrist1

Member Since 2 Years Ago

Experience Points 17,030
Experience Level 4

2,970 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 149
Lessons
Completed
Best Reply Awards 2
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.

15 Mar
2 months ago

ekrist1 left a reply on Vue.js | Get Data From CKeditor And Saving It To The Database

You will need to use the v-model directive like this:

<input v-model="firstName" placeholder="Firstname">

Vue form input binding

ekrist1 left a reply on Best Way To Avoid Repeating Code In Controler

A good why to solve this is to extract the filtering logic. Take a look at the let's build a forum git repository. If you have a subscription here at Laracast you could also watch the serie lets build a forum. You could also use this [Spatie package] (https://github.com/spatie/laravel-query-builder)

ekrist1 left a reply on How To Make A Dynamic Category Tree In The Route?

hi

From Laravel documentation

You may define as many route parameters as required by your route:

Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});

Instead of nesting the routes this, it might be better to use fewer levels. I can't see the benefit of using more then 2-3 route parameters.

domain.test/main-category/slug

In your blade / vue-component you could still build a breadcrumb which reflects the desired category level.

ekrist1 left a reply on Form Validation With Vue Component And Vee-validate

Is there any error messages in the console? Can't see why this isn't working. I find it easier to use server side validation using this package: backend validation

ekrist1 left a reply on Vue.js | Get Data From CKeditor And Saving It To The Database

You need to post the data to the server using axios / fetch. You can't use a normal form post.

Example:

´´´ axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ´´´

16 Feb
3 months ago

ekrist1 left a reply on Using Queries In Blade Templates

Is there any reason why you are trying to fetch records from the blade template and not passing the data from your controller? If you have configured your relationship correctly you could loop through your posts like this:

@foreach ($postcat->posts as $post)
{{ $post->created_date }}
@endforeach

ekrist1 left a reply on Attaching Multiple Image To Form

hi.

Here is my Vue method which I use to upload multiple files (I´m using loadash to loop through the files). You need to add "multiple" to your input field.

''' attachDocuments: function(e) { this.fileNames = [] this.form.attachments = e.target.files || e.dataTransfer.files

        _.forEach(this.form.attachments, (file) => {
            this.fileNames.push(file.name)
            if(file.size > 15728640) {
                alert('Filen er for stor. Maks størrelse er 15MB!')
                this.form.attachments = []
                this.fileNames = []
            }
        })
        this.submitForm()
    },
    submitForm() {
        this.loading = true
        this.form[this.method](this.action)
            .then(response => {
                this.loading = false
                window.location.href = response.redirect
            })
            .catch(error => {
                this.loading = false
                if (error.response.status === 401) {
                    this.showmodal('image-auth-error')
                }
                this.displayErrorMessage(this.form.errors.all())
            })
    },

'''

input

''' <input class="cursor-pointer absolute block opacity-0 pin-r pin-t" type="file" name="file" id="file" @change="attachDocuments" multiple accept='image/*'> '''

04 Feb
3 months ago

ekrist1 left a reply on Laravel 5.7, Vue.js And Zizaco/entrust

You can't trust client-side validation alone, so you need to add serverside validation to your POST route (like you normally protect your Laravel routes). If you are sending JSON data to your Component, you need to send only the data which the current user is authorized to see. It's not safe to use Client-script to hide information.

23 Jan
4 months ago

ekrist1 left a reply on E-commerce

Take a look at Codecource. It's not a finished package, but it looks really promising

20 Jan
4 months ago

ekrist1 left a reply on Vue Momentjs Update Relative Time In Real Time

I guess you could rewrite this jQuery code shared on Jsfiddle to vue: dynamic date/time

ekrist1 left a reply on Laravel 5.7 Vue Js .default

Take a look at the Laravel Mix upgrade documentation

As part of the vue-loader 15 updates, if your code uses the CommonJS syntax for importing EcmaScript modules, you'll need to append .default. Switching to EcmaScript imports is the recommended option.

ekrist1 left a reply on Vue And Paginate

You don't have any fetchComments method in your Vue-file. I made a pagination component a while ago which works for me: gist - you will also find a tutorial how to make a pagination here at Laracast.

08 Oct
7 months ago

ekrist1 left a reply on Hiding Vue Component From All Users Besides Owner

Maybe you could solve it passing props to your vue-component:

<vue-component :isOwner="{{ Auth::check() ? 'true' : 'false' }}"

In your vue-file you could then use a v-if to check if the user is an owner. You also need to add necessary server-side validation.

07 Oct
7 months ago

ekrist1 left a reply on Something Like Middleware, But After The Controller Does Its Thing

Not sure what you are trying to solve, but there are three options you might want to consider:

  1. Fire an event: Laravel Events
  2. Dispatch a job: Queues
  3. Model events

ekrist1 left a reply on Jquery To Vue

I guess you are using Laravel? You need to add your Vue component to your app.js.

app.js ...

Vue.component('flash', require('./components/utilities/flash.vue'));

in your blade.php file:

<flash></flash>

You should try to make reusable components, but some times a component is on only one page.

You should also check out Vuecomponents - there are a lot of great components out there.

ekrist1 left a reply on Re-use The Same Search Components Multiple Times

It depends if you like to make the search in the child component or pass the input to the parent. If you like to emit data from the AppInput component you could do like this:

AppInput.vue

<input :id="name" :name="name" type="text" @input="$emit('input', $event.target.value)"

ekrist1 left a reply on Re-use The Same Search Components Multiple Times

I think the best way to solve this is to create resuable child components. Use props to pass data to the child component and use an event hub if you need to pass data back to the parent component.

Take a look at the laracast toturial: Laracast Vue

You could call the child component this way:

<AppInput name="search" type="text" placeholder="search article" />
<AppInput name="search2" type="text" placeholder="search posts" />

In your parent component

import AppInput from '/your/patch'

export default {
components: { AppInput },

.....
}
18 Apr
1 year ago

ekrist1 left a reply on Is Encrypt() Really Secure?

As far as my knowledge the encrypt&decrypt is very safe. However, in PHP 7.2 you could use the new Sodium encryption. I just made a Sodium service provider in on of my project, and are storing a encryption key for each tenant. The encryption service looks something like this:

<?php

namespace App\Services;

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Contracts\Encryption\EncryptException;

/**
 * Encrypt a message
 *
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 */

class SodiumEncrypter
{
    protected $key;

    public function __construct($key)
    {
        $this->key = $key;
    }

    public function safeEncrypt($message)
    {
        $nonce = random_bytes(
            SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
        );

        $cipher = base64_encode(
            $nonce .
            sodium_crypto_secretbox(
                $message,
                $nonce,
                $this->key
            )
        );

        return $cipher;
    }

    /**
     * Decrypt a message
     *
     * @param string $encrypted - message encrypted with safeEncrypt()
     * @param string $key - encryption key
     * @return string
     */
    public function safeDecrypt($encrypted)
    {
        $decoded = base64_decode($encrypted);
        if ($decoded === false) {
            throw new DecryptException('Could not decrypt the data.');
        }
        if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
            throw new DecryptException('Could not decrypt the data, the message was truncated');
        }
        $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
        $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

        $plain = sodium_crypto_secretbox_open(
            $ciphertext,
            $nonce,
            $this->key
        );
        if ($plain === false) {
            throw new DecryptException('the message was tampered with in transit.');
        }
        return $plain;
    }
}
13 Apr
1 year ago

ekrist1 started a new conversation Eventing And HTTP Reponses

If you are using the Laravel Events to send an SMS to a recipient you will not be able to return any values since the Event classes returns void. How do you return a HTTP api error response? Lets say that you don't have any creditt left at on your Nexmo account, how do you notify the user when using Laravel Events?

13 Dec
1 year ago

ekrist1 left a reply on Is It Worth Javascriptifying The Front-end?

@thebigk I think it depands on what you are building. If you are going to load different data inside tabs or accordions, i would go with Ajax/Axios to load/post the data, but for simple CRUD operations you won't necessarily need any JS.

I recently used Laravel and Vue to make a simple comperisan tool: [Heisann.no] (https://heisann.no/calc/mobile) and are using Vue for filtering data, and I'm passing data from the backend as Props to Vue.

I'm going to add a simple review rating system as well later and think i'll use Vue for the reactivity part, but use Blade to post the data to the server.

ekrist1 left a reply on Is It Worth Javascriptifying The Front-end?

You will need to duplicate some of the functionality offered by blade (such as pagination and checking permission), but using Vue together with Blade gives you more flexibility to create great user interfaces. In my experience Vue and Blade plays well together. By using Vue you could easily replace jQuery code as well.

There are several great components which will make your life easier, such as: [Spatie form validation] (https://github.com/spatie/form-backend-validation)

It is also possible to use Vue without Blade templates (if you like to build a SPA-application). So from my point of view, go with Blade and use reusable Vue components to add reactivity.

03 Dec
1 year ago

ekrist1 left a reply on Sort V-for List With Calculated Field

@joshuafranks the data comes from Laravel, but the sorting "must" be done at the frontend due to user input (its a calculator): https://tools.altonline.no/calc/power

ekrist1 left a reply on Sort V-for List With Calculated Field

@bobbybouwmann thanks :) this will solve my issue. I'm using Laravel as backend, but with your solution I don't need to post any data back to the server.

ekrist1 started a new conversation Sort V-for List With Calculated Field

I have a v-for loop which runs a method to calculate a price for each vendor. Is there any ways to sort the list according to low-high prices using computed properties?

<div class="mt-4 mb-4 mr-3 border-2 border-grey p-4 bg-grey-lightest sm:w-full md:w-2/5" v-for="vendor in vendors" :key="vendor.id">
<h3{{ vendor.company }}</h3>
 <p class="text-darker">Agreementname: {{ vendor.agreement_type }}</p>
<p class="text-darker">Vendor price: {{ vendor.price }} kr</p>
<p class="text-darker">Fee: {{ vendor.fee }}</p>
<powercontact :vendordescription="vendor.description"></powercontact>
>div class="flex items-center bg-orange text-white text-sm font-bold px-4 py-3 mt-6" role="alert">
<p> Price per month {{ calculatePrice(vendor.fee, vendor.price, vendor.invoice) | roundCalculatedPrice }},-</p>
</div>
</div>
18 Aug
1 year ago

ekrist1 started a new conversation Vue Component Inside A Foreach Loop

I´m building a multipage application and in some of my views I need some reactivity. One option I have thought about is to create a Vue component for each blade view, but it feels wrong.

If I have a blade view with a foreach loop of thousands of contacts (with pagination), is it considered a bad practise to add a component within the foreach loop?

@foreach($contacts as $contact) {{ display something }} @endforeach

I have started to understand and use some of the power with Vue and are using it for some part of my application, but sometimes it feels like going all in for Vue + Vue Routing or to use traditional blade with some jQuery scripts.

For instance:

Sometimes when you only need some reactivity to only one page and don´t need a reusable component it feel a bit wrong to create a global component.

09 Aug
1 year ago

ekrist1 started a new conversation Shared State With Vuejs And Laravel 5.5

It took me some time to figure out how I could share data between vue components with Laravel 5.5.

First you will need to upgrade to the latest version with the command npm install vue ( “two-way binding” for a prop only works with vue 2.3.0+)

  1. Add a data object and properties in your app.js file
const app = new Vue({
    el: '#app',
    data: {
        store: {
            showpagecontent: true
        }
    }
});
  1. Add v-bind.sync to your vue component in your blade file(s)
<Globalsearch v-bind.sync="store"></Globalsearch>
<start v-bind.sync="store"></start>
  1. Add the prop to your vue files:
props: ['showpagecontent'],
  1. Change the value globally with:
this.$emit('update:showpagecontent', false);

In this example I´m hiding some elements on the page when doing a search.

Take a look at this changelog from vue

26 May
1 year ago

ekrist1 left a reply on Update A JSON Key Stored In A JSON Type Field

@Boris This is how i do it when i'm storing and updating data to the JSON column :) With the raw query i'm able to delete a single key from all contacts rows.

The video was useful - thanks for sharing.

ekrist1 left a reply on Update A JSON Key Stored In A JSON Type Field

It took me some time to find the answer:

App\Contact::query()->update(['additional' => DB::raw('JSON_REMOVE(additional , \'$."3"\')')]);

This query is useful if you like to delete a JSON key from a table.

25 May
1 year ago

ekrist1 left a reply on Update A JSON Key Stored In A JSON Type Field

@Borisu I solved the problem using the ID instead of the name. The next problem is to delete key from the JSON column. The query statement I´m using is: UPDATE `contact SET `additiona = JSON_REMOVE(`additiona , '$."3"'), but I can´t figure out how to run this as a raw query in larval.

ekrist1 started a new conversation Update A JSON Key Stored In A JSON Type Field

In my application I have added functionality to let users add their own fields, and I´m storing this fields in a JSON column in MySQL. I would like to allow the users to edit the field name (eg. rename Power to Voltage). I haven´t found any way to perform this operation.

Additional JSON column: {"Watt": 10w, "Power": 220}

Any clues how to perform a key update action using Eloquent or raw sql?

01 May
2 years ago

ekrist1 left a reply on Displaying Related Data - Why Is It Working?

@tykus Thanks for the explanation.

I´m viewing a singel contact. Just debugged the SQL query, and as you say I´m avoiding the N+1 problem.

ekrist1 started a new conversation Displaying Related Data - Why Is It Working?

I have defined a hasMany and belongsTo relationship. In my contact table I store the ID of the industry type (single id). If I eager load the relationship then I could use:

Industry: {{ $contact->lookup_industry_type->industry }} Output: Automobile Service

If I don´t eager load the relationship, then I´m successfully able to use this code in my blade file:

Industry: {{ $contact->lookup_industry_type['industry'] }} Output: Automobile Service

It seems like it lookup the industry field, but I haven´t found any documentation describing this behaviour. Is this an appropriate way to display related data which only stores one value?

26 Mar
2 years ago

ekrist1 left a reply on Eloquent Query With Pagination

added:

´´´ $contacts->appends(Request()->all())->links(); ´´´

seems to work

ekrist1 started a new conversation Eloquent Query With Pagination

I have implementet query string filtering using the laracast session (https://laracasts.com/series/eloquent-techniques/episodes/4).

I´m able to add pagination to the result, but how can I add pagination together with the query string? Now the next_url shows http://laravel.dev/api/getcontacts?page=2 regardless your have a query string like: http://laravel.dev/api/getcontacts?keyword=t

Getcontact controller: ´´´ $contacts = Contact::filter($filters)->paginate(2);

    return response()->json($contacts);

´´´ Query string code: https://github.com/laracasts/Dedicated-Query-String-Filtering

22 Mar
2 years ago

ekrist1 left a reply on Get A Url Parameter Blade Issue

Fixed: ´´´

        <div class="input-group">
            <input type="text" name="city" id="city">
            <button type="submit">søk</button>
        </div>

´´´

21 Mar
2 years ago

ekrist1 started a new conversation Get A Url Parameter Blade Issue

I´m trying to get url parameters from the blade view, and it works the first request, but the url parameters has a wrong format doing the second request. Any ideas why this happens?

Blade view: '''

søk '''

First request (works): http://laravel.dev/contacts/?city=Oslo

When i´m doing the second search, I expect the query string to be Contacts/?xxx but it adds Oslo to the url, and the request fails.

--> http://laravel.dev/contacts/Oslo?city=Bergen

21 Sep
2 years ago

ekrist1 started a new conversation Loop Trough A Collection

I´m trying to loop trough a collection, but i keep hitting the error: Undefined property: Illuminate\Database\Eloquent\Collection::$leaguestatistics (View: /Applications/MAMP/htdocs/sport/resources/views/frontend/seasontable.blade.php)

If i return the collection it has the right data: [{"id":1,"created_at":"2016-09-18 00:00:00","updated_at":"2016-09-18 00:00:00","deleted_at":null,"leaguename":"Tippeligaen 2016","slug":"tippeligaen-2016","datafrom":"2015-09-18","datoto":"2016-09-18","sortkey":1,"description":"Norges eneste","leaguestatistics":[{"id":1,"created_at":"2016-09-18 00:00:00","updated_at":"2016-09-18 00:00:00","deleted_at":null,"wongames":10,"lostgames":10,"tiegames":10,"playedgames":10,"goalswon":10,"goalslost":8,"rank":1,"league_id":1,"team_id":1},{"id":2,"created_at":"2016-09-18 00:00:00","updated_at":"2016-09-18 00:00:00","deleted_at":null,"wongames":5,"lostgames":5,"tiegames":5,"playedgames":5,"goalswon":5,"goalslost":2,"rank":2,"league_id":1,"team_id":2}]}]

Any idees how to loop trough the secound array?

Model: ''' public function leaguestatistics() { return $this->hasMany('App\Stats', 'league_id'); }

} ''' Controller: ''' public function show($slug) { $leaguestats = League::where('slug', $slug)->with('leaguestatistics')->get(); //return $leaguestats; return view ('frontend.seasontable', compact('leaguestats')); } } ''' View: ''' @foreach ($leaguestats as $leaguestat) @foreach ($leaguestats->leaguestatistics as $teamestat) -->code @endforeach @endforeach '''

13 Sep
2 years ago

ekrist1 started a new conversation Retrieve Related Records Based On Slug

I have two tables. One division table and one seasontable. The seasontable records is related to the divisiontable (hasOne). I’m trying to use a slug to only show seasontable records equal to the slug field on the divsiontable.

I´m able to retrieve all related tables, but i can´t find a way to only retrieve a selection based on the url slug. Any ideas how to use eloquent to achieve this?

Model: public function show($slugdivision, Request $reguest) { //$seasontables = Seasontable::where('Seasontable->seasondivision->slugdivision', $slugdivision)->get(); $seasontables = Seasontable::with('seasondivision')->get(); return $seasontables; }

Result: [{"id":1,"wongames":5,"lostgames":3,"tiegames":2,"playedgames":10,"pointsgames":32,"goalswon":9,"goalslost":7,"rank":3,"teams_id":1,"years_id":1,"division_id":1,"created_at":"2016-09-11 00:00:00","updated_at":"2016-09-11 00:00:00","seasondivision":{"id":1,"divisionname":"tippeligaen","divisiondescription":"lorem","created_at":"2016-09-06 00:00:00","updated_at":"2016-09-05 00:00:00","slugdivision":"tippeligan"}},

{"id":2,"wongames":10,"lostgames":10,"tiegames":3,"playedgames":13,"pointsgames":44,"goalswon":3,"goalslost":4,"rank":4,"teams_id":2,"years_id":1,"division_id":1,"created_at":"2016-09-12 00:00:00","updated_at":"2016-09-12 00:00:00","seasondivision":{"id":1,"divisionname":"tippeligaen","divisiondescription":"lorem","created_at":"2016-09-06 00:00:00","updated_at":"2016-09-05 00:00:00","slugdivision":"tippeligan"}}]

04 Jul
2 years ago

ekrist1 started a new conversation Passing Data To Views

Hi.

I´m new to Lavarel, so I wonder if this is the correct way to do this.

I have some statistics data which i would like to pass to several views. In my accountcontroller today, i have an array that fetch data from my customer table: $accounts = account::all();

I would like to output the number of accounts (customers) to several of my views by using:

Will it be the right way of doing this to move the $accounts = account::all(); to a view composer? https://scotch.io/tutorials/sharing-data-between-views-using-laravel-view-composers https://laracasts.com/series/laravel-5-fundamentals/episodes/4

Another question: If i´m going to add some business logic (i.e format or change some data in on of my array´s), will the right way of doing this using Service Providers?