nikocraft

nikocraft

Member Since 2 Years Ago

Malmö

Experience Points 27,270
Experience Level 6

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

18 Apr
3 days ago

nikocraft started a new conversation How To Process My Array To Be Associative On First Two Levels And On Third To Have Simple Value

I'm trying to construct an array where there only strings and the array would look like this key->key->value

To explain it I attached two screenshots below.

I start with this: enter image description here

After my code below I'm 90% there, yet there is an array in value on the third level instead of simple value.

enter image description here

Here is some code:

        $theme = ThemeHandler::with('sections.settings')->find($activeTheme);
        $themeSettings = $theme->sections;
        $themeSettings = collect($themeSettings->toArray());

        // dd($themeSettings);

        $themeSections = [];
        foreach ($themeSettings as $key => $value) {
            $settings = collect($value['settings']);
            $settings = $settings->mapToGroups(function ($item) {
                return [$item['key'] => $item['value']];
            });
            $themeSections[$value['key']] = $settings->toArray(); 
        }
        dd($themeSections);

I would like to end up with this structure

key->key->value

and not

key->key->single_element_array->value

I'm not sure how I end up with an array at the bottom level when I do this

    return [$item['key'] => $item['value']];

inside the mapToGroups, which is a function found here: https://laravel.com/docs/5.8/collections#method-maptogroups

Maybe I misunderstand how mapToGroups work. Anybody has an idea how to get key->key->value structure output?

17 Apr
4 days ago

nikocraft started a new conversation Laravel's Polymorphic Relationships Performance Vs Normal Relationships

When it comes to polymorphic relationships are there any hits on performance vs. using standard relationships. Or are polymorphic relationships equally good? I have a case where I can merge 3 tables into one and make the relationships polymorphic instead of normal relationships.

How often does the rest of you like to use polymorphic relationships, as soon as the opportunity presents itself or do you try to avoid them?

nikocraft started a new conversation UpdateOrCreate A Row And Skip A Column Update If We Got Null, Keep The Original Value

Is it possible to do this? I got a function that takes these parameters.

Upon the first time it's called it will create all possible settings that are defined by a JSON file and save them to the database. Important column here is meta, which is string column but saves JSON values.

Once data has been saved to the database, meta values do not need to be modified anymore and we do not need to send them from UI back to the server when we want to save. What will happen bellow if $meta is null? It will set the meta column to null as well. Is there an elegant way to tell laravel not to update the column if the value that comes in is null, so it keeps the old values?

´´´ public function saveSetting($section, $parent, $key, $value, $type = 'string', $meta) { if(is_array($value) || is_object($value)) { $type = 'json'; $value = json_encode($value); }

    $setting = $this->settings()->updateOrCreate(
        ['theme_id' => $this->id, 'section' => $section, 'key' => $key],
        ['section' => $section, 'parent_id' => $parent, 'key' => $key, 'value' => $value, 'type' => $type, 'meta' => $meta]
    );

    return $setting;
}

´´´

Right now only solution I think of is where I use an if to see if meta is set, something like this:

´´´ public function saveSetting($section, $parent, $key, $value, $type = 'string', $meta) { if(is_array($value) || is_object($value)) { $type = 'json'; $value = json_encode($value); }

    if(isset($meta)) {
        $setting = $this->settings()->updateOrCreate(
            ['theme_id' => $this->id, 'section' => $section, 'key' => $key],
            ['section' => $section, 'parent_id' => $parent, 'key' => $key, 'value' => $value, 'type' => $type, 'meta' => $meta]
        );
    } else {
        $setting = $this->settings()->updateOrCreate(
            ['theme_id' => $this->id, 'section' => $section, 'key' => $key],
            ['section' => $section, 'parent_id' => $parent, 'key' => $key, 'value' => $value, 'type' => $type]
        );
    }

    return $setting;
}

´´´

Is there any better way to skip updating meta?

This is how code that calls saveSetting function looks like:

´´´ foreach ($section as $key => $setting) { $theme->saveSetting($sectionKey, $sectionSetting->id, $key, $setting['value'], $setting['type'], null); } ´´´

meta is set to null, since we already have meta in the database and our UI does not need to send it to the server upon user pressing save. We only send to server data user actually can modify.

08 Jan
3 months ago

nikocraft left a reply on Suggest Me A License For This CMS I Built Over Last 2 Years That I Plan To Open Source

@CLICK - I do not worry at all, but If I say I want to open source the CMS and build a community around it and perhaps some devs want to contribute back, you expect me to release without a proper open source license? Nobody would contribute without a good open source license. I do not worry about those who would steal, but If I do choose to open source it, I wanted to hear my fellow laravel devs opinions on what they think would be a good license to pick :)

If 1% of bad actors steal the code, repackage it community would found out and if they had any reputations it would go to toilets, internet is a small world today, professionals will not do that kind of stuff, maybe teenagers :)

nikocraft left a reply on Suggest Me A License For This CMS I Built Over Last 2 Years That I Plan To Open Source

thanks @d9705996 that's good feedback on your side. You are right, perhaps I could release with custom license and not go open source at this time and if I change my mind later down the road I could open source it.

I am 100% aware of if I go open source people can soft clone it on the github, that is ok as long as they respect the licese, if they steal some code and put it in their project and their project does not take off, they would be secure, but if it takes off they could be in trouble if found out.

I would like to believe that 99% would not do dirty tricks like that, but there is always that 1% that would take the code and not give you any credit and just plugit into their project

nikocraft left a reply on Suggest Me A License For This CMS I Built Over Last 2 Years That I Plan To Open Source

@d9705996

how do you feel about:

https://choosealicense.com/licenses/mpl-2.0/

or

https://choosealicense.com/licenses/lgpl-3.0/

do you see any weaknesses considering what I mentioned above that I want third party devs to be able to put their own license on extensions/plugins and themes.

nikocraft left a reply on Suggest Me A License For This CMS I Built Over Last 2 Years That I Plan To Open Source

@d9705996 why do you think this would be a big problem?

A limitation of this license for developers is that it requires you to add prominent notifications of any changes you make to a file.

Does it mean even if you add smallest of change, like change a single row you have to add that to the top of the file and register it each time you do small changes?

nikocraft left a reply on Suggest Me A License For This CMS I Built Over Last 2 Years That I Plan To Open Source

@MARTINBEAN - @martinbean thanks for your input, I don't worry about that at all. I just worry to find a perfect license. I got a great feedback from people who have seen it in action and from strangers who have seen it just on video. Do you have any real feedback for me or not?

nikocraft left a reply on Suggest Me A License For This CMS I Built Over Last 2 Years That I Plan To Open Source

@danieloplata problem with any GPLvX license is that all works that base on the software licensed with GPLvX are supposed to be also realeased as GPLvX

For example in WP community there is "grey legal area" where when you release a theme or a plugin that interacts with the CMS relased on for example GPLv2 license now you cant release a plugin under another license and that means if you want to sell it you are good to do that but if someone buys it from you and then gives it away for free you cant legaly do anything, since they are right. If you doubt what I mean just read this:

https://wordpress.org/about/license/

Specifically:

There is some legal grey area regarding what is considered a derivative work, but we feel strongly that plugins and themes are derivative work and thus inherit the GPL license. If you disagree, you might want to consider a non-GPL platform such as Serendipity (BSD license) or Habari (Apache license) instead.

And also a good read: https://gschoppe.com/wordpress/plugins-and-themes-open-source/

I want third party developers who develop themes and plugins to be able to give them under any license.

It's really hard to pick a license. If I pick MIT it's too permissive and If I pick GPLv2 it's too restrictive.

nikocraft left a reply on Suggest Me A License For This CMS I Built Over Last 2 Years That I Plan To Open Source

Hi @d9705996 and thanks for being the first to post.

I know about https://choosealicense.com

I wanted to get the laracats and laravel communities opinion on what they personally would choose if they had the same objectives as I mentioned in my post above.

nikocraft started a new conversation Suggest Me A License For This CMS I Built Over Last 2 Years That I Plan To Open Source

I've spent last two years building this Laravel + Vuejs powered CMS. I invested a lot of time and effort to build it. I plan to release it within the next 2-3 months.

Take a second a check a quick preview here: https://www.youtube.com/watch?v=pCjZpwH88Z0

IMAGE ALT TEXT

I would like to use open source license but I am kinda stuck right now on which one.

MIT is out of the question since it is too permissive and would give the right to anyone to just do what they please. I spent two years and hired another developer to help me get this far, my goal is to build a big community around it and would like contributions to come in from others in the community as well, with MIT and anyone doing what they want with it it may be hard to grow big community that can help better the software.

I was leaning towards PGLv2 but I noticed how much confusing it gets when third-party developers release themes or plugins and other people who buy their stuff choose to release it for free because they feel themes+plugins fall under GPLv2 as well. https://gschoppe.com/wordpress/plugins-and-themes-open-source/

WP itself has a very strong opinion on this here: https://wordpress.org/about/license/

So with MIT and GPLv2 out of the way, what another license could I use that is more relaxed when it comes to derivative works like plugins or themes but also protects any copyrights I've released the CMS with.

Do we have anyone visiting forums here that could give me some advice?

29 Oct
5 months ago

nikocraft left a reply on Is Naming Columns With Reserved Words Problematic?

@jlrdw you make no sense

So your custom framework does escape it, but Laravel does not then you say check the vendor you bet Taylor does escape it.

What did you really mean :)

nikocraft started a new conversation Is Naming Columns With Reserved Words Problematic?

For example, in pure PHP this guy has a problem because he has a column named key

https://stackoverflow.com/questions/23446377/syntax-error-due-to-using-a-reserved-word-as-a-table-or-column-name-in-mysql

However, I am using both key and value for column names in my application which I have developed for 15 months now and never did I have any single problem with these names. I probably use some more reserved words.

Is Laravel escaping them with backtick as the answer suggests one should do manually? If Laravel is not escaping them how come I can use any name for the column in a table and not get problems like in the link above?

27 Oct
5 months ago

nikocraft left a reply on Can't Use OR In Blade Template

thanks guys, that was fast! :)

nikocraft started a new conversation Can't Use OR In Blade Template

When I am developing locally on win10 php7.2 nginx expression like this works just fine

    <div class="{{ $menuclass or 'menu'}}">

which gives

    <div class="menu">

but as soon as I deploy it via laravel forge to ubuntu machine it fails to work and I get this

    <div class="1">

It seems that instead of doing this:

    isset($menuclass ) ? $menuclass : 'menu'

it just returns 1

Any ideas why?

This feature was blogged about here: https://laravel-news.com/blade-or-operator

Has it been deprecated in later versions of laravel?

28 Sep
6 months ago

nikocraft left a reply on Filter An Eloquent MorphMany Relation By Morphable?

Ping, I need an answer to this question as well. How do you skip having to use two where to get the specific type and specific ID? Is there smoother way that Laravel offers to get polymorphic relationship?

12 Sep
7 months ago

nikocraft started a new conversation API Question: Can I Store Oauth Client_secret On Server Instead Of Sending It From The Frontend Client So Everyone Can See It?

I am building a client that will consume api. Using Laravel and vuejs for this. Backend is it's own app and frontend client is its own app that will run on vuejs.

Right now when I want to login user to the backend I have to send this data from client:

                form: {
                    'grant_type' : 'password',
                    'username': '[email protected]',
                    'password': 'pass1234',
                    'provider': 'student',
                    'client_id': "2",
                    'client_secret' : 'fXz4bILqz5CnDjFCvXpw7RZWLgWXxsTa0LN1'
                }

How smart or dangerous is it to save secret in client like this? Now everyone can see it, can they use this in some way? And if its dangerous how is everyone else doing it? If you are not sending secret from the client, then where do you keep it?

15 Aug
8 months ago

nikocraft left a reply on Using Laravel Accessors In A Vue Layout

the above is the only solution, once appeneded, they will always follow :)

nikocraft started a new conversation Laravel Connection: Sqlite, Database: Memory Leads To Could Not Find Driver

I'm running laravel on win10, so I cant really run

sudo apt-get install php7.1-sqlite3 as pointed out here:

Laravel - Could not find driver exception with sqlite

I am trying to run some tests with phpunit and inside one of tests I've done:

class ViewConcertListingTest extends TestCase { use DatabaseMigrations;

and inside phpunit.xml

I've added these two

<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>

What can I do to get laravel to be able to use sqlite and memory database?

11 Aug
8 months ago

nikocraft left a reply on How Does Everyone Sync Their MorphToMany Relationships?

there is also morphToMany which is basically manyToMany relationship but on polymorphic models :)

If we have sync for many-to-many why not morphToMany as well?

nikocraft left a reply on How Does Everyone Sync Their MorphToMany Relationships?

Maybe I am thinking wrong here, why do we for example have sync for manyToMany relationships at all in Laravel but not for morphToMany?

10 Aug
8 months ago

nikocraft left a reply on How Do I Select MorphToMany Relationship Based On The Morphable Type?

you don't post for 10 months and you help me, thank you @Abi appreciated! :)

nikocraft started a new conversation How Do I Select MorphToMany Relationship Based On The Morphable Type?

I want to do something like this:

Tag::where('taggable_type', 'App\Models\Core\Media\Image')->get()

Image model has Tags, which are defined like

public function tags()
{
    return $this->morphToMany(Tag::class, 'taggable');
}

And then we have two migrations

    Schema::create('tags', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('slug')->unique();
        $table->timestamps();
    });

and

    Schema::create('taggables', function (Blueprint $table) {
        $table->integer('tag_id');
        $table->integer('taggable_id');
        $table->string('taggable_type');
    });

so ofc I cant do this Tag::where('taggable_type', 'App\Models\Core\Media\Image')->get()

since tag model it self does not have taggable_type, but the polymorph pivot table has. How can I query tag table but let it only return stuff where taggable_type is of this 'App\Models\Core\Media\Image'?

nikocraft started a new conversation How Does Everyone Sync Their MorphToMany Relationships?

How do you sync them?

Do you just detach and then attach again? Why do we not have sync method for toMany polymorphic relationships? Is this method hard to implement correctly for polymorphic models?

02 Jul
9 months ago

nikocraft left a reply on Setting Up Lets Encrypt On Forge

hi so once this is done I can access https://mysite.com

do I need to tell laravel to run everything over https or will it automatically work? I've done this over a year ago but I forgot the details. Greatfull for any tips in case extra steps are needed after Lets Encrypt has been installed :)

01 Jul
9 months ago

nikocraft started a new conversation How To Turn Of Phpinfo On Freshly Deployed Forge Server?

if server is accessed directly by ip in browser it displays phpinfo, how can this be turned off?

nikocraft left a reply on How Good Is Forge Support From Your Perspective?

seems like Stripe has really some bad algorithms to block a valid bussiness card. Why does paypal never have the same problem :) I never got this with them.

nikocraft started a new conversation How Good Is Forge Support From Your Perspective?

I'm wondering about Forge support, do they allways respond? I've read on reddit that some questions go unanswered, has it happened to any of you?

I've tried to sign up to business plan and I got a message saying that it failed and that I should get in touch with Stripe to check why.

I tried reaching out to Said, the guy Taylor hired as laravel first employe. I reached out to him about this on twitter 18 hours ago and he did not care to even respond.

I guess they must be too busy and dont care about some of this stuff.

What is your experience? Is support good, how long before Taylor answers? I guess he is the one answering most support questions?

27 Jun
9 months ago

nikocraft left a reply on How To Tell Laravel To Automatically Decode Urls

how do I access incoming paramters and then push them back in?

TrimStrings looks like this

class TrimStrings extends Middleware
{
    /**
     * The names of the attributes that should not be trimmed.
     *
     * @var array
     */
    protected $except = [
        'password',
        'password_confirmation',
    ];
}

nikocraft started a new conversation How To Tell Laravel To Automatically Decode Urls

How do I tell laravel to automatically turn this

http://laraone.oo/backend/activate/8%3Fexpires%3D1530213677

into this

http://laraone.oo/backend/activate/8?expires=1530213677

I am currently getting the first type of link when I submit something via post method from the vue, and if I remember correctly there is somewhere in laravel a place where I can enable laravel to conver all first type of links into second type of links before it starts extracting them and parsing them.

nikocraft started a new conversation How To Verify Signed Url When Submiting As Post Via Vuejs?

I am using laravels signedRoutes and I have signed a route on the server and now I need to submit this route again to the server but from the client which is in javascript. Below code is what I have before I send it to the server.

                        let formData = {
                            signature: '51bd52ece280dd29857aa7443e9178e64cf27047e831f4cdfd32c951c4571f65',
                            testing: '12345',
                            expires: '1530209048',
                            user: '7',
                            password: this.password,
                            passwordConfirm: this.passwordConfirm
                        }

return axios.post(route('backend.user.activate'), formData)

When I recieve this on the server I do

    public function activate(Request $request)
    {
        if ($request->hasValidSignature()) {
            dd('we cool!');
        }

"we cool!" does not print for me, which means Laravel has problem to verify the valid signature when sent as a post.

I also tried attaching like this

return axios.post(route('backend.user.activate', urlSignature), formData)

where urlSignature="7?expires=1530209048&testing=12345&signature=51bd52ece280dd29857aa7443e9178e64cf27047e831f4cdfd32c951c4571f65"

but laravel still fails to verify that signature is valid, which it is, since it works over simple route like this

Route::get('/activate/{user}', 'Auth\[email protected]')->name('backend.user.activate.show');

but as soon as I go to post

Route::post('/activate/{user}', 'Auth\[email protected]')->name('backend.user.activate');

it fails.

I need to use the post, since I must send password in the post and I do not wish to send it via get request.

26 Jun
9 months ago

nikocraft left a reply on How To Override Auth Login Function In Laravel?

@jlrdw hi, how are things in the future, are Marty and Doc still around? Is everything ok with Earths gravity?

nikocraft left a reply on How To Override Auth Login Function In Laravel?

Ok this is final function if anyone from the future wonders what the solution was:

    public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if($this->guard()->validate($this->credentials($request))) {
            if(Auth::attempt(['email' => $request->email, 'password' => $request->password, 'is_activated' => 1])) {
                // return redirect()->intended('dashboard');
            }  else {
                $this->incrementLoginAttempts($request);
                return response()->json([
                    'error' => 'This account is not activated.'
                ], 401);
            }
        } else {
            // dd('ok');
            $this->incrementLoginAttempts($request);
            return response()->json([
                'error' => 'Credentials do not match our database.'
            ], 401);
        }
    }

this part validates the correct credentials but does not login the user: if($this->guard()->validate($this->credentials($request)))

this part logs-in the user if all requirments are met:

if(Auth::attempt(['email' => $request->email, 'password' => $request->password, 'is_activated' => 1]))

nikocraft left a reply on How To Override Auth Login Function In Laravel?

Actually its good except we got another problem now.

If user creditials do not match what is found in the database now user will only get back "This account is not activated." error message, which may not be true. Any idea how to solve this problem? I have to show the user correct error message.

nikocraft left a reply on How To Override Auth Login Function In Laravel?

yes it was very usefull :) thanks!

Btw if anyone in future wonders what I did, here is how I solved it

I still had to override the login function inside LoginController.php this had to be done so I get all the throttling and error messages that can be generated by the system. Here is my final function

    public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if(Auth::attempt(['email' => $request->email, 'password' => $request->password, 'is_activated' => 1])) {
            // return redirect()->intended('dashboard');
        }  else {
            $this->incrementLoginAttempts($request);
            return response()->json([
                'error' => 'This account is not activated.'
            ], 401);
        }

        $this->incrementLoginAttempts($request);
        return $this->sendFailedLoginResponse($request);
    }

@BishoyWagih if you think it could have been even more simplified plz let me know :)

nikocraft left a reply on How To Override Auth Login Function In Laravel?

ok I see now, example is in the documentation. Thanks :)

nikocraft left a reply on How To Override Auth Login Function In Laravel?

and how exactly do I tell attempt to also check the is_activated field

What would I put here inside attempt so it checks additional column for true or false?

        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );

nikocraft left a reply on How To Override Auth Login Function In Laravel?

You are correct I want to check for is_activated. I did this for now:

I copied the whole login function into LoginController.php and this is the interesting part

        if ($this->guard()->validate($this->credentials($request))) {
            $user = $this->guard()->getLastAttempted();
            if ($user->is_activated && $this->attemptLogin($request)) {
                return $this->sendLoginResponse($request);
            } else {
                $this->incrementLoginAttempts($request);
                if ($request->ajax()) {
                    return response()->json([
                        'error' => 'This account is not activated.'
                    ], 401);
                }
            }
        }

If I do it as you suggest, how can I also generate the error message as above only if is_activated is false on that particular user?

nikocraft started a new conversation How To Override Auth Login Function In Laravel?

I need to override laravels default login function, however I am confused by the code I find there. I do not understand how laravel AuthenticatesUsers.php verifies that user exists in db and then authenticates the user.

I've come to this function in AuthenticatesUsers

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
    }

I guess I would need to override this function inside auth/LoginController.php

but I do not understand how it works. Where are guard() and attempt() implemented, I guess the real action happens there. I need to add another condition to the login.

Anyone understands how laravels default login works? and those two functions guard() and attempt(), for example attempt is not implemented inside AuthenticatesUsers.php it self and I belive its this function I should really override.

Where can I find it's implementation?

04 Jun
10 months ago

nikocraft left a reply on Making A Laravel 5.4 Query On A JSON Field Containing A JSON Array

I got a similar problem. Here is my case:

Inside users table I have a json column named "agencies" that stores data as a simple array like this:

[
"0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12",
"f7c748d4-8718-441e-aa69-91b890ead5ed"
],

the above is valid json. When I try to select all users that contain 0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12 I get null

Is my query correct?

$users = User::whereRaw('JSON_CONTAINS(agencies->"$[*]", "0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12")')->get();

is the below correct way to do write JSON select query considering how I store uuids as an array inside agencies column which is defined as json?

'JSON_CONTAINS(agencies->"$[*]", "0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12"

I looked at the original stackoverflow answer posted above and modified it to this agencies->"$[*]" but it does not seem to be working for me.

Using Laravel 5.4

I'd appreciate if you guys had any ideas what may be wrong in my case?

26 May
10 months ago

nikocraft started a new conversation Call Artisan Command That Has No Name For The One And Only Option

How would I execute command like this from the Controller:

Package I am using that gives the below artisan commands: https://github.com/JosephSilber/page-cache

php artisan page-cache:clear {slug}

for example if typed manually

php artisan page-cache:clear about-us

Laravel docs gives us this: https://laravel.com/docs/5.6/artisan#programmatically-executing-commands

Artisan::call('email:send', [
    'user' => 1, '--queue' => 'default'
]);

Since the artisan command page-cache:clear does not take any named parameters, how do I send the slug parameter to it?

I've tried this:

Artisan::call('page-cache:clear ' . $content->slug);

and get back this error:

Command "page-cache:clear hem" is not defined.↵↵Did you mean this?↵    page-cache:clear

and also I've tried this:

Artisan::call('page-cache:clear', [$content->slug]);

but then slug is not added and it calles

php artisan page-cache:clear without slug so this package clears all the cached files.

23 May
10 months ago

nikocraft left a reply on How To Go From Http To Https, Certificate Already Installed And Https Is Working...

@cronix

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ / [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

I placed it at the end of .httaccess that comes with laravel but it gives an error:

The page isn’t redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

nikocraft left a reply on How To Go From Http To Https, Certificate Already Installed And Https Is Working...

nice, but why layout.app, why not web.php where it would be more elegant to keep that code at top?

nikocraft started a new conversation How To Go From Http To Https, Certificate Already Installed And Https Is Working...

if someone directly enters www.myapp.com the browser will take them to http://www.myapp.com

myapp is configured to work with https so if we enter manually https://www.myapp.com then there are no problems laravel generates https urls correctly?

how do I get browser to go to https when user just enters www.myapp.com instead of browser taking them to the http?

Where is the most elegant place to make this happen?

10 May
11 months ago

nikocraft left a reply on Will Laravels Packages Also Work On Lumen?

sorry name of that package confused me, I thought it would execute on the client and not on server, actually link I post first is wrapper for the htmlpurifier! :)

nikocraft left a reply on Will Laravels Packages Also Work On Lumen?

there is also a postman that hacker can use to post something to an endpoint :)

nikocraft started a new conversation Will Laravels Packages Also Work On Lumen?

I'm interested in Purifier package which is used to clean up the input from the user, and wonder if I can use it on Lumen

https://github.com/mewebstudio/Purifier

What is everyone else using to sanitize input in Lumen?

05 May
11 months ago

nikocraft left a reply on How To Print Curly Braces From Database

thats great! thanks for update :) we all use vuejs now in our projects and I will soon need this again, so its just purefect! :)

24 Mar
1 year ago

nikocraft left a reply on SQLSTATE[HY000]: General Error: 1215 Cannot Add Foreign Key Constraint Laravel

@snapey you never had to do anything like this? for parent-child in the same table?

@cornix I figured out the problem, I had to add unique() to the id column, it wont assign it without that.