grenadecx

grenadecx

Member Since 1 Year Ago

Webdeveloper at Rocketlabs AB

Experience Points 30,020
Experience Level 7

4,980 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 3
Lessons
Completed
Best Reply Awards 48
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

10 Jul
1 week ago

grenadecx left a reply on How To Change Queue? For Notification Broadcasting

Still haven't solved this. So gonna bump this and see if a kind soul could help me out.

28 Jun
3 weeks ago

grenadecx left a reply on Directory Path

Read my edited message.

grenadecx left a reply on Multilevel Authentication

I would use a role based system for this with permissions.

You could take a look at spaties role/permission package over here: https://github.com/spatie/laravel-permission

Basically depending on the complexity, you could get away with just creating 4 roles and then just check the roles in the code. More elegant way would be to add proper permissions and then check the permissions instead, that way you could have any number of roles and just apply the permissions on the roles instead.

In both cases you apply a user to a role and they will get either the assigned permissions or when you check for a specific role for access in the code.

grenadecx left a reply on Directory Path

By the look on your folders, the folder name of imagineprofil is actually \imagineprofil.

If that's the intention, you need to reference it correctly. In your case it would be

src="{{asset('\imagineprofil/'.$profileimage->image)}}"

13 Jun
1 month ago

grenadecx left a reply on Adding A Step Before Registration

I'm glad you worked it out :)

12 Jun
1 month ago

grenadecx left a reply on Adding A Step Before Registration

Auth::routes takes you to: https://github.com/laravel/framework/blob/5.8/src/Illuminate/Routing/Router.php

public function auth(array $options = [])
    {
        // Authentication Routes...
        $this->get('login', 'Auth\[email protected]')->name('login');
        $this->post('login', 'Auth\[email protected]');
        $this->post('logout', 'Auth\[email protected]')->name('logout');
        // Registration Routes...
        if ($options['register'] ?? true) {
            $this->get('register', 'Auth\[email protected]')->name('register');
            $this->post('register', 'Auth\[email protected]');
        }
        // Password Reset Routes...
        if ($options['reset'] ?? true) {
            $this->resetPassword();
        }
        // Email Verification Routes...
        if ($options['verify'] ?? false) {
            $this->emailVerification();
        }
    }

So basically you could just copy the routes over instead of using auth::routes.

With your flow, you could perhaps do this with a middleware?

So basically the middleware would check if session variable is set. If it is, allow the user to enter registration page. If not, take you to the other page you want to handle first, which has it's on controller and view etc. And once data is entered and validated you are redirecting to the register page, and since session now would be set, the middleware will allow you to pass through.

07 Jun
1 month ago

grenadecx left a reply on How To Return Chunk() To Json?

If you have 3000 records and you want to display 1000 at a time, use pagination instead of chunk. This gets the first 1000 and by default listens to the ?page= in the url.

$NrMniDataUploaded = NrMniData::with('user')->paginate(1000);
return response()->json($NrMniDataUploaded);

Data will be wrapped as per https://laravel.com/docs/5.8/pagination#converting-results-to-json

06 Jun
1 month ago

grenadecx left a reply on How To Return Chunk() To Json?

I don't see how chunk solves that problem.

Chunk, in your case, would fetch 1000 users and store them in a collection. You would loop those 1000 users to print their names. and then it would fetch another 1000 users, store them in the same variable (collection) and so on. What this does is to make sure you don't run out of ram, since it will reuse the variable to store the data, so it wont keep all data in memory. Only a 1000 at a time.

At the best, using chunk this way you would allow you print the last 1000 users, since that what chunk does, the the previous data will be overriden with the last data. You could use chunk to create a new array with all the users, but then you could easily just have gotten all the users without chunk in the first place.

grenadecx left a reply on Laravel 5.7.28 Wrong Collection

Not sure about the phpmyadmin issue. But it seems to me that Laravel is working as intended

grenadecx left a reply on OrderBy Related Table's Column In Half-assembled Builder

If you want to have the results ordered by the relationship "page" in this case, you will need to join the tables so you can use orderBy on the builder instance.

Take a look at leftjoin over here: https://laravel.com/docs/5.8/queries#joins

grenadecx left a reply on How To Return Chunk() To Json?

Is the plan to only return the first 1000 users? Or do you want to return all the users?

Chunk is great when you need to fetch a lot of data that you need processing and you don't want to run out of memory, but if you need to return it as json, I don't see the point with chunk.

You are far better of just limiting the results or using pagination for this.

grenadecx left a reply on After Upgrading My Laravel To 5.8 I Get This Error As I Try To Login

First you could take a look if the login controller actually exists. It should be located in the app/Http/Controllers/Auth folder. If you open it up you can double check so the namespace of that controller is in fact App\Http\Controllers\Auth\LoginController.

If it's there are and the namespace is correct, it would seem laravel can't find it. Usually this is done automatically with the composers autoloader PSR-4 settings. So if you look inside your composer.json you should have something like:

    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories",
            "widgets"
        ],
        "psr-4": {
            "App\": "app/"
        }
    },

If that's the case and it still doesn't work, you could try to manually call from the terminal in the project folder:

composer dump-autoload
05 Jun
1 month ago

grenadecx left a reply on Laravel 5.7.28 Wrong Collection

You are saying you get 4 items when there's only 3. Are you sure the model is fetching data from the same table? I would double check the models $table variable to make sure you are fetching data from the correct table.

Could you perhaps show us the data you get with the raw sql query and the data you get in the collection?

04 Jun
1 month ago

grenadecx left a reply on Colleges - Do They Get Loaded In Memory At Once?

Sorry for late reply, but yeah, I think that would do just fine. You can always monitor the ram usage of php between using it to see if you are hitting near the limit or not. Also, php resources can be increased as well.

grenadecx left a reply on From Json To Excel

Having it as a command line would work just the same really. If you use laravel I would assume you want to use commands for this, so you could do something like

php artisan mycommand:export

So any basic laravel tutorial would work, but instead of creating Controllers, Views etc, you could just create your command that in turn executes what you want. Take a look here:

https://laravel.com/docs/5.8/artisan#writing-commands

grenadecx left a reply on From Json To Excel

Maatwebsite Laravel Excel is a good option for just that. You could easily just fetch the response into an array and convert it directly, or you could make a view table and loop through it and export the view.

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

Read the docs over there to get started.

31 May
1 month ago

grenadecx left a reply on Colleges - Do They Get Loaded In Memory At Once?

I think chunk would be your best option then. Since your memory allocation wouldn't skyrocket and you would be able to deal with them on a per chunk/item basis. The only thing that differs is you will make more queries to the database, but that probably doesn't matter at all.

grenadecx left a reply on Class Naming When Developing A Laravel Package

A package could come with multiple service providers. So naming them makes sense.

Often however, if a package comes with multiple service providers they are usually within their own namespaces anyways - so in that sense it wouldn't matter. But I think it makes easier to find and deal with when they are named, like AuthServiceProvider.

grenadecx left a reply on Colleges - Do They Get Loaded In Memory At Once?

It works exactly as you described. There's different ways to handle this. One way would be to paginate the replies and get like 20 at a time. That would save the memory allocation. It all depends if you need all that data at once or not and what you need it for.

To get for example 20 instead, you would do something like:

$replies = $post->replies()->take(20)->get(); // Or you can use ->paginate() and use the builtin pagination instead.

grenadecx left a reply on Pivot Table Always Returning Null

Of course, but you are allowed to name your models whatever you want. As long as you define the columns the right way in the relation, it doesn't matter.

30 May
1 month ago

grenadecx left a reply on Pivot Table Always Returning Null

You could try to define the columns for the relations, you might need to switch place between group_id and refreshments_id in my example.

public function refreshments()
{
    return $this->belongsToMany(
        Refreshments::class,
         'group_refreshments',
        'group_id', // you might need to switch place with this one and the one below
        'refreshments_id', // Can nenver remember how these goes
        'id'
    )->withPivot('quantity');
}

grenadecx left a reply on How To Receive Xml

I still don't understand what you mean with

And Laravel does not receive xml easily.

If the entire body is xml, you could just get it using the request object:

$xml = $request->getContent();

Otherwise you need to explain what you've tried because what you are saying makes no sense.

29 May
1 month ago

grenadecx left a reply on How To Receive Xml

laravel does not receive XML very well

Not sure what you mean with that, but there are a few solutions that converts xml into a php array or you could use a parser to parse the xml.

Here are a few examples: https://github.com/nathanmac/Parser https://github.com/orchestral/parser https://github.com/vyuldashev/xml-to-array

24 May
1 month ago

grenadecx left a reply on How To Check Queue Errors

Ah, you need to limit the jobs. If you run

php artisan queue:work --tries=1

It will fail directly to the failed_job table after first failure.

grenadecx left a reply on How To Check Whre

If you have failed_jobs table migrated, you can look at the exception column for the failed job to see the exception that was thrown.

Ref: https://laravel.com/docs/5.8/queues#dealing-with-failed-jobs

23 May
1 month ago

grenadecx left a reply on How To Best Protect My Invoice Uploads?

In laravel, you have a few different storage drives configured, take a look in the config/filesystem.php file. The one configured as public goes to storage/app/public, which in turn is symlinked to public/storage folder. I would suggest you use the local storage driver ( or configure a new one) that goes to storage/app folder, and then you can place the invoices inside a folder called invoices. This means the invoices wont be publically available using the url.

Then you could create your own route that in turn fetches the invoice from that storage folder and just returns the binary file to the client.

Take a look at the Filesystem documentation

Ref: https://laravel.com/docs/5.8/filesystem

grenadecx left a reply on "The System Cannot Find The Path Specified. " Stdout: "" Command: /usr/local/bin/wkhtmltopdf

Hm I don't see the error. I've used snappy pdf a lot and my configuration looks just like that from what I can tell.

It seems to me that it ignores the configuration and tries to go on the local installed wkhtmltopdf binary, which is kinda odd. What version of snappy pdf is that?

grenadecx left a reply on How To Count The No Of Blog That Have Category With Match Id

If you use Eloquent and you fetch all the categories, you could use withCount relation to count the relation to blogs if you have that relation.

$displays = Category::withCount('blogs')->get();

// Now $displays[0]->blogs_count exists and contains the count of the blogs for that category.

Ref: https://laravel.com/docs/5.8/eloquent-relationships#counting-related-models

grenadecx left a reply on Is It Bad Practice To Use Absolute URL In An Anchor Tag?

Absolute urls are fine. In fact laravel usually generates absolute urls when you use their functions, unless you specify you want relative.

In your case I think you should consider named routes. So you can generate your urls like this instead:


<a href="{{ route('discussion', ['forum' => $discussion->forum->slug, 'id' => $discussion->id, 'slug' => $discussion->slug]) }}"></a>

Using named routes will allow you to change the structure of your routes a lot easier and will be less prone to break if you decide you want to change the base structure and it's a lot easier to remember.

https://laravel.com/docs/5.8/routing#route-group-name-prefixes

grenadecx left a reply on How To Send Sms After Register A User?

If you don't grasp the basic concept of what you are trying to write, this will be hard.

You are calling save on what exactly?

According to your error you are doing it on a Illuminate\Http\Request object, that doesn't make any sense at all.

if ($request->save()) {

What is that line for and what are you trying to accomplish with it? The user object above that line will already be created in the database, so it's hardly the $user object either. I'm not sure what's going on with your code.

The part

        $sendSms = new User;
    $sendSms->mobile = $request->mobile;
        $sendSms->code = rand(۱۰۰۰۰,۹۹۹۹۹);

What's going on here? Do you want to create a new user, or do you want to update the existing user or do you want to create a new row in the database for some kinda of sms table?

Also you are saving the mobile into the

        $sendSms->mobile = $request->mobile;

And later on down you call on the

$receptor = $sendSms->mobile_number;
22 May
2 months ago

grenadecx left a reply on Dynamic Table

@yezawhein If you read what he said, he said your solution wont work because he uses join, which means he is merging multiple tables. By using your solution with the getColumnListing function, he will only be able to get keys from one table. He would need to run that per each join table he has as well and merge that into a single array to accomplish that with your code.

@wultyc Instead of doing toArray on the entire record you could just loop the first one and use the getOriginal on the record to get all attributes with values and then just display the $key.

@if(isset($records[0]))
    <tr>
    @foreach($records[0]->getOriginal() as $key => $field)
            <th>{{ $$key }}</th>
    @endforeach
    </tr>
@endif

This will of course, like with yours, not work if don't have any records.

I think the getColumnListing function is your best bet, but you will need to call that on each table you are joining and merge that into one header you can loop.

grenadecx left a reply on Implementing 3 Types Of Users

Checkout the answer over at this thread here: https://stackoverflow.com/questions/46292391/authenticate-users-from-more-than-two-tables-in-laravel-5

Baiscally you can add multiple authentication guards and make your 3 different models that are Authenticatable. That way when you login users like:

Auth::guard('admin')->attempt($credentials)
Auth::guard('donator')->attempt($credentials)
Auth::guard('charity')->attempt($credentials)

I would probably not do it this way. Seems a lot easier to deal with one table and roles.

Another way would be to make the users table morhpable. That way you would have like: users, admin, donator, charity tables and users table would have model_id and model_type columns. Those columns are then filled with the corresponding data from either admin, donator or charity table:

// Admin user on User table

model_id = 1
model_type = "App\Admin"

// Charity on User table
model_id = 1
model_type = "App\Charity"

// Donator on User table
model_id = 1
model_type = "App\Donator"

// Then you set the relation, maybe called type so you could

// User model
public function type()
{
    return $this->morphTo();
}

// Example on Admin model

public function user()
{
    return $this->morphOne('App\User', 'model');
}

// Then if you wanted you could add something like isAdmin or isDonator on the User model, all you need to check if the model_type equals to whatever you expect and return true/false. That way you could allow different access to stuffs.

21 May
2 months ago

grenadecx left a reply on Query Pivot Table With Data From Secondary Table

If relations are setup then something like this should work

// eagerload relation to user when fetching nominees. 
// this is optional tho, as long the relation is there, calling user from it should hkuld work
$nominee = Nominees::with('user')->find(1);

// get the name from user relation 
$nominee->user->name

grenadecx left a reply on LeftJoinSub() Inside Another Left Join Subquery?

While I haven't tried this, but if I remember correctly, you can send in a closure with the leftJoin, in that case you should be able to use a new leftjoin inside that closure.


Test::where('id', 1)->leftJoin('table3 AS c', function($join){
    $join->on('a.field2', '=', 'c.field2');
    $join->leftJoin() // New leftjoin here
});


grenadecx left a reply on Edit Parent Details - Eloquent Models

Great :)

That way you don't need to clutter it everywhere. Another way would be to use a function inside the child.

$child->activate();

And inside that child you execute the activation for parent as well. But I like event/observer bit as well, it's quite clean.

grenadecx left a reply on How To Get Sum Of A Column In This Relation? User > Booking > Booking_items

Well there are a lot of ways to do the same thing. I'm not sure what's best. You could move it inside the User model and not being static and then replace the $userId with $this->id, that way you could fetch it by the user model directly. You could also use static inside the booking model and call that static in a nonstatic on the user model. That way you could do both Booking::function and the $user->function

The only noteworthy thing to remember is when you work on the relations is that it will automatically apply the constrains of the relation on the model if you work directly with the relation. When you work with the model directly, you wont get those retraints.

If you want static functions or not that's up to you, both are possible. But if you want it inside the booking model, static is the only sensible because it's not a specific booking. If you want it inside user model, nonstatic works fine because it's on a specific user.

Hope I make any sense...

grenadecx left a reply on How To Get Sum Of A Column In This Relation? User > Booking > Booking_items

Alright, I understand. But if that's the case, wouldn't it make more sense to have it as a static function inside the bookings model and not the BookingItem?

public static function getUserBookingCount($userId = null)
{

    $userId = $userId ?? auth()->id();

    // If you use it as a static function you can't use $this variable, so use the model directly
    $sum = BookingItem::whereHas('booking.user', function($query) use ($userId){
            $query->where('id', $userId);
    })->whereHas('booking', function($query){
        $query->where('status', 'confirmed');
    })->sum('item_num');

}


// As per your example in a controller or elsewhere:
$bookingSum = Booking::getUserBookingCount();

grenadecx left a reply on Custom Login And Authentication

Hi there,

Well in the default laravel installation the Auth\LoginController handles the authenthication. And by default it imports the Illuminate\Foundation\Auth\AuthenticatesUsers trait that comes with a bunch of functions.

For example the trait comes with the function below.

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

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

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

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

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

All functions that comes with the trait can be overriden in the Auth\LoginController. So you can do whatever you need there. But the first function is the above one and then it in turns calles the validateLogin function etc.

But I'm not sure I quite understand. If you have a tenants system, wouldn't that system already figure out which database you are working against? and apply that during authentication anyways? I mean all that's really needed is to setup the tenants database connection for the user model before the authentication is taking place?

grenadecx left a reply on Automating Child Insertion From Parent Using Custom UUID

The above function is called when the eloquent model is saved with the $model->save() or ::create. But only during the creation, not when it's being updated. During the save process it fires the creating event and the above function listen to just that. So before it's actually saved it's calling Uuid:generate to generate a new uuid before putting it inside the database.

So if you need that in your child model as well, just add a similar boot function inside that model and it will also listen to itself being created and appends the uuid.

grenadecx left a reply on SQLSTATE[42S02]: Base Table Or View Not Found

It says the table claimfiles table doesn't exist in the main_db database. Have you checked that it does? Maybe you forgot to migrate it?

Check your database and migrations files. If it's named something else you might need to set the protected $table = 'claimfiles'; inside the ClaimFiles model.

grenadecx left a reply on Edit Parent Details - Eloquent Models

You could use an event listener/observer and listen to the eloquent event of the child and if it's changed update the parent to activated. I'm not sure if events are fired if you use the ->update instead of fetching it with find for example and running ->save().

Here's the documentation:

https://laravel.com/docs/5.8/events#introduction https://laravel.com/docs/5.8/eloquent#observers

grenadecx left a reply on How To Get Sum Of A Column In This Relation? User > Booking > Booking_items

I thought it would make more sense to have it on the booking model, because you could

$booking = Booking::find(1);

$sum = $booking->getUserBookingCount();

Putting it inside the BookingItem works as well, but wouldn't it be more logical then to make the function static and enter the booking id and user id:

$sum = BookingItem::getUserBookingCount($booking_id, $user_id);

Either way, if you use the booking id, I'm not sure the user_id would be necessary at all, since you want to get the sum from that booking either way?

grenadecx left a reply on How To Get Sum Of A Column In This Relation? User > Booking > Booking_items

You can use the scope instead. Just replace the

$query->where('status', 'confirmed');
$query->confirmed();

Scopes are called on those models, so when we are in the whereHas booking closure, the scope used there will be on the relationship, in this case the booking model.

grenadecx left a reply on How To Get Sum Of A Column In This Relation? User > Booking > Booking_items

How about something like this:

$sum = BookingItem::whereHas('booking.user', function($query) use ($userId){
    $query->where('id', $userId);
})->whereHas('booking', function($query){
    $query->where('id', $this->id); // Or however you get the booking id
    $query->where('status', 'confirmed');
})->sum('item_num');

grenadecx left a reply on Send Email Verification Link For Custom Registration

    public function sendEmailVerificationNotification()
    {
        $this->notify(new Notifications\VerifyEmail);
    }

The above function is implemeted by the verification system on the User model or the model you use that needs verification. You just need to call that function.

 $user->sendEmailVerificationNotification();

grenadecx left a reply on Send Email Verification Link For Custom Registration

What about the verification process is it that you want to customize?

17 May
2 months 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