drewdan

PHP Engineer at Talkative Ltd

Member Since 1 Year Ago

Newport

Experience Points
58,710
Total
Experience

1,290 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
245
Lessons
Completed
Best Reply Awards
44
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

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

Level 12
58,710 XP
Oct
11
1 week ago
Activity icon

Awarded Best Reply on Get Sub Menu

I am not sure I understand your approach? Can you not just get all of the data in one request? Fetch all of the types and eager load the related models and just store that? And then loop through that, it feels very inefficient to hard code some of the data and then request the results one at a time?

Activity icon

Replied to How To Fix If My Application Is Not Working In Microsoft Edge Browser?

What app is this? I'm guessing you're on about some front end code? Have you compiled and bundled it with something like Webpack to make it compatible with older browsers?

Oct
09
1 week ago
Activity icon

Replied to About Filter Input, Escape Output

What data requires you to save a " in the database? If its required, then fair enough, output it as is.

I dont know a time where you would need a " in a form. Can it be avoided? But then again, I am sure there are many times it would be needed.

Activity icon

Replied to Using Multiple Relationships On User

Oh sorry, without adding an extra coumn on the table? Umm, depends, you could make a polymorphic relationship, so you map the user to a model and an id. But that would limit the user to only be related to a single model, rather than say a restaurant and a hotel.

https://laravel.com/docs/8.x/eloquent-relationships#polymorphic-relationships

Maybe thats what you need?

Activity icon

Replied to Mysql Connection At Edit And Delete Route: Null

You are welcome, glad I could help. You will have to do the same in your show, and update routes too :)

Activity icon

Awarded Best Reply on Mysql Connection At Edit And Delete Route: Null

Change your edit method to this and try again.

public function edit(Tag $tag)
    {   
        dd($tag);
        return view("tag.edit")->with("tag", $tag);
    }

The variable name needs to match the {tag} in your routes.

Activity icon

Replied to About Filter Input, Escape Output

Depends, if that data makes it back into the database and is malicious, it could be bad if it was rerendered as part of the page. I make an effort to never use {!! !!) unless there is a real need for it. So it all depends on the circumstance. I would always use caution when outputting unescaped data though!

Activity icon

Replied to Mysql Connection At Edit And Delete Route: Null

Change your edit method to this and try again.

public function edit(Tag $tag)
    {   
        dd($tag);
        return view("tag.edit")->with("tag", $tag);
    }

The variable name needs to match the {tag} in your routes.

Activity icon

Replied to Mysql Connection At Edit And Delete Route: Null

Ok, excellent, so its just the model route binding that is not working.

Can you run php artisan route:list --path tag and post the output here, and also show me the code you have for your tag migration?

Activity icon

Replied to Laravel Sanctum - Impersonate User

There is a package that enables you to impersonate users:

https://github.com/404labfr/laravel-impersonate

The user guide is pretty good and its easy to use, so maybe consider using this? I have no used sanctum, so I am not sure if this does exactly what you need it too, but I think it probably would :)

Activity icon

Replied to Mysql Connection At Edit And Delete Route: Null

Ok, so that looks good, so after you submit this form, does this line fire correctly:

return $this->index()->with([
            "message_success" => "Der Tag <b>" . $tag->name . "</b> wurde erfolgreich hinzugefĆ¼gt"
        ]);

Do you get redirected to the index page with the correct message? And you can see the tag in the list on the index page?

Activity icon

Replied to Get Sub Menu

I am not sure I understand your approach? Can you not just get all of the data in one request? Fetch all of the types and eager load the related models and just store that? And then loop through that, it feels very inefficient to hard code some of the data and then request the results one at a time?

Activity icon

Replied to Mysql Connection At Edit And Delete Route: Null

Can you show me your create blade file, where you are creating the tag?

Activity icon

Replied to Socialite/Google Login On Public Computer

I am not sure you can, as you authorize with google, the flow would be to log out of Google to end the session. You could redirect the user to Google after they logout? Or put a reminder on the screen to remind them to log out of Google if they are on a public machine.

There seems to be a potential method here: https://laracasts.com/discuss/channels/laravel/socialite-logout - might be worth reading and seeing if it has any merit.

Activity icon

Replied to Service Question

I think what you are looking for is the builder (manager) pattern. Which is commonly used throughouth the codebase in Laravel:

https://designpatternsphp.readthedocs.io/en/latest/Creational/Builder/README.html

Those docs should give you an idea of how to implement it. Its a very useful pattern. Hope that helps :)

Activity icon

Replied to How To Check If A User_id Already Exist?

Haha, that post made my day! :D

Activity icon

Replied to Dynamic Navbar With Menu Items - Active Class

You seem to be mixing the need for curly braces within the @if helper.

 <a class="nav-link {{ Request::is($page->url)) ? active : '' }}" href="{{ URL::to($page->url) }}">{{ $page->title }}</a>

Something like that should work

Activity icon

Replied to Pagination Ajax Filter

If you have a subscription to Laracasts, and use Vue, this is a really useful tutorial to handle pagination with ajax.

https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/38

Activity icon

Replied to Mysql Connection At Edit And Delete Route: Null

The code looks ok to me, are you getting an error message? Or is the data just not saving to your database? Or is the data saving to your database, you just cannot retrieve it?

Activity icon

Replied to Using Multiple Relationships On User

You can add as many relationships to a user as you want, in the future, if you wish to add another, just create a migration to update the table accordingly.

So if a user belongs to a restaurant now, and in the future, maybe they can belongs to a hotel? You could create a migration to add a hotel_id to the user table, and then add the appropriate relations to the user. You can create a new migration with the php artisan make:migration command, and name it something like update_user_table_with_hotel_id

and then in your migration the up() method might look like

public function up() {
    Schema::table('users', function (Blueprint $table) {
        $table->unsignedBigInteger('hotel_id')->nullable();
    });
}
public funcion restaurant() {
     $this->belongsTo(Restaurant::class);
}

public function hotel() {
    $this->belongsTo(Hotel::class);
}

Hope that makes sense :)

Activity icon

Replied to Production.ERROR: No ReaderType Or WriterType Could Be Detected

Iirc, can you not change it too:

public function import(Request $request){
    $request->validate([
        'file' => 'required|max:10000|mimes:xlsx,xls',
    ]);

    $path = $request->file('file');

        Excel::import(new LeavesImport, $path);        
    
     Session::flash('success', 'Leave Records Imported Successfully');
      return redirect()->route('leave.leave_reviews.index_hr');  
  }

I think this should work!

Activity icon

Replied to How To Get Value In Table And Update Has Expired In A Column Of Same Table

Use a mutator on the model

public function getIsExpiredAttribute(): bool {
	return (bool) !$this->quantity; //better check the login on this, but basically make sure it returns false if the value is 0
}

and then you can access it like

$model->isExpired;

which will return a true or false

Activity icon

Replied to Perfect Structure For Coupon Table Laravel

This looks good to me, only worry I would have are the enums, they are not easy to change if you decide to in the future. https://laravel.com/docs/8.x/migrations#modifying-columns enums cannot currently be renamed or changed through the usual methods should you need too. And I agree with @laracoft - best to separate our your migrations to make it clearer what each migration does

Activity icon

Replied to How To Check If A User_id Already Exist?

So, just to clarify, you want to allow users to be able to signup, and if the account already exists, you would just override the account with some new details? Like, say, a password? Surely you would just want the user to be redirected back and tell them they already have an account and should login, or choose a different email for example?

Activity icon

Awarded Best Reply on Call The Methods Of A Artisan Command From A Parent Class

Its due to the way Laravel runs the method. When you run php artisan command:name what you are doing is calling a method which will find the appropriate command, resolve its dependencies, etc. It will then call the handle method and pass that output back to the console.

/**
     * Execute the console command.
     *
     * @param  \Symfony\Component\Console\Input\InputInterface  $input
     * @param  \Symfony\Component\Console\Output\OutputInterface  $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        return (int) $this->laravel->call([$this, 'handle']);
    }

This is the method in the command class which executes the command. Which calls the handle method on the command that you made.

I am not well versed enough to explain fully/well, but at the point the constructor is called, the command has not been fully resolved, and there it does not have access to the methods which write output.

I hope that makes sense!

Activity icon

Replied to Call The Methods Of A Artisan Command From A Parent Class

I dont think I have ever used a constructor in a command. If you need to do logic, I would create a method on the parent class, which the child class can all, effectively making that your constructor, and then call that from the handle method in the child class

Activity icon

Replied to Call The Methods Of A Artisan Command From A Parent Class

Its due to the way Laravel runs the method. When you run php artisan command:name what you are doing is calling a method which will find the appropriate command, resolve its dependencies, etc. It will then call the handle method and pass that output back to the console.

/**
     * Execute the console command.
     *
     * @param  \Symfony\Component\Console\Input\InputInterface  $input
     * @param  \Symfony\Component\Console\Output\OutputInterface  $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        return (int) $this->laravel->call([$this, 'handle']);
    }

This is the method in the command class which executes the command. Which calls the handle method on the command that you made.

I am not well versed enough to explain fully/well, but at the point the constructor is called, the command has not been fully resolved, and there it does not have access to the methods which write output.

I hope that makes sense!

Activity icon

Replied to How To Check If A User_id Already Exist?

https://laracasts.com/series/laravel-6-from-scratch/episodes/25

Jeffrey has an excellent Laravel on the subject, and I believe its free to watch this one too :D

Activity icon

Replied to How To Check If A User_id Already Exist?

You should do some form validation

$data = $request->validate([
'user_id' => 'unique:users,id',
]);

https://laravel.com/docs/8.x/validation

This way you can check directly in the database and laravel will redirect back with the errors to show on your blade file.

Activity icon

Replied to Call The Methods Of A Artisan Command From A Parent Class

the error you are having is because you are doing in the constructor.

$this->info();

This method does not work in the constructor, only in the handle method.

The second approach you used where you extend the abstract class should work if you remove this->info(); also all dependency injection is done through the handle method in commmands rather than the constructor

Activity icon

Replied to Failed To Load Resource (404) > Partly Solved

How are you setting these scripts up? Are you importing them into resources and then compiling them using something like laravel mix? Or are you puttin them directly into the public folder and then trying to reference them that way?

Activity icon

Replied to Should You Go Full-stack Or Only Front End / Backend?

I think full stack is just one of those terms which describe someone that works in both front and back end. I consider myself a full stack developer because my job requires me to work in both front and back end. But my strength is in backend code. I think this is true of many developers, they are full stack but their strength is in one of the other.

Also, back end or front end, things change, stacks improve, etc. I do not believe the end exists, I believe you can become very knowledable but every day is a lesson, even for developers who have been coding for far longer.

Some of the developers I work with are incredible, their knowlege in both backend and frontend stuff is amazing, but by their own admission, they do not know everything, which is why forums such as these exist, so we can reach into the community and keep on learning.

More than anything, I believe its down to personal choice. I think a person should do what they feel most comfortable with and makes sense for them and their personal circumstances.

Activity icon

Replied to How To Append Multiple Imagein FormData?

I agree with @niush - I feel like this would be a better approach for you to take for multiple file upload, unless there is a reason you are keeping each file separate.

Whats confusing me, is you say the first has a response of the file name, and then you have a second response. So it sounds like you are making multiple requests to upload these files, whereas you are setting this up so you can upload the files at the same time?

If not, the error 500 should have left something in your log files as to the reason for the error. I would take a look there.

Activity icon

Replied to How To Append Multiple Imagein FormData?

So you have 11 inputs numbered through 1 to 10 and one without a number.

<input type="file" id="inputProjectImage1">

And you are trying to append them to the form? What happens if you console.log the file1, file2, etc to the console, does it have the value you expect?

Activity icon

Replied to How To Append Multiple Imagein FormData?

Can you show us some more code? How are the file variables being created?

Oct
07
1 week ago
Activity icon

Replied to First Job Struggle

The job I have now is my first proper developers job, the work I did before that was freelance and rather unstructured. If I could go and talk to past me, I would suggest making some small opensource projects to have as a demostration of my skills and then put them up as public repos on github. I think having experience of managing an open source package is really useful.

The other bit of advice I would give myself it to contribute to open source projects where possible. Find a repo with some issues, and then try to solve the issue and make a pull request, even if its just updating documentation. I remember my first PR, it was on a Spatie repo and the feeling of it getting merged was immense, felt really pleased to have contributed to the community. Doing this also helps you get to grips with working in a team on the same codebase.

One last thing, don't lose faith, I was rejected from many roles before landing this one. All it takes is one person to see the potential in you and open that door for you. It took me a while to get where I am, but I am here now and look forward to going to work every day.

Oct
05
2 weeks ago
Activity icon

Awarded Best Reply on UPDATE USER ON THR PROGRESS OF A RUNNING QUEUE

Could you use websockets and broadcast an event every time a mail is sent. The user sits on the front end and it listens for the broadcast and updates the dom accordingly?

https://laravel.com/docs/8.x/broadcasting

Activity icon

Replied to Redirecting Users

@snapey There was a guide for this?! Wish I had found that last week lol

Activity icon

Replied to Error On Login With Jetstream And Socialite

Does your user Model extend the Authenticatable class?

Activity icon

Replied to CypressError Cy.visit() Failed Trying To Load

Looks like your server is responding with an error 500. So the test is hitting the URL, and it does load, but returns a 500 error. Could you take a look into the logs and see what causes the 500 response?

Activity icon

Replied to Laravel 5 - Mail Function

Are there any error logs? Are you able to load tinker? And check the user exists in the database? Make sure it has correctly migrated the data?

Activity icon

Replied to Redirecting Users

I had this issue when playing around with Laravel 8. It seems in Laravel 8, the login responses extend a Responsable contract. To handle this I rebound my own Response methods in the container. So My FortifyServiceProvider looks like:

<?php

namespace App\Providers;

use App\Response\LoginResponse;
use App\Response\RegisterResponse;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use App\Actions\Fortify\UpdateUserProfileInformation;
use Illuminate\Support\ServiceProvider;
use Laravel\Fortify\Fortify;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;

class FortifyServiceProvider extends ServiceProvider {
	/**
	 * Register any application services.
	 *
	 * @return void
	 */
	public function register() {
		$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
		$this->app->singleton(RegisterResponseContract::class, RegisterResponse::class);

	}

	/**
	 * Bootstrap any application services.
	 *
	 * @return void
	 */
	public function boot() {
		Fortify::createUsersUsing(CreateNewUser::class);
		Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
		Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
		Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
	}
}

In it, I am binding the LoginResponse and RegisterResponse contracts into the conttainer. The two responses I am binding in are as follows:

<?php

namespace App\Response;

use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;

class LoginResponse implements LoginResponseContract {

	public function toResponse($request) {
		return $request->wantsJson()
                    ? response()->json(['two_factor' => false])
                    : redirect()->intended(route('admin.index', ['company' => $request->user()->company->domain]));
	}
}

and my register response looks like

<?php

namespace App\Response;

use http\Env\Request;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;

class RegisterResponse implements RegisterResponseContract {
/**
     * Create an HTTP response that represents the object.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function toResponse($request)
    {
        return $request->wantsJson()
                    ? new JsonResponse('', 201)
                    : redirect(route('admin.index', ['company' => $request->user()->company->domain]));
    }
}

There may be a better way to do this, but this worked well for me. And I am implementing the contracts in Laravel rather than ripping anything apart.

You can see in my responses that I am providing the redirect route, in this case, it is redirecting them to an index page which has a subdomain. So every user will be redirected to their own subdomain. But you should be able to adapt this to any logic you require.

Activity icon

Replied to Laravel 5 - Mail Function

Is your env file cached? Can you try running php:artisan config:clear?

Activity icon

Replied to Default User Role On User Create Spatie

Just to add to this, if you wanted to you could create a User model observer, and then on created, assign a role there.

https://laravel.com/docs/8.x/eloquent#observers

So you could have something like

public function created(User $user)
    {
        $user->assignRole('some-role');
    }

This means whenever a new user model is created, a role will automatically be assigned. This could be handy with your tests, so if you used a user factory to create a new user, the observer would fire and add the role.

Both options work fine, but I like the Observer Pattern as it just means slightly cleaner controllers. Only downside is that this pushes the logic out of the flow, so if you did not know the observer was there, you might be a little confused as to what was happening!

Sep
27
3 weeks ago
Activity icon

Replied to Your Requirements Could Not Be Resolved To An Installable Set Of Packages.

If it is this package: https://github.com/andreasindal/laravel-markdown there is a warning the package is no longer maintained and will not support future Laravel packages. Seems support stopped at 5.8. So you will either need to fork the package and update it yourself or find a different package.

Activity icon

Replied to Eager Loading Not Possible

Is that adding an extra query after you remove the $with from the model?

Sep
25
3 weeks ago
Activity icon

Replied to Eager Loading Not Possible

It sounds like you are hydrating the model multiple times. Can you show me your controller code? I have found using $with on the model often causes more issues than it solves, so I would eager load somewhere in the controller using the with() or load() method

Sep
24
3 weeks ago
Activity icon

Replied to Store Value Globally In Controller

Today I learned! I did not know that!

@msslgomez try doing the dd in the place where you need the data and see if appears then

Activity icon

Replied to Store Value Globally In Controller

If you go into your .env file and you should see some entries which define which drivers are using in Laravel, there are some for mail, cache etc:

BROADCAST_DRIVER=pusher
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=600

Mine look like this, because I have a redis instance setup locally. Can you show me what your SESSION_DRIVER is?