Member Since 1 Year Ago

Webdeveloper at Rocketlabs AB

Experience Points 30,050
Experience Level 7

4,950 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
Best Reply Awards 48
Best Reply
  • 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.


    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.


    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.

15 Aug
1 month ago

grenadecx left a reply on Selection To Filter Other Selection

There are a few solutions:

  1. I would make an on change event on the company select, make an ajax request using the company id and then based on that you could get an entire new view with the entire select, populated with all the channels that has company_id and just replace the existing select with that.
  1. If you don't want to make an ajax request, you could reload the entire page when user selects company appending company_id=something and just fetch all the channels for that company if company_id exists, else fetch all channels.
  1. If a channel can only have one company, an easier solution could be to just append data-company-id and just use display:none to hide them and then show them when company is selected, example
<select class="js-tags form-control" name="channels[]" multiple="multiple">
    @foreach($channels as $channel)
        <option value="{{$channel->id}}" data-company-id="{{ $channel->company_id}}" style="display:none">{{$channel->title}}</option>

And then create an onchange event for the company select, and just grap the options and show them where the id matches.

// Quick dirty example
$('select[name=company]').on('change', function(){
    var company_id = $(this).val();
    $('select[name=channels\\[\\]]').find('option').hide(); // hide all options
    $('select[name=channels\\[\\]]').find('option[data-company-id='+company_id+']').show(); // show those with correct company_id

09 Aug
1 month ago

grenadecx left a reply on Scopes Or Traits Or Services Or ... ? How To Clean Up This Code And Make It More Readable ?

You could also create a helper function and then extend blade to use that function. So in the end you would do something like


To create help file and add it using composer:

To extend blade:

05 Aug
1 month ago

grenadecx left a reply on How Do I Create A Unique Session For A User That Is Not Logged In

In laravel, by default all your routes put inside the web.php are using all of the middlewares defined in the "web" middleware group. Under app/Http/Kernel.php you can check:

    protected $middlewareGroups = [
        'web' => [
        // ...

As you can see, the middleware for creating a session is always active, that means even if the user isn't logged in, a unique session for that user has already been created. So you can store and return things from the session using the session() helper function or the Session facade.

It's possible that once you login, the session will be destroyed and a new one is created, I don't remember. If you want to keep the cart, you would need to store in in a variable, allow the session from the logincontroller to run and then readd the cart to the session.

10 Jul
2 months 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
2 months 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:

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


Edit: Actually I realize that might not help because the browser probably don't support backslash in the url. You would need to fix the folder name without the backslash instead.

13 Jun
3 months ago

grenadecx left a reply on Adding A Step Before Registration

I'm glad you worked it out :)

12 Jun
3 months ago

grenadecx left a reply on Adding A Step Before Registration

Auth::routes takes you to:

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) {
        // Email Verification Routes...
        if ($options['verify'] ?? false) {

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 own 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.

The middleware would be fairly basic, kinda like the checkAge in the above page. But instead you check the session variable.

07 Jun
3 months 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

06 Jun
3 months 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.

Chunk isn't the solution to this, it has a different purpose.

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:

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.

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": [
        "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
3 months 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
3 months 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:

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.

Read the docs over there to get started.

31 May
3 months 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.

Edit: Also since it extends the actual "ServiceProvider" you would need to do something like

use Illuminate\Support\ServiceProvider;

// This would give error
class ServiceProvider extends ServiceProvider
// So you would need to do something like
use Illuminate\Support\ServiceProvider as somethingelse;

class ServiceProvider extends somethingelse

Or you would get problem because they are named the same.

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.

Edit: Chunk is also a great way to deal with it, it all depends on where and how you need to use it. Using chunk should save memory allocation for sure, but it will also do a query for each chunk. Kinda like a pagination would do.

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
3 months 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(
        'group_id', // you might need to switch place with this one and the one below
        'refreshments_id', // Can nenver remember how these goes

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_data = $request->getContent();

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

29 May
3 months 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:

24 May
3 months 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 Queue Errors

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.


23 May
3 months 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


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.


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]) }}">{{$discussion->title}}</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.

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
3 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.

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

This will of course, like with yours, not give you any headings 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:

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


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.

// So you could do
auth()->user()->type // This would then get the data from Admin, Donator or Charity table.

// Check for permissions

You can read about polymorhpic relations over here:

21 May
3 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 

Edit: If you need to add the relations, take a look here, using the belongsToMany relation.

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.


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...

Edit: Don't forget to mark the answer if you are satisfied with it working.

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');


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

Edit: Just saw your reply, let me revise my answer...

E.g. if I create that above method inside BookingItem.php, then the query naturally select(*) from booking_items .... so I can do sum() ... however not so sure how to sum when inside Booking.php or even User.php ??

That's because you use the relation $this->. You would need to do it independent and acessing the model directly, like BookingItem::whereHas....

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)

        // 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)) {

            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.

        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:

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');

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.

Edit: Actually I'm not sure what I was thinking. You don't need the whereHas for the booking id if you want for all the bookings. You can remove that completely.

// You can remove this row, unless you want for a specific booking
$query->where('id', $this->id); // Or however you get the booking id

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');

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 MustVerifyEmail interface on the User model or the model you use that needs verification. You just need to call that function.


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
4 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?