Mikegk

Mikegk

Member Since 10 Months Ago

Experience Points
6,240
Total
Experience

3,760 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
48
Lessons
Completed
Best Reply Awards
0
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 2
6,240 XP
Sep
13
1 week ago
Activity icon

Replied to How Resolve Route [verification.verify] Not Define?

Simply add

Route::get('email/verify', 'Auth\[email protected]')->name('verification.notice');

On the bottom of your web.php routes file.

Sep
03
3 weeks ago
Activity icon

Replied to Protected $has = ['something‘] Possible?

(I did not make it clear enough, sorry: I need to get one Post by its ID and I need to assure that there is an relation to a User)

Activity icon

Replied to Protected $has = ['something‘] Possible?

Thank you.

Please tell me what's wrong with

$post = \App\Post::find(1)->has('user')->first()

if I would like to get the Post with ID 1, that has one active User in Relations?

Activity icon

Started a new Conversation Protected $has = ['something‘] Possible?

Hi guys,

I wonder if it's possible to make an Eloquent-Model always involve an existent Relationship. For Example a Post should always have an active User (\App\Post::find(1)->has('user')->first()). Using

protected $with = ['user'];

works.

So is it possible to define the $has like that as well?

Sep
01
3 weeks ago
Activity icon

Replied to Where To Put A Script To Be Called At The Very End?

Great, thank you, that's what I was searching for. A good example / tutorial can be found here https://www.tutorialspoint.com/laravel/laravel_middleware.htm (for anyone who ran into the same question).

Activity icon

Started a new Conversation Where To Put A Script To Be Called At The Very End?

Hi guys,

I wonder where to put a script that needs to be called at the very end of a request?

Just want to make sure it's called when everything else is "done".

I'm glad for any help :). Thanks.

Aug
22
1 month ago
Aug
20
1 month ago
Activity icon

Started a new Conversation Calling Auth()->user() Multiple Times

Hi guys,

one question: How does the auth()->user() helper work when I invoke it? Will it request the database for the current logged in user each time it is called, or is there some kind of storage once I called it (and did not change anything)?

Thank you

Aug
11
1 month ago
Activity icon

Replied to Ignoration Function

Solved it

Activity icon

Started a new Conversation Ignoration Function

Hello,

Im trying to implement some kind of ignoration function for loggedin users.

There is a table called 'user_ignore' which contains: -id -id_user (that's the ID of the user, who set the current entry) -id_foreign (...and the ID of the user who is ignored)

I have got many calls to my User Model, and each User belongs to many different aspects of the site. How can I assure, that a logged in user, will always get a filtered result based on the user_ignore contents?

It's important that the user who ignores, such as the user who is ignored won't "see" each other.

Global Scopes sounded like something I could have used, but I do not really know how to "join" data there - and if it's even possible.

Does anyone has an Idea how to deal with that Problem?

Thank you very much for any help.

Activity icon

Awarded Best Reply on Changing The Default Hash Comparsion Method

No. Question was totally correct, your interpretation without necessary information was not. ...I won't continue that any further because it's senseless. Maybe you did your best to be emphatic...

Whatever, for anyone who ran into the same question, this solution might help:

Within the LoginController (Controllers/Auth/LoginController.php) you can add something like that

protected function attemptLogin(Request $request)
    {
        $user = \App\User::where([
            'email' => $request->email,
            'password' => md5($request->password)
        ])->first();

        if ($user) {
            $this->guard()->login($user, $request->has('remember'));
            return true;
        }

        return false;
    }

to perform a login with MD5 hashes.

An attempt to upgrade Real Users to have their credentials saved using Laravels standard hashing-function can look like that:

protected function attemptLogin(Request $request)
    {

        $user = \App\User::where([
            'email' => $request->email
        ])->first();

        $logged_in = false;

        if ($user) {
            //Try MD5 match
            if (!$user->new_hash_set) {
                if ($user->password === md5($request->password)) {
                    $user->password = Hash::make($request->password);
                    $user->new_hash_set = true;
                    $user->save();
                    $logged_in = true;
                }
            } else { // Try 'standard' Hash match
                if ($user->password === Hash::make($request->password)) {
                    $logged_in = true;
                }
            }
        }

        if ($logged_in) {
            $this->guard()->login($user, $request->has('remember'));
            return true;
        }

        return false;
    }

Please make sure to upgrade the database and set the password field to be 'VARCHAR' and 191 characters long. Also add some control column such as "new_hash_set" which can be something like 'TINYINT' with a length of 1.

Note: This is a very basic attempt which of course might be improveable.

Activity icon

Replied to Changing The Default Hash Comparsion Method

No. Question was totally correct, your interpretation without necessary information was not. ...I won't continue that any further because it's senseless. Maybe you did your best to be emphatic...

Whatever, for anyone who ran into the same question, this solution might help:

Within the LoginController (Controllers/Auth/LoginController.php) you can add something like that

protected function attemptLogin(Request $request)
    {
        $user = \App\User::where([
            'email' => $request->email,
            'password' => md5($request->password)
        ])->first();

        if ($user) {
            $this->guard()->login($user, $request->has('remember'));
            return true;
        }

        return false;
    }

to perform a login with MD5 hashes.

An attempt to upgrade Real Users to have their credentials saved using Laravels standard hashing-function can look like that:

protected function attemptLogin(Request $request)
    {

        $user = \App\User::where([
            'email' => $request->email
        ])->first();

        $logged_in = false;

        if ($user) {
            //Try MD5 match
            if (!$user->new_hash_set) {
                if ($user->password === md5($request->password)) {
                    $user->password = Hash::make($request->password);
                    $user->new_hash_set = true;
                    $user->save();
                    $logged_in = true;
                }
            } else { // Try 'standard' Hash match
                if ($user->password === Hash::make($request->password)) {
                    $logged_in = true;
                }
            }
        }

        if ($logged_in) {
            $this->guard()->login($user, $request->has('remember'));
            return true;
        }

        return false;
    }

Please make sure to upgrade the database and set the password field to be 'VARCHAR' and 191 characters long. Also add some control column such as "new_hash_set" which can be something like 'TINYINT' with a length of 1.

Note: This is a very basic attempt which of course might be improveable.

Aug
10
1 month ago
Activity icon

Replied to Changing The Default Hash Comparsion Method

I was offended with "[...]you should have a severe word with yourself about the respect you give to your users", without knowing what I do, and if there are any users. Where did he take that information from? Does he know me? Does he know about my personal thoughts of responsibility just by reading this topic?

My answer is rude because I do not want to be told to show respect to users although nobody knows if there is any user on my project? Sorry man, I'm not with you in this point.

And yes: I do appreciate the thoughts, work and decisions laravels developers make for us. But again: Who said that I did not use the technique? This is just a special case. No need to worry, but thank you anyway.

To shorten things up a little: This is just a question. Im fine if I do not get an answer, but please do not judge me for something none of you can assess. Sorry if anyone feels attacked...

Activity icon

Replied to Changing The Default Hash Comparsion Method

...well first of all thank you.

I do respect users, and I also said that I already know about the deprecation. Your answer sounds very offensive to me - Im not a murder, I did not commit any crime so please have a severe word to yourself about respect to other users on that board! Just because I want to know how to change the algorithm / authentification method and understand how the Auth::attempt method works doesn't make me a bad person.

What if the project doesn't hast anything todo with live data and / or live users?! I did not gave any details to my project...

But thank you for your time!

Activity icon

Started a new Conversation Changing The Default Hash Comparsion Method

Hi guys,

I know that's something nobody would suggest because MD5 is more than deprecated and might end up in collisions but for the current project it is necessary.

The question is, how can I get the system Login method, to NOT use it's hash algorithm on login? I would like to use MD5(request('password')) instead.

I already looked at https://laravel.com/docs/7.x/authentication#authenticating-users (Manually authentification) but there was no info about changing the hash algorithm (I do not want to change the config/hashing.php because I will use the bcrypt hashing method later).

Within the AuthenticatesUsers Trait I localized the following Method

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 (method_exists($this, 'hasTooManyLoginAttempts') &&
            $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);
    }

...and it looked like this would be the corresponding part

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

...so all there is to do, is telling "attemptLogin" to compair MD5(request('password')) with users.password (and the e-mail of course), right?

Following the attemotLogin Method, I end up here:

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

...well and that's where it leads me to the Auth-Class. Neither a login nor attempt Method :(...

Would be very happy for any help.

Aug
07
1 month ago
Activity icon

Replied to Relationship Problem

It works with:

$category['categoryData']->first()->file_1

and also with

$category['categoryData'][0]->file_1

and even with

$category->categoryData->first()->file_1

...why? What is correct?

Activity icon

Replied to Relationship Problem

Okay that works - but I cannot access the categoryData. Within a foreach loop I iterate over $categories and receive single $category Objects. Those contain categoryData-Relation Objects (some of them). How can I access them? I tried:

$category->categoryData

and also

$category['categoryData']

Im a little confused right now because gettype says its an array ?! I just want to receive the first entry under:

category_data

Activity icon

Replied to Relationship Problem

I did

$categories = Category::where(['status' => 1])
            ->with(['categoryData' => function ($q) {
                $q->whereHas(['user' => function ($sub) {
                    $sub->where('status', 1);
                }])
                    ->where(['status' => 1, 'kind' => 'header'])
                    ->limit(1);
            }])
            ->get();

And get

Error
Call to a member function getRelationExistenceQuery() on array
Activity icon

Replied to Relationship Problem

Ahh... great. I did this es few seconds ago:

$categories = Category::where(['status' => 1])
            ->with(['categoryData' => function ($q) {
                return $q->where(['status' => 1, 'kind' => 'header'])
                    ->with(['user'=>function($q2){
                        return $q2->where(['status'=>1]);
                    }])
                    ->limit(1);
            }])
            ->get();

I try your solution! Thanks!

Activity icon

Started a new Conversation Relationship Problem

Hi guys,

I just faced a relationship problem.

I have got a "Category" Model that has many CategoryData (entries). One CategoryData belongs to the Category Model and it also belongs to a User.

The question is, how can I make sure, that only CategoryData with active users (user.status = 1) will be returned?

That's my try

$categories = Category::where(['status' => 1])
            ->with(['categoryData' => function ($q) {
                return $q->where(['status' => 1, 'kind' => 'header'])
                    ->limit(1);
            }, 'categoryData.user' => function ($q) {
                return $q->where(['status' => 1]);
            }])
            ->get();

...but that doesn't really work.

I would by glad for any ideas.

Jul
31
1 month ago
Activity icon

Started a new Conversation Linking An Existing User Table With Laravels Auth / User System

Hey guys,

I'm trying to upgrade an existing project to Laravel. Therefore I just picked the database structure and now I'm making Models and try to re-built each process... One thing figures out to be a problem: The users Authentification. It's an old system and a "user" table is already existing also the registration process. How do I make Laravel / Auth work with that? The password creation is also not the same process. How can I implement the current "user" table to be used with Laravels Auth System / Methods etc. and how can I ensure that passwords will be set using the "old" system process (because they are saved that way right now).

Would be happy for any advice.

Thanks.

Jul
29
1 month ago
Activity icon

Replied to Custom.js To Be Required Or Chained On Mix?

...yes indeed it does, thanks.

I wonder if I can call functions located in mixed files elsewhere in my code because I cannot find them by search inside the compiled file:

testit(){
 alert("TEST COMPLETED");	
}

"testit(" was not found in app.js :/

Activity icon

Started a new Conversation Custom.js To Be Required Or Chained On Mix?

Hello,

I just want to include a javascript file (which also contains jquery) to the compile list of mix. For my understanding there are at least two ways for that.

  1. Chaining the file to the mix Object like so:
mix.js('resources/js/app.js', 'public/js')
    .js('resources/js/custom.js','public/js')
    .sass('resources/sass/app.scss', 'public/css');
  1. Adding an require Command to app.js like so:
require('./bootstrap');
require('./custom');

Is this correct? I would like to have one mixed file. Chaining doesn't really work since its making a new file.

How do you do it - what are common ways to include / mix custom javascript Code? I would not put the file into the public/ directory to access it there manually. If there is a way to compile and "uglify" the code, it would be perfect.

Jun
09
3 months ago
Activity icon

Started a new Conversation Private Channels Won't Work

Hey guys,

I just setup the laravel-websockets on my server. Now I got stuck on the change from regular to private channels (yes I know that presence channels are also nice and offer some more features, but at the moment I want to go with private channels).

So here are the files I use


//App\Events\ConversationEvent.php

namespace App\Events;

use App\User;
use App\Conversation;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class ConversationEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;
    public $id_conversation;

    /**
     * Create a new event instance.
     *
     * @return void
     */
//    public function __construct(Conversation $conversation)
    public function __construct(User $user,$id_conversation)
    {
        $this->user = $user;
        $this->id_conversation = $id_conversation;
//        $this->dontBroadcastToCurrentUser();
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('Conversation.1');
    }
}

//routes\channels.php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('Conversation.{id}', function ($user, $id) {
    return true;
//    return (int) $user->id === (int) $id;
});

And the view simply looks like so

window.Echo.private('Conversation.1').listen('ConversationEvent', (e) => {
	console.log(e);
});

Everything is correctly set up I guess. If I change the Echo.private method to Echo.channel, I can see a connection in the console on "Conversation.1". If I switch back to Echo.private, It doesn't seem to work.

It's also not possible to trigger an Event through a basic route such as:

Route::get('/event',function(){
   event(new App\Events\ConversationEvent(Auth::user(),1));
});

The console doesn't display that event.

If it's important to know: I do use SSL, but Im not sure if that makes a difference here. And I also use the local "laravel-websockets" Library that simulates pusher as broadcaster.

Would be happy for any help.

Activity icon

Commented on Presence Channels

It's just exactly whats beeing taught in this Episode. Simply watch and learn ;).

Apr
29
4 months ago
Activity icon

Replied to Confusion About The Storage Path

Ah, yes you are right - my fault. It was never necessary to add "public" to the path, so of course files will be available under "/storage"... Thank you :).

Activity icon

Started a new Conversation Confusion About The Storage Path

Hi guys,

I just used the Storage engine for the first time in my Laravel 6 project. After reading the documents, I created the symlinks using

	php artisan storage:link

But I do not really understand the behaviour: The Symlink is created between

	app_root/storage/public

and

	app_root/public/storage

that's what the "filesystems.php" says:

'links' => [
        public_path('storage') => storage_path('app/public'),
    ],
	

So we could expect placing a file in the storage folder, should make it visible for web users like so:

	https://appname.com/public/storage/some_file.jpg

right?

But it doesn't. Instead you can visit

	https://appname.com/storage/some_file.jpg

and get the image.

Why is that? Is this correct?

Apr
22
5 months ago
Activity icon

Replied to Chain-break Eloquent Methods

Both great answers! Thanks guys.

Activity icon

Started a new Conversation Chain-break Eloquent Methods

Hi guys,

I just wanted to create an Eloquent Query and some parts of it should just be applied to the filters if certain parameters are set

$model = MyModel::with('tasks','projects')
->where('active',1);
if($param1){
$model->where('something',$param1);
}

$model->get();

Sadly that doesn't work. I also can neither use MyModel->where(...) nor MyModel::where(...) to continue...

Any ideas?

Apr
14
5 months ago
Activity icon

Awarded Best Reply on Getting Last 25 Records From ASC Ordered List

...I did a work around using DESC sorting and

	array_reverse($res)
Activity icon

Replied to Getting Last 25 Records From ASC Ordered List

...I did a work around using DESC sorting and

	array_reverse($res)
Activity icon

Replied to Getting Last 25 Records From ASC Ordered List

Hey guys,

thanks for reaching out. I tried both of your advices without success 😩... Is it somehow possible to fire a subquery? Negative values within take won't work - and for my understanding, the only difference between take() and limit() is, that take() works on Collections and ORM Objects as well.

Let's say I have an Array with 10 entries, and the Limit is 5 Rows, the following list should appear:

6,7,8,9,10

Activity icon

Started a new Conversation Getting Last 25 Records From ASC Ordered List

Hi guys,

sounds pretty easy and can be done via Subqueries, but currently I do not find a way to get an eager loaded property beeing limited to 25 in ASC order.

	//My try
	$model = SomeModel::with(['someProperties'=>function($q){
		$q->limit(25)
		    ->orderBy('created_at','ASC');
		/*
		* How to perform a subquery here - or how to take the last 25 Entries :/ ?!
		*/
	}])->get()
			

I just found a way to inverse sort the query with

SELECT * 
FROM (SELECT * FROM comments
      WHERE postID='$id' 
        AND state='0' 
      ORDER BY id DESC 
      LIMIT 3) t
ORDER BY id ASC;

...but I don't know how to implement that using Eloquent. Is there a more elegant way?

Mar
27
5 months ago
Activity icon

Replied to Update Eloquent Data

...indeed! I find "result()" as a set of results and "row()" as one specified row much better then get() and first().

Activity icon

Replied to Update Eloquent Data

Just for my understanding, is it comparable to Codigniter's ->row() and ->result() ? Because in that case I would be able to do something like:

$user_status = UserStatus::getUserStatusById($id_user,$select);
        $user_status = $user_status[0]; //Select an entry...
        $user_status->something = 1;
        $user_status->save();

...right?

Activity icon

Replied to Update Eloquent Data

Thank you very much!!!

Activity icon

Started a new Conversation Update Eloquent Data

Hi Guys,

within an model (UserStatus), I have the following method:

private static function getUserStatusById($id_user,$select='*'){
        return UserStatus::where('id_user',$id_user)
                            ->select($select)
                            ->limit(1)
                            ->get();
    }

This results the wanted row as it should. But I wonder why I cannot change the data inside the model:

someMethod(){
...
$user_status = UserStatus::getUserStatusById($id_user,$select);
        $user_status->something = 1;
        $user_status->save();
}

...Results in: "Method Illuminate\Database\Eloquent\Collection::save does not exist."

Using

$user_status = UserStatus::find(1)
$user_status->something = 1;
$user_status->save();

...works fine. Why?

Mar
24
6 months ago
Activity icon

Started a new Conversation Controller And Model Names...

I seriously ran into that question many times: What is the correct and suggested name of a controller and a model? I read several articles where its said that controllers should be written in

-Camel case -Singular

For Example: UserController

The Model also should named that way:

-Camel case (if necessary) -Singular

For Example: User, UserData

Jefrey Way used to name his controllers "ArticlesController" within his screencast.

What is suggested? Or is it a matter of taste? Of course /article/ sounds not good at all if showing multiple entries whereas /articles/ sounds much better and more sensible.

Activity icon

Commented on Layout Pages

This whole series is awesome. Jefrey is a great teacher and it is easy listening and understanding what he says. Thumbs up :).

Mar
20
6 months ago
Activity icon

Started a new Conversation Separated Npm Module

Hi guys,

short question: When Im using an "npm install PACKAGE" command, the package will be installed within the node modules directory. How can I access it afterwards? I don't want Laravel to mix it up because I will just need to use it on one subpage. Is there a clean workflow for that? Can I automatically create multiple .mix files - separated from the app.js file? How would you do it?

Thank you so much and please stay healthy 😊✌🏻