grenadecx

grenadecx

Member Since 11 Months Ago

Webdeveloper at Rocketlabs AB

Experience Points 23,210
Experience Level 5

1,790 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 0
Lessons
Completed
Best Reply Awards 37
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.

17 May
3 days ago

grenadecx left a reply on Use JQuery With Vue

In a default laravel installation they do it like this:

window.$ = window.jQuery = require('jquery');

Wouldn't you be able to do the same?

grenadecx left a reply on What Is The Best Solution To Generating Export Csv Data (Performance)

I would queue it. There's a good example of it over here:

https://docs.laravel-excel.com/3.1/exports/queued.html

But yeah queuing it and just notify the user upon completion seems like a better options, especially if the file can vary and be that big.

And sure the query you use to fetch the data matters, but it's hard to say what you can optimize without seeing the code for it.

grenadecx left a reply on How Do I Create A Join With The Query Builder When I Have A Pivot Table?

Well you have defined your relationship as belongsToMany. So when the query is made traversing it, it's gonna check against the pivot table as well. You can enable the querylog in laravel and check how the queries are made.

\DB::connection()->enableQueryLog();

$campaign_id = 1;

$items = Items::whereHas('campaign', function($query) use ($campaign_id){
    $query->where('campaign_id', $campaign_id)
})->get();

$queries = \DB::getQueryLog();
return dd($queries); // Now you inspect the queries that have been made since you enable the querybuilder
16 May
4 days ago

grenadecx left a reply on How Do I Create A Join With The Query Builder When I Have A Pivot Table?

You could utilize whereHas for that.

$campaign_id = 1;

$items = Items::whereHas('campaign', function($query) use ($campaign_id){
    $query->where('campaign_id', $campaign_id)
})->get();

Ref: https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence

grenadecx left a reply on Using The Query Builder For A Many To Many Relationship?

Can one file relate to many campaigns now then?

You could fetch the campaign, and then fetch the files

$camapaign = Campaigns::find($id);

$files = $campaign->files(); // This would be the same query as

// $files = File::where('campaign_id', $id);

// Then go on as usual and add your extra queries on the $files

Another way would be to utilize there whereHas function: ref: https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence

$files = File::whereHas('campaign', function($query) use ($id){
    $query->where('campaign_id', $id);
});

// Then go on as usual and add your extra queries on the $files

Hope I understood your relations.

grenadecx left a reply on Using The Query Builder For A Many To Many Relationship?

If you use eloquent, you can do something like:

$campaign = Campaign::with(['items => function($query){
    $query->whereMonth('somemonth');
    $query->orderBy('something', 'asc');
}'])->find(1);

Reference: https://laravel.com/docs/5.8/eloquent-relationships#constraining-eager-loads

When it comes to Query Builder without eloquent you would probably need to use joins, since it doesn't have relations. But if I understood you correctly, wouldn't using eloquent work with constraints?

grenadecx left a reply on Prevent Site Going Down When Route Does Not Exist

Alright, now I get ya. Sorry for being so slow >.>

Well then the only way would be to either override that function or actually load a helper file with the route function before laravel loads their helper file. Because they load it through the composer and it will only be defined it it doesn't already exist.

grenadecx left a reply on Prevent Site Going Down When Route Does Not Exist

    public function render($request, Exception $exception)
    {

        if (env('APP_ENV') == 'production' && $exception instanceof \InvalidArgumentException){
            return response()->make('',200);
        }

        return parent::render($request, $exception);
    }

I was too lazy to check the string, but you get the point. Wouldn't this work?

grenadecx left a reply on Prevent Site Going Down When Route Does Not Exist

Yeah I got that. I missunderstood the question.

Wouldn't it be possible to catch the "InvalidArgumentException" that is being thrown, investigate the string and if it begins with "Route" and ends with "not defined."?

        throw new InvalidArgumentException("Route [{$name}] not defined.");

grenadecx left a reply on Prevent Site Going Down When Route Does Not Exist

You could always create a wildcard route at the bottom of all your routes that will catch everything.

Route::get('{slug}', function(){

echo "Hello there";

})->where('slug', '.*');

Might be better solutions however. And if you only want it to be active during production, just put an if statement around it?

grenadecx left a reply on Updated Image Does Not Show Correctly

I wouldn't say it's better, but it's doable. But you need to get the contents of the file and the base64 encode it.

I will show an example of how you could do it, it's untested code however.

$data = file_get_contents($request['image']->getPathName());
$base64 = base64_encode($data);

// Now you could store the base64 encoded into the binary column.

Checkout the following post for some suggestions to that, here they show how to retrieve the image type as well and store it together. Some of this needs to be converted to laravel functions but yeah. https://stackoverflow.com/questions/3967515/how-to-convert-an-image-to-base64-encoding

grenadecx left a reply on Updated Image Does Not Show Correctly

That would help. It would also help to know how you want the image stored. Is the goal to have it stored in the database as a binary image or do you want to store the file on disk and just store the filepath in the database as reference?

If the second part is true, you should take a look here: https://laravel.com/docs/5.8/requests#storing-uploaded-files

They show how to store it to disk, and then you can use the filelpath you get back and store that into the database. In a default laravel installation, laravel have a filesystem configured as "public" that points to storage/app/public folder, this folder then gets symlinked to public/storage when you run php artisan storage:link.

If you want to store stuffs to that folder, something like this:

$path = $request['image']->store('images', 'public'); // First argument is folder and second is disk

// Now you have the $path and this could be stored in database as a string
$user = User::find(auth()->user()->id);
$user->image = $path;
$user->save();

// Now when you need to output this in the view I would do:
<img src="{{ \Storage::disk('public')->url(auth()->user()->image) }}"/>
 

Reference on using the filesystem to get urls https://laravel.com/docs/5.8/filesystem#file-urls

Now if you wanted it stored as a binary, the setup would be different. I would advise storing it as binary in database unless you really need it.

grenadecx left a reply on Updated Image Does Not Show Correctly

The problem here is that you are saying the image is successfully stored.

User::where('id', Auth::user()->id)
                ->update(
                    [
                        'image' => $request['image']]
                );

This piece of code is odd. Because you take the image object which is a (UploadedFile class) from laravel and inserts directly into the image column in the user table. What structure is that column?

I don't see that UploadedFile class would have any magic functions such as __toString that would convert into into a binary if you would use it as you do. Therefor I'm not sure what you have stored.

Without additional information such as column structure, picture of the data stored, it's hard to help you any further.

15 May
5 days ago

grenadecx left a reply on Updated Image Does Not Show Correctly

If you are storing the image as a binary in the database, the output would normally be something like:

<img src="data:image/jpg;base64, {{ Auth::user()->image }}" />

the image/jpg might need to be difference depending on the uploaded file however.

But I'm still not convinced on how the image is actually stored. If the image is stored as a filepath and the actual file in inside the storage folder then you would need to php artisan storage:link to make it available from the public folder.

grenadecx left a reply on Updated Image Does Not Show Correctly

I'm not sure what's going on here. In your view you are calling

                <img src="{{Auth::user()->images}}"/> // images?

And then in your controller you are

User::where('id', Auth::user()->id)
                ->update(
                    [
                        'image' => $request['image']] // image?
                );

Question is, what are you storing and how do you know if the image is stored correctly? If you are attempting to store the file path, you are not really storing the file anywhere. If you are attempting to store it as a binary to the database, I'm pretty sure that's also not the correct way (especially the output would be different).

Please take a look under to get a better understanding of uploading files using laravel: https://laravel.com/docs/5.8/filesystem#file-uploads

grenadecx left a reply on AOS With Jquery.easing.min.js Not Working

<script src="{{ asset('themes/js/jquery-3.3.1.slim.min.js') }}"></script>
<script src="{{ asset('themes/js/popper.min.js') }}"></script>
<script src="{{ asset('themes/js/bootstrap.min.js') }}"></script>
<script src="{{ asset('themes/js/jquery.min.js') }}"></script>
<script src="{{ asset('themes/js/jquery.easing.min.js') }}"></script>
<script src="{{ asset('themes/js/aos.js') }}"></script>
<script src="{{ asset('themes/js/script.js') }}"></script>

You are loading jquery slim and then you load jquery after bootstrap. Loading both will cause problems. I suggest doing this:

<script src="{{ asset('themes/js/jquery.min.js') }}"></script>
<script src="{{ asset('themes/js/popper.min.js') }}"></script>
<script src="{{ asset('themes/js/bootstrap.min.js') }}"></script>
<script src="{{ asset('themes/js/jquery.easing.min.js') }}"></script>
<script src="{{ asset('themes/js/aos.js') }}"></script>
<script src="{{ asset('themes/js/script.js') }}"></script>

That will take care of not loading jquery more then once. Try that out and see if you still have the same error.

grenadecx left a reply on How To Modify/Personalize Email Verification Email

As far as I can tell the best way to do this is to override the

    public function sendEmailVerificationNotification();

on the User model.

That comes from the MustVerifyEmail interface. And inside that you could either use the $this->notify to send a notification email of your choice. It's the same kinda of logic that is done on the "reset password" notification.

grenadecx left a reply on How To Paginate And Sort Results?

sortByDesc is done on the collection itself, while orderBy is done on the eloquent model, so it's used in the query.

 $files = $files->orderBy('created_at', 'desc')->paginate(2);

There's a difference between doing it on the query and doing it after the query. That's why.

14 May
6 days ago

grenadecx left a reply on Incorrect Request

Could you do:

dd($data['impot']);

Inside the controller? So we know how it looks like?

grenadecx left a reply on Using Uuid My Foreign Key Constraints Fail

@SLIPPERYDIPPERY - Try, since that's what you use on the id on users table.

$table->uuid('user_id')->nullable();

grenadecx left a reply on How To Get The User Name By Not Primary Key Field In Laravel

You setup a similar relationship on the task model as you did with the user relation.

class Task extends Eloquent {

    // add this to task model
    public function assigned()
    {
        $this->belongsTo(User::class, 'user_id', 'id') // You might need to reverse user_id and id, can't remember which way they references
    }

}

And then use

$tasks = Task::with('user','assigned')->get();


VIEW

ID Creator ASSIGNED TO CONTENT

@foreach($tasks as $task)

{{ $task->id }} {{ $task->user->name }} {{ $task->assigned->name }} // what sould i write here to get the user name. {{ $task->content }} @endforeach ```

grenadecx left a reply on Incorrect Request

public function demo(Request $request)
{
    $im = salaries::selectRaw('(nombreparts) as total')
            ->where('salaries.id', $request->id)
        ->first()
        ->total;

        $data['impot'] = DB::table('baremes') ->where('revenubrut','=',$d);
        
    if( $im == 1){ 
        ->select('un'); // Syntax error
    }
    ->get(); // Syntax error
}

The above is wrong, but I guess that is what you needed help with? I'm not quite sure what you are after however.

    $im = salaries::selectRaw('(nombreparts) as total')
            ->where('salaries.id', $request->id)
        ->first()
        ->total;

        $import_query = DB::table('baremes') ->where('revenubrut','=',$d);
        
    if( $im == 1){ 
        $import_query->select('un'); // Using the query to just append to it
    }

    $data['impot'] = $import_query->get(); // Executing the query

grenadecx left a reply on Using Uuid My Foreign Key Constraints Fail

        $table->integer('user_id')->unsigned()->nullable();

Here you are defining the relation as an integer. But in the users table it's an uuid. And then you reference it, shouldn't they be the same type?

09 May
1 week ago

grenadecx left a reply on Laravel Multiple Slugs

Well based on what you explained I don't see any other way around that. So yeah I think this will work just fine for you.

grenadecx left a reply on Laravel Multiple Slugs

Something like this

Route::get('/ads/{slug}', '[email protected]')
    ->where('slug', '.*')

Then in the controller you explode the slug based on /.

grenadecx left a reply on Search Function MYSQL

You need to add

use View;

At the top of the AppServiceProvider.php file. You can also use the helper instead

        view()->share('categories', Category::all());
08 May
1 week ago

grenadecx left a reply on Class App\Http\Controllers\Auth\Auth\ForgotPasswordController Does Not Exist

Leaving an empty group serves no purpose. Just remove the entire group around those routes unless you are actually planning to use it for something.

grenadecx left a reply on Class App\Http\Controllers\Auth\Auth\ForgotPasswordController Does Not Exist

Seems you have double Auth\Auth in the namespace for the ForgotPasswordController. You probably solve this by moving the Route::resetPassword outside the Route namespace Auth group.

You could also remove that group and just add the Auth\ to all the controllers instead.

I assume you have the problem because the Route::resetPassword() already calls the route with Auth\ForgotPasswordController, and you adding the extra namespace makes it double.

grenadecx left a reply on Deploying Laravel App On Cpanel Is Returning Symfony/polyfill-mbstring/bootstrap.php

To me it looks like you are missing a vital file inside the vendor folder.

require(/home/demolinx/vendor/composer/../symfony/polyfill-mbstring/bootstrap.php

This file is responsible to load a bunch of mb_functions if mb_strlen function is missing. Even if you have mbstring extension installed, this file should still exists and needs to be loaded. Try update your vendor folder with

composer update

You could empty that folder before running the command to make sure it will download it.

07 May
1 week ago

grenadecx left a reply on I Would Like To Register Users Manually, Any Relevant Videos/guides?

Inside vendor/laravel/framework/src/Illuminate/Routing/Router.php

You will find the auth() function. This is what gets called when you call Auth::routes(); inside web.php. You can just copy all those routes and move them inside your web.php route and remove the Auth::routes();

Just replace $this-> on the routes with Route::

When it comes to registration, it's nothing fancy, you could either modify the current controller in Controllers/Auth/RegisterController to suit your need, or just create your own controller with your own form.

grenadecx left a reply on Modifying Input Type On Chrome Inspect

No. You can't go around this. Also, unless the password is encrypted, the user can see it in plain text when you send it under the network tab, they could just inspect the formdata being sent with that request.

I think you are trying to solve a problem that doesn't really exist. If it's a password that a user shouldn't be able to see, then just don't autofill it back into the form field.

06 May
2 weeks ago

grenadecx left a reply on How To Delete Multiple Records Using Checkbox Checked In Laravel?

If you had 100 checkboxes, that would mean 100 queries.

You could do as @ftiersch already stated:

Purchase_details::whereIn('id', $data['purchase'])->delete();

This would do the same thing but with only one query. Only negative impact on doing it this way is you can't listen to eloquent events like deleting and react to that. But if you need to do that you could just fire off your own event.

03 May
2 weeks ago

grenadecx left a reply on Fail_job Using The Old Data When They Retry Again

That depends on your job. If you passed information to the job and are using that information, then that information will be the same "old" values. But if you inside the job is making queries or whatever, that will be done in realtime of course.

For example if I have a job for my order table after order is complete and I just pass the id to the job, and inside the job I use that id to query the database, then it would fetch new information. But if you passed for example the entire order to the job, the order would just been serialized and restored when running the job, so that would be "old" data.

02 May
2 weeks ago

grenadecx left a reply on Is There A Way To Optimize Css?

If you are gonna use purgecss, may I suggest you take a look at this wrapper from spatie:

https://github.com/spatie/laravel-mix-purgecss

It simplifies the setup process quite a bit.

grenadecx left a reply on Redirect To Intended Page After Login - Laravel 5.7

He could call the proper function that deals setting it instead of setting the session manually.

redirect()->setIntendedUrl(url('/intended-url'));
30 Apr
2 weeks ago

grenadecx left a reply on Laravel 5.7 Resend Verification Email Not Working On Server

I missed that you used mailtrap. Doesn't mailtrap have any kind of logs? At least so we can determine if mailtrap gets the message or if laravel never sends it.

grenadecx left a reply on Laravel 5.7 Resend Verification Email Not Working On Server

@LUKA - If you look at the config file, you will see it uses the env function when defining some of those options. That means you can use .env file to override those options. So if you wanna use the .env file to do that or just append the config file directly is really up to you, but best practice is using the .env file for it.

Also the problem isn't the smtp driver. If other emails are being sent out then the problem elsewhere.

But if you are willing, you could setup a mailgun account (free) up to 10k emails a month and setup the emails using it instead. It's possible to use the regular smtp protocol over it but you can also use the mailgun api to send the emails.

https://laravel.com/docs/5.8/mail

Look at the mailgun driver here. But as I said, you can skip the mailgun driver and use the smtp driver over mailgun as well. So it's what you prefer. I would recommend the api over smtp however.

In mailgun you can also see log files if they receive the email and where they send it. That way you can track it.

grenadecx left a reply on How To Use Search Option In Drop Down In Array Of Drop Downs Javascript

How does the new select get created? Could you show some code there?

I mean all you really need to do is to somehow be able to select it so you can run the .chosen on it it. For example:

// heres the template code
$template = $('<select name="product_name[]"><option value="test">test</option></select>');

// Execute the chosen on the select inside the template
$template.find('select[name=product_name\\[\\]]').chosen();

// appends the template to the body. You can also choose to execute the chosen after appending to the body as long as the template is an jquery object.
$(body).append($template);

29 Apr
3 weeks ago

grenadecx left a reply on Validate HTML Array Input In Laravel

Sorry, I wasn't clear enough. Since I don't see all the code, but I did assume you use foreach to list all the inputs somehow. And if you do, you could use

foreach($items as $key => $item){
    // Now you have access to $key
}

But I don't know. How are you outputing multiple inputs? Like the one below

<input type="text" class="form-control"  name="included_items[]" placeholder="Item Name">

grenadecx left a reply on Validate HTML Array Input In Laravel

name="included_items[]"

Once this get sent to the server, it will be turned into an proper array with indexes. Your validation rule will work serverside because you use included_items.* (which will be translated into included_items.0 for the first item sent, increasing with +1 for each item sent in the array.

But then you need to check for that specific key or the wildcard when returning to the view if you want to be able to mark that specific input with correct error.

@if ($errors->has('included_items.*')) // But this will probably not give you the desired result

If you use a foreach to loop out the

<input type="text" class="form-control"  name="included_items[]" placeholder="Item Name">

May I suggest you add they $key there

<input type="text" class="form-control"  name="included_items[{{$key}}]" placeholder="Item Name">

Because that will make it easier on the

@if ($errors->has('included_items.'.$key))

and the

{{ $errors->first('included_items.'.$key) }}
26 Apr
3 weeks ago

grenadecx left a reply on Saving An Array To Database

That seems right. Laravel will encode and decode the coordinates column upon saving and fetching.

So you just treat is as a normal array and laravel will do the rest. And the database column is best treated as json as your doing if possible, but it could also just be a string/text really.

25 Apr
3 weeks ago

grenadecx left a reply on Session Has Been Expired 419

Are you sure you are getting a match with the selector and it's being sent? In chrome you can inspect the request headers that is being sent in the inspection tool under network.

Like below http://i.imgur.com/AVQoXx7.png

grenadecx left a reply on Session Has Been Expired 419

That error is usually because of missing token in the ajax request.

Take a look here https://laravel.com/docs/5.8/csrf

Since you use axios, in the default app.js or maybe it's bootstrap.js that comes with laravel, it has this code:

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

As you can see it takes the csrf from the meta tag and appends all ajax calls with axios.

grenadecx left a reply on Tawk.to(chat Tool) Integration To Laravel Project

I've never used that package, but to add tawk all you really need is the widget code you get that from tawk.to.

Like in the example below https://www.tawk.to/wp-content/uploads/2015/04/add-new-site.png

You take that code and add anywhere in your page and it start working as per your configuration for that widget.

24 Apr
3 weeks ago

grenadecx left a reply on Laravel 5.8 Migrate Not Working

I've explained the problem already.

You either have multiple migration files using the same table name like below:

Schema::create('products'....

Or you did not remove products table in the database before you ran the migration again.

Do this:

  1. Drop all tables in the database manually or through phpmyadmin
  2. Run php artisan migrate

If you get error that says table already exists, this means you have multiple migrations for the same table. Look inside your migration files to solve this.

If you have another error, please post it so we can debug futher.

grenadecx left a reply on Laravel 5.8 Migrate Not Working

If you did you would get another error. If the database is empty and you migrate, and with only those files you showed, the first error you will get will not be that the products table already exists.

grenadecx left a reply on Laravel 5.8 Migrate Not Working

The error you are getting is because the table it's trying to migrate already exists.

This can happen during migration if you have error in one migration file, then you could end up with a table that was created but laravel threw error and now it's missing in the migration table. So during migrate it will keep giving you that error.

I would suggest you clean out all tables by hand, since refresh wont remove it if it isn't in the migration table.

grenadecx left a reply on Laravel Weebhook

NotFoundHttpException indicates that either the url is wrong in postman or you are calling a get request instead of a post request. So if you could double check that that would be great.

grenadecx left a reply on Laravel Weebhook

What's the exact error message? Getting a response 500 isn't enough to determin what's going on here. You should get an error message along with it if you have debugging enabled.

Also don't forget to exclude the url from the csrf middleware if you have that enabled. Take a look here under the "Excluding URIs From CSRF Protection": https://laravel.com/docs/5.8/csrf

23 Apr
3 weeks ago

grenadecx left a reply on Passing An Array Of Values To A Multi-select Component

I did something similar a few days ago. I found that passing it with {!! !!} doesn't work, instead it works with just regular {{ }}.

You almost got it right.

<div id="chatApp">
    <chat
        :routes="{{ json_encode(config('rl_chat.routes.api.chat')) }}">
    </chat>
</div>

And my config looked like this:

return [

    'routes' => [
        'chat' => [
            // More data here
        ]
    ]
    
];