kaju74

kaju74

Member Since 4 Years Ago

Experience Points 15,045
Experience Level 4

4,955 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 211
Lessons
Completed
Best Reply Awards 0
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.

22 May
3 months ago

kaju74 left a reply on Mail::to(...) Is Sending To All Recipients??

Okay - I'll found the problem:

I've created an instance of the Mailable-Class like:

$mail = new MyMailable();

and use this to send the mail:

Mail::to($user, $mail);

This way, the recipients are appended in the Mail-Class each time and the last mail got all previous send email addresses...

kaju74 started a new conversation Mail::to(...) Is Sending To All Recipients??

Hi,

I've created a newsletter command to be able to send something to all registered users. I'm using a loop to send queueable mailables like this (Laravel 5.6):

foreach ($users as $user) {
  Mail::to($user)->send($mail);
}

But now, every user got's a lot of mails and on every mail a new iterated loop user is attached to the receipient list!!!!! Can anyone tell me, why this happens?

Thank you, kaju

06 Mar
6 months ago

kaju74 started a new conversation Respect DSGVO / GDPR Using FCM For Push Notification?

Hi,

I've created a cardova app for iOS & Android using PhoneGap Push Plugin to be able to receive push notifications & implemented a ServiceController on my Laravel backend to send this pushes. The mobile app registrers the device & receives a token which will be send to my backend & bundled with the authenticated user. This way, I'm able to send individual pushes to single devices running my app. So far so good. If the user logouts on my mobile app, the push service will be unregistered. The user is also able to manage all registered devices through the backend. This way, he can delete a device (which was sold or has been damanged) from the list. To respect the DSGVO / GDPR laws, I need to delete all informations stored by FCM for this user. I took a look at the FCM documentation and recognized a FCMobject where it's possible to delete all data using an "instance id". But how to implement this on my laravel backend? And: is the "instance id" is the same as the registered device token?

Regards, kaju

02 Nov
10 months ago

kaju74 left a reply on Timestamp Unix Millenium Bug Y2K38

You're all right ;-) I've noticed this problem today only, cause a colleque has tested my app to plan future absences (due a calendar select) and this item doesn't appear in the overview list (it was dated to 00.00.0000). That's why I've took a look at the code what happens - and I've read about the known Y2K38 bug in MySQL....

kaju74 started a new conversation Timestamp Unix Millenium Bug Y2K38

Hi,

I've a problem with using timestamp for date related fields in my laravel app. Based on laravels implementation for the default database fields "created_at" and "updated_at", I'm using timestamp for all my other fields...but today I've noticed the so called Y2K38 bug: The last possible timestamp is 2038-01-19. Well, I've 20 years to fix this, but why laravel still used timestamp instead of datetime?

Regards, kaju

23 Jun
1 year ago

kaju74 started a new conversation Prevent From Vector Sql Injections If Using REGEXP For Eloquent Calls?

Hi,

I'm not sure, if Laravel protects me from a SQL injection if using the following code snippet to search for whole words:

$query->orWhere($column, 'REGEXP', '[[:<:]]' . $search . '[[:>:]]');

A better way seems to use an :attribute like this:

$query->orWhere($column, 'REGEXP', '[[:<:]]:search[[:>:]]');

...but I don't know how to use it the right way.

Or: Does Laravel is save enough using "$seach" is the first expression?

Thank you, Marc

30 Mar
1 year ago

kaju74 left a reply on How To Dynamically Access An Object Property?

Okay, so this is maybe not the best way to solve my problem. But, is there a better way to make this kind of stuff dynamically? I've created a simple @checkbox blade directive declared in the AppServiceProdiver:

Blade::include ('includes.form.checkbox', 'checkbox');

This include file look like:

<div class="field">
    <div class="ui fluid basic label">
        <div class="ui checkbox">
            <input type="hidden" name="...">
                   {{ HTML::checked(optional($b)->$v) }} value=1>
            <label>{{ $l ?? '[MISSING LABEL]' }}</label>
        </div>
    </div>
</div>

In my form, this include is called like:

@checkbox(['b' => $user, 'l' => 'Antwort auf einen meiner Kommentare', 'v' => 'settings->notifications->comments', 'op' => true])

So I pass the name of the property of the binded class (i.e. $user) and wonna include the "checked" attribute, if the value is true.

Regards, Marc

29 Mar
1 year ago

kaju74 left a reply on How To Dynamically Access An Object Property?

I‘ll try that out. Thank you. It‘s for a dynamic form builder i.e. dynamic checkboxes. I‘m using objects directly casted through Laravel from the database to be able to use the new optional helper instead of using multi-if conditions in the blade template as well as having consequent writing paradigm through the whole app.

Accessing JSON inside a where-clause also uses the -> instead of array-dot-notation.

Marc

kaju74 started a new conversation How To Dynamically Access An Object Property?

Hi,

I'm using a MySQL JSON-Column inside Laravel to store all my user settings. This variable is casted to an object inside my model ($casts = [...]). So I can access a value like this:

Auth::user()->settings->notifications->comments

I can read & write this without any problems while hardcoding this...but is there a PHP-way to access this property using a variable?

My variable looks like this: $n = 'settings->notifications->comments'

And I've tryed:

Auth::user()->$n

...as well as...

Auth::user()->{$n}

...but nothing works. Any idea here?

Thank you, Marc

14 Feb
1 year ago

kaju74 left a reply on LV5.6: Queued, System Generated Emails?

Hi.

Thank you - I've implemented my own notification class now with ShouldQueue trait to be able to fit my needs. I thought, there's a configuration maybe to enable queueing for Laravels own notifications, but after taking a deeper look to it's implementation, I found the necessarry method to override (inside my user model):

public function sendPasswordResetNotification($token)

Regards, Marc

kaju74 started a new conversation LV5.6: Queued, System Generated Emails?

Hi,

I've switched to Laravel 5.6 (coming from 5.1) and noticed, that we have new notifications & mailable classes. By default, Laravel uses notifications to send an email for a password reset. How to configure Laravel, that this kind of messages will be also using a worker queue? My background worker is running and working for my own (ShouldQueue) mailable classes, but system mails aren't using the queue?!?!

Regards, Marc

01 Feb
1 year ago

kaju74 left a reply on Tell PHPStorm To Type Hint An Extended Class?

That's exactly what I've searched for ;-) Works like a charm...

Thank you, kaju

kaju74 left a reply on Tell PHPStorm To Type Hint An Extended Class?

Hi,

the IDE-Helper is already installed. I've found a workaround, so PHPStorm is able to recognize the underlying user class:

    public function toArray($request)
    {
        /** @var User $this */
        return [
            'first_name' => $this->first_name,
            'last_name'  => $this->last_name,
            'systems'    => optional($this->profile)->system_list,
        ];
    }

Regards, kaju

31 Jan
1 year ago

kaju74 started a new conversation Tell PHPStorm To Type Hint An Extended Class?

Hi,

I've followed the Laracast videos about all the Laravel 5.5 news and played with the new Resource classes. So I created something like this:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

/**
 * Class UserResource
 * @package App\Http\Resources
 */
class UserResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'first_name' => $this->first_name,
        ];
    }
}

Is there any way to tell PHPStorm, that the class "UserResource" is reflecting the model "App\User", so the type hinting inside the "toArray(..)" method works?

Currently, the line "$this->first_name" will be underlined by PHPStorm...

Regards, kaju

08 Feb
2 years ago

kaju74 started a new conversation Image:make(request->file)...resize(...)->save() & Exif Informationen...

Hi.

I've a problem using intervention image to upload a file, manipulate it and store it on the server. As soon as I use Image:make(...)->save(...), all exif-informations of the original file were lost.

Is there any way to prevent Image::xxx from deleting the exif informations?

Thank you, Marc

29 Dec
2 years ago

kaju74 left a reply on Skip Storing Previous Url For Selected Routes?

Yes, but I don't know what the previous route is ;-) The above situation is just an example. The are many pages with images and it should be always possible to return back to the refered one.

I've played with the several web middlewares, but it seems it's not a middleware which stores the called route.

Just to make it clear:

  1. Route is "homepage" (this is what to store for back()!)
  2. Homepage loads a set of images (through media routes)
  3. Each called route will be stored as the last one!

So the last route isn't "homepage" (or whatever page is called first!) - instead, it's the route the last loaded image!

So I'm searching for a technic to prevent storing the called route for images.

kaju

kaju74 started a new conversation Skip Storing Previous Url For Selected Routes?

Hi,

does anyone knows a solution how to skip storing a route call to the session?

Let's say, I'm rendering a webpage with images which are sub calls to a media controller. So the first call the that page is "http:/.../homepage" while the last network call is "http://.../media/images/1".

The problem is, that a call to "back()" (i.e. redirect()->back()) will redirect to that image instead to the homepage.

How do I prevent Laravel from storing route calls (internal to "_previous.url")?

Thank you, kaju

14 Jun
3 years ago

kaju74 left a reply on How To Change Email Template For Password Resets?

Perfect - this is, what I've looked for ;-) Thank you...

Marc

13 Jun
3 years ago

kaju74 started a new conversation How To Change Email Template For Password Resets?

I'll try to change the $emailView used in "PasswordBroker.php" to send out an email for password resetting. The view will be passed inside the constructor of the broker, but how do I change view used?

As in previous versions before, I'm trying to modify the PasswordController to change that path, but don't know how. The broker will use "resources/views/auth/emails/password.blade.php" - but all my email views are in "resources/views/emails", so it would be nice to put the password reset view in that folder, too!

Regards, Marc

18 May
3 years ago

kaju74 left a reply on ICal Provider For Laravel 5.3?

Sorry. It's a typo. I mean 5.2 8-)

kaju74 left a reply on ICal Provider For Laravel 5.3?

Hi...

...just for it's simplicity ;-) So I'll write it my own...which package did you use?

Thank you, Marc

kaju74 started a new conversation ICal Provider For Laravel 5.3?

Hi.

Is there an actual package to be able to render data in iCal (and other) formats? Found only native PHP packages w/o service providers for Laravel...

Thank you, Marc

04 May
3 years ago

kaju74 left a reply on Get Latest Records Ordered By Date?

thanks. I'll try that out asap

kaju74 left a reply on Get Latest Records Ordered By Date?

...that's what I've tryed but I can't figured out the correct syntax...8-(

Regards, Marc

kaju74 left a reply on Get Latest Records Ordered By Date?

Okay, it seems, I found a solution:

        $publications = $query
            ->where('user_id', $user->id)
            ->where('start_at', '>=', Date::now()->startOfWeek())
            ->orderBy('start_at', 'asc')
            ->orderBy('created_at', 'desc')
            ->get()
            ->groupBy(function ($item) {
                return substr($val = $item['start_at'], 0, strpos($val, ' '));
            })
            ->pluck(0);

...but, is there's a smarter way to do this? Marc

kaju74 left a reply on Get Latest Records Ordered By Date?

Hi,

thank you for the quick answer, but this only calls a simple "$this->orderBy($column, 'desc')" and doesn't return the latest row of EACH week...

Marc

kaju74 started a new conversation Get Latest Records Ordered By Date?

Hi, I've a problem getting the latest records of a tables ordered by another column.

So, here are some demo records:

"user_id";"start_at";"end_at";"target";"actual";"delta";"balance";"data";"created_at"
"113";"2016-05-02 00:00:00";"2016-05-08 23:59:59";"39,5";"39,5";"0";"0";"data";"2016-05-04 12:25:11"
"113";"2016-05-02 00:00:00";"2016-05-08 23:59:59";"39,5";"39,5";"0";"0";"data";"2016-05-04 12:23:32"
"113";"2016-05-09 00:00:00";"2016-05-15 23:59:59";"39,5";"39,5";"0";"0";"data";"2016-05-09 12:58:01"
"113";"2016-05-09 00:00:00";"2016-05-15 23:59:59";"39,5";"39,5";"0";"0";"data";"2016-05-04 12:25:11"
"113";"2016-05-09 00:00:00";"2016-05-15 23:59:59";"39,5";"39,5";"0";"0";"data";2016-05-04 12:23:32"

I want to get only the latest created records (created_at) from every available week (start_at). As you can see, there are two records for the week from 2016-05-02 and three records for 2016-05-09. The final result should be:

"user_id";"start_at";"end_at";"target";"actual";"delta";"balance";"data";"created_at"
"113";"2016-05-02 00:00:00";"2016-05-08 23:59:59";"39,5";"39,5";"0";"0";"data";"2016-05-04 12:25:11"
"113";"2016-05-09 00:00:00";"2016-05-15 23:59:59";"39,5";"39,5";"0";"0";"data";"2016-05-09 12:58:01"

How do I write the eloquent query for this? I've tryed several things, but nothing works 8-(

Thank you very much, Marc

P.S.: I know, one 'created_at' date is in the future ;-)

07 Mar
3 years ago

kaju74 started a new conversation Best Way To Share API Methods With Controllers?

Hi.

I'm just thinking about the "best practice to share API methods with controllers" and end up with the following:

  1. Create a helper class which be be boot-loaded (composer.json)
  2. Implement all sharing methods inside this class
  3. Use this class in the model controller as well as inside the api controller

This works fine, but is there a better way to do this?

Example: I've a search method which returns all results as json. This method is used in the UI as well as part of the API which can be called external. Don't want duplicate code for that...

Regards, Marc

kaju74 left a reply on How To Get Auth User On Ajax Call?

No problem - is wan't clear ;-) Well, I'll try to seperate this from my API..

06 Mar
3 years ago

kaju74 left a reply on How To Get Auth User On Ajax Call?

And exact this seems to be the problem cause I made the call to the API route. Hmm. I need this call from inside the app as well as from outside through my API (protected by an JWT). What's the best way to set this up?

kaju74 left a reply on How To Get Auth User On Ajax Call?

Yes - but this will be null, due of the ajax call to the backend. So it seems, if the backend route will be called through an ajax call, the Auth:user() is empty.

kaju74 started a new conversation How To Get Auth User On Ajax Call?

Hi.

I'm trying to implement a simple "I like this" functionality to be able to let users like articles. So the ajax call will pass the corresponding article id to the backend....but how does the backend knows, which (authenticated) user makes that call? I don't want to include the user id in the request...so the backend should use the user currently logged into the system.

Does anyone knows how to do that?

Thank you, Marc

kaju74 started a new conversation Redirect()->back After Ajax Calls?

Hi.

I'd run into a problem using "redirect()->back" after my page has lazy-loaded images while displaying:

I have a page with a lot of images which are loaded as soon as they scrolled into the viewport. So while scrolling, I made a background ajax call to replace the img-src with the real image data. This works fine so far. Now, I've included a language switcher which can be called everywhere in my app using the following url:

http://xxxx.de/lang/de

This will setup the new language and should redirect back to the original page. But, if I use redirect()->back, the url will be redirected back to the latest ajax-call instead of the latest real url.

How do I solve this?

Thank you, Marc

27 Feb
3 years ago

kaju74 left a reply on Route, Use The Same Controller In Laravel 5.2

Hi.

If you don't want to replace your code (e.g. if you've a lot of API methods), you can use this little helper function:

class API
{
    /**
     * Register public API routes
     *
     * @param $uri
     * @param $controller
     */
    public static function register($uri, $controller)
    {
        // define allowed verbs
        $verbs = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'];

        // define possible wildcards
        $wildcards = '/{one?}/{two?}/{three?}/{four?}/{five?}';

        // iterate through all public methods
        foreach ((new ReflectionClass('App\Http\Controllers\\' . $controller))->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {

            // check for valid classes & allowed verbs
            if ($method->class != 'Illuminate\Routing\Controller' && Str::startsWith($method->name, $verbs)) {
                // split method name into individual parts
                $segments = preg_split('#([A-Z][^A-Z]*)#', $method->name, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

                // create matching route
                Route::match($segments[0],
                    $uri . '/' . Str::lower(implode('-', Arr::except($segments, '0'))) . $wildcards,
                    $controller . '@' . $method->name
                );
            }
        }

        // add fallthrough route
        Route::any($uri . '/{_missing}', $controller . '@missingMethod')->where('_missing', '(.*)');
    }
}

Then, just replace "Route::controller" with "API::register", or whatever name you've choosed for ;-)

Best regards, Marc

12 Feb
3 years ago

kaju74 left a reply on After Some AJAX Requests TokenMismatchException

Hi.

Not sure, if this helps, but I always include token setup in my app.js like this:

/* Setup ajax token */
$.ajaxSetup({
    headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
});

Ooops, this part was linked above - sorry for double posting...

Regards, kaju

kaju74 started a new conversation Using Lity W/ Base64 Encoded Image Data

Hi.

I've looked the "Make a flyer" series and added Lity to my project with works fine as long as my images referenced with physical files. Then, I've added two new variables to my controller to deliver the thumbnal and large image as base64 encoded data which works fine for the thumbnail, but as soon as I click on it, the Lity lightbox will opened and shows the large image, but the box isn't scaled to fit the dimension - instead, it is opened with full width & height. So it seems, Lity can't handle image data propertly.

Do you have any idea how to solve this?

Thank you, kaju

17 Sep
3 years ago

kaju74 left a reply on User E-mail Confirmation On Signup.

Hi.

You can also overwrite the 'authenticated' method your AuthController:

    protected function authenticated(Request $request, User $user)
    {
        if (!$user->active) {
            Auth::logout();

            return redirect($this->loginPath())
                ->withInput($request->only($this->loginUsername(), 'remember'))
                ->withErrors([
                    'active' => trans('validation.inactive'),
                ]);
        }

        // set flash message
        Flash::info(Lang::get('user.login'));

        // redirect to...
        return redirect()->intended($this->redirectPath());
    }

I simply use a new 'active' field in the user table migration like:

$table->boolean('active')->default(false);

Best regards, Marc

kaju74 started a new conversation Proceeding Incoming JSON - The Right Way?

Hi.

I'm building an API server with laravel and everything is fine right now. I'm now at a point, where I had to proceed an incoming nested JSON structure, validate it, extract single objects/classes and update the internal database. Before implementing this logic the wrong way, I like to ask you, what's the best pratice to handle incoming JSON data? Which helpers may exists in Laravel??

Currently, I've tested two ways:

/**
 * Transfer request data to StdClass
 */
$data = json_decode(Request::getContent());

foreach ($data->weeks as $week) {
    try {
        foreach ($week->days as $day)
            $out .= $day->name;
    } catch (Exception $e) {
        // catch access errors!
    }
}

Here I'm using the transformed data to interact using a StdClass. But, I had to catch all errors, if I try to access an non-existing class member (if the passed json structure isn't valid!).

My other solution:

/**
 * Transfer request data to parameter bag
 *
 * @var ParameterBag $data
 */
$data = Request::json();

foreach ((array)$data->get('weeks') as $week) {
    foreach ((array)Arr::get($week, 'days') as $day) {
        $out .= Arr::get($day, 'name');
    }
}

This way, I'm using the standard Request::json() without any key, to get a so called ParameterBag back. The 'get' method accepts a path, but then returns arrays instead of subclass-members. The benefit here is, that I can pass default values, if no valid json data was passed.

Are there any other solutions to parse & handle json if I had to iterate through a nested structure or did my solutions are fine? If so, which one should I use??

Thank you, Marc

08 Sep
4 years ago

kaju74 left a reply on Prevent Model:Update Event On Rember_token Changes?

I've made a workaround yet, to trigger the event manually and removed the updated-event until there's a better solution ;-)

Thank you, Marc

kaju74 left a reply on Prevent Model:Update Event On Rember_token Changes?

Hi.

This doesn't seem to work. The problem ist, that Auth::logout() will automatically generates a new token - independant, if the user want's to be remembered (seems to be the internal logic to handle this). So, the event will be fired, cause the request doesn't have the "remember_token" for that call...

Marc

kaju74 left a reply on URL Problem With Queued Jobs

ah, okay... thank you again ;-)

kaju74 left a reply on URL Problem With Queued Jobs

Oh...shit...I forgot this to configure ;-) But why does I got two different urls depending on how the emails were send?

Regards, Marc

kaju74 started a new conversation Prevent Model:Update Event On Rember_token Changes?

Hi.

My app listens to the event (user->updated) like:

    protected static function boot()
    {
        // call parent boot
        parent::boot();

        // register user events
        static::updated(function ($user) {
            event(new UserWasModified($user));
        });
    }

The problem is that everytime, the user is logged in, the remember_token database field will be updated, so the update-event will be fired.

Is there any way to prevent this event, if only the remember_token field has been updated?

Thank you, Marc

kaju74 started a new conversation URL Problem With Queued Jobs

Hi.

I'm a little bit confused about a behaviour, queued jobs handles the root url of my app. But one after the other ;-)

I've created a simple job to send confirmation mails to my users using a blade-template as my email envelope, so the user can click on the embedded confirmation link:

<a href="{{ url('auth/confirm/'.$token) }}">{{ url('auth/confirm/'.$token) }}</a>

If I use the non-job method like:

Mail::send('emails.confirm', $data, function ($message) use ($data, $user)...

...the email contains a link like:

http://my.domain.de/auth/confirm/2e1d91526d59150b51b84fcf284b8984de7f835817013b722380c4d605dd7449

As soon as I create the job like:

$this->dispatch(new SendConfirmEmailJob($user, $data));

...the corresponding email looks like:

http://localhost/auth/confirm/2e1d91526d59150b51b84fcf284b8984de7f835817013b722380c4d605dd7449

Why does the domain name has been replaced with "localhost"??

My job code is:

class SendConfirmEmail extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $user;
    protected $data;

    /**
     * Create a new job instance.
     * @param User $user
     * @param array $data
     */
    public function __construct(User $user, array $data)
    {
        $this->user = $user;
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @param Mailer $mailer
     */
    public function handle(Mailer $mailer)
    {
        $mailer->send('emails.confirm', $this->data, function ($message) {
            $message->from($this->data['mail_from_address'], $this->data['mail_from_name']);
            $message->subject($this->data['mail_subject']);
            $message->to($this->user->email);
        });
    }
}

BTW: I'm using an event/listener to hock into the update/create methods of my user-model, if this could be the reason for my problem.

Any ideas?

Thank you, Marc

03 Sep
4 years ago

kaju74 started a new conversation Misapply "DatabaseTokenRepository" For Create User Confirmation Emails

Hi.

Coming from another thread, I've tryed to send an email to the user after he has been registered to confirm the account. I took a look at the password_resets table and it fits my need on how to handle this. Instead of writing my own logic and I was looking around how the token handling was imlemented in Laravel...

...so here's the trick:

  1. Create a new Event/Listener to be notified about new created users
  2. Be sure, you user model implements "CanResetPassword" like this
class User extends Model implements AuthenticatableContract, CanResetPassword

...

    public function getEmailForPasswordReset()
    {
        return $this->email;
    }

  1. The event listener should looks like this:
    public function handle(UserWasCreated $event)
    {
        $user = $event->user;

        if (!$user->active) {

            $tokenizer = new DatabaseTokenRepository(DB::connection(), 'user_confirm', 'SALT');

            $data['user'] = $user;
            $data['token'] = $tokenizer->create($user);

            Mail::send('emails.confirm', $data, function ($message) use ($data, $user) {
                $message->from('no-reply@mypage.de', 'MyPage');
                $message->subject('MyPage: Registrierung');
                $message->to($user->email);
            });
        }
    }

This way, the token will be generated like the password-reset does it, and the token will be automatically inserted in the specified database table. You only had to implement the confirmation stuff using the other available methods of the DatabaseTokenRepository instance.

I'm not sure, if this is the gentle art of doing this stuff, but I'm a beginner in Laravel right now ;-)

Best regards, Marc

kaju74 left a reply on Check If A User Exists In Password Reset Table

Hi.

Is it possible to use the DatabaseTokenRepository to create own tokens for other stuff (e.g. send an email to confirm new registered users?) I'm not sure, how to use this class for my own purposes...

Thank you, Marc

02 Sep
4 years ago

kaju74 left a reply on How To Prevent Laravel From Returning Escaped JSON Data?

Hi.

Thank you for the quick answers. No, it's not just a problem by getting the data escaped cause I could unescape it, I only excepted, that Laravel will return it unecaped if I pass utf-8 in the request header. I thought, there's any convention on how to handle unicode json data and when to escape it like in my example above (I know, I've forgot the '}' character in my json data ;-)

Regards, Marc

kaju74 started a new conversation How To Prevent Laravel From Returning Escaped JSON Data?

Hi.

I'm implementing an API Server w/ Laravel which should return JSON...so it's fine, that the framework automatically support this. My problem is, that Laravel returns escaped data as soon as unicode characters (like german umlauts) will be used.

My host application sends stuff like this:

{"id": "53SEDXAF", "name": "Testhülse"

My API Controller simply return that stuff:

// return status
return [
    'status' => 'success',
    'data'   => Request::all(),
];

If I take a look at the response (e.g. using Fiddler), the data value will be returned using escape characters:

{"status":"success","data":{"data":{"id":"SEDXAF","name":"Testh\u00fclse"}}}

My request header looks like:

Accept: */*
Host: xyz
User-Agent: xyz
Content-Type: application/json; charset: utf-8
Accept-Charset: utf-8
Connection: Keep-Alive
Content-Length: 38
Pragma: no-cache

So, why does Laravel returned it w/ escaped characters? I thought, if I pass utf-8 as the character set in the header, the returned data will be unescaped...

I know, that I can return the JSON like this:

return response()->json(data, 200, [], JSON_UNESCAPED_UNICODE);

...but is there no other way to:

a) set this globally? b) let Laravel return JSON dependant of what character-set has been passed in the header?

Thank you, Marc