ahoi

ahoi

Member Since 7 Months Ago

Experience Points 2,280
Experience Level 1

2,720 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 0
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

15 Apr
1 week ago

ahoi started a new conversation Watch Array For Changes And Prevent Items To Be Empty

Hello everybody,

I got an array of objects like this:

item.list:

[
  {
    price: 1,
    factor: 1
  },
  {
    price: 1,
    factor: 2
  },
]

Now I would like to create a watcher, that prevents price or factor to be empty. If it is, it automatically should be set to 0.

I would do it like this:

'item.list': {
    handler: function (val, oldVal) {

        //how to get the key of the changed object here? 
    },
    deep: true
}

But unfortunately I don't get the key of the changed element?

12 Apr
1 week ago

ahoi left a reply on Alias For Model?

Hi @snapey

That's what I would love to do... But how can I make sure that only users having the "customers" role are linked to that model?

11 Apr
1 week ago

ahoi started a new conversation Alias For Model?

Hello everybody,

I got a Model called User. Each user can have an id, name, email, role etc.

Now I would like to create a model that is called Customer, which allows a customer to log in. But a Customer should always be a User with the role customer.

Is it possible to create an alias that defines a Customer to be a User that has a specific role assigned like this:

$customer->assignRole('customers');
09 Apr
1 week ago

ahoi started a new conversation Update Model With Dynamic HasMany-relation

Hello everybody,

I got a model that is called Car. This Car hasMany Attributes.

An attribute looks like this:

id = int
car_id = int
description = text

Now I can create a new Car and assign many Attributes. If I update the Car, I also would like to update the Attributes.

This is how I'd do this at the moment:

public function update(Request $request)
{
    /*Get car*/
    $car = Car::findOrFail($request->car_id);
    
    /*Get car attributes and delete them*/
    $car->attributes->each(function ($attribute) {
        $attribute->delete();
    });
    
    /*Save new attributes*/
    $attributes = $request->input('data.attributes');
    
    foreach ($attributes as $attribute) {
        Attribute::create([
            'car_id'      => $car->id,
            'description' => $attribute['description'],
        ]);
    }
    
    /*Update car title*/
    $car->title = $request->input('data.title');
    $car->save();
    
    return response()->json(['message' => 'success']);
}

So first of all I'd delete all attributes and recreate them afterwards according to the input. Is there any room for improvements here? How would you update these dynamic fields?

27 Mar
3 weeks ago

ahoi started a new conversation Add Object To An Array And Modify It Without Modifying The Initial Object

Hello everybody,

I created a little codepen to demonstrate my issue: https://codepen.io/spqrinc/pen/moYKZo

If you add "hello" from the select field multiple times, there will be text input fields where you can edit the value of this specific element. Well: That's the plan.

But if you change the title of one "hello" field, all other entries are getting a new title, too. How can I prevent this? I would like to have this new title only on the specific entry.

This is my source:

new Vue({
    el: '#app',
    data: {
        items: [
            {title: 'hello'},
            {title: 'world'}
        ],
        itemlist: [],
        newItem: {}
    },
    methods: {
        addItem: function (option) {
            this.itemlist.push (this.newItem);
        },
    },
});
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<div id="app">
    <select v-model="newItem">
        <option v-for="item in items"
                :value="item">{{item.title}}
        </option>
    </select>
    <button v-on:click="addItem">Add</button>
    <div v-for="item in itemlist">
        <input v-model="item.title"/>
    </div>
</div>
</body>
</html>
16 Mar
1 month ago

ahoi started a new conversation 70GB Of Logs (Laravel.log) Because Of Failing Job?

Hi there,

today, my queue worker wrote round about 70GB of logs (laravel.log). It was always the same message:

[2019-03-16 21:09:07] local.ERROR: include(/var/www/example.org/example/vendor/composer/../laravel/framework/src/Illuminate/Queue/FailingJob.php): failed to open stream: No such file or directory {"exception":"[object] (ErrorException(code: 0): include(/var/www/example.org/example/vendor/composer/../laravel/framework/src/Illuminate/Queue/FailingJob.php): failed to open stream: No such file or directory at /var/www/example.org/example/vendor/composer/ClassLoader.php:444)
[stacktrace]
#0 /var/www/example.org/example/vendor/composer/ClassLoader.php(444): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'include(/var/ww...', '/var/www/netzhe...', 444, Array)
#1 /var/www/example.org/example/vendor/composer/ClassLoader.php(444): include()
#2 /var/www/example.org/example/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/var/www/netzhe...')
#3 [internal function]: Composer\Autoload\ClassLoader->loadClass('Illuminate\\Queu...')
#4 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(440): spl_autoload_call('Illuminate\\Queu...')
#5 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(426): Illuminate\Queue\Worker->failJob('redis', Object(Illuminate\Queue\Jobs\RedisJob), Object(ErrorException))
#6 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(358): Illuminate\Queue\Worker->markJobAsFailedIfWillExceedMaxAttempts('redis', Object(Illuminate\Queue\Jobs\RedisJob), 3, Object(ErrorException))
#7 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(331): Illuminate\Queue\Worker->handleJobException('redis', Object(Illuminate\Queue\Jobs\RedisJob), Object(Illuminate\Queue\WorkerOptions), Object(ErrorException))
#8 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(277): Illuminate\Queue\Worker->process('redis', Object(Illuminate\Queue\Jobs\RedisJob), Object(Illuminate\Queue\WorkerOptions))
#9 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(118): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\RedisJob), 'redis', Object(Illuminate\Queue\WorkerOptions))
#10 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(102): Illuminate\Queue\Worker->daemon('redis', 'default', Object(Illuminate\Queue\WorkerOptions))
#11 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(86): Illuminate\Queue\Console\WorkCommand->runWorker('redis', 'default')
#12 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#13 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#14 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#15 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#16 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Container/Container.php(572): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#17 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
#18 /var/www/example.org/example/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#19 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#20 /var/www/example.org/example/vendor/symfony/console/Application.php(901): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#21 /var/www/example.org/example/vendor/symfony/console/Application.php(262): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#22 /var/www/example.org/example/vendor/symfony/console/Application.php(145): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#23 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Console/Application.php(89): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#24 /var/www/example.org/example/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#25 /var/www/example.org/example/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#26 {main}
"} 

Is it correct that a specific file could not be found by ClassLoader or don't I understand that correctly?

I just did a composer dump-autoload...

03 Mar
1 month ago

ahoi left a reply on Modify Array Before Saving It

This helps a lot! Thank you very much!

02 Mar
1 month ago

ahoi started a new conversation Modify Array Before Saving It

Hello everybody,

I am using a JSON field in my database. Now, I am saving an Array in it that is converted to JSON before:

User model

 protected $casts
        = [
            'options' => 'array',
        ];

Saving an option

$options = $user->options;                                                                                                                                                                       $options['notify'] = true;                                                                                                                                                               $user->options = $options;                                                                                                                                                                       $user->save();    

Now the Array comes from an user form input, this is validated as array.

Is it possible to modify this array before saving to make sure that it contains at least the field notify? If the array does not contain thenotify field, create one with value false.

I thought I could use something like this:

    public function setOptionsAttribute($value)
    {
        $this->attributes['options'] = json_encode($value); //TODO: Check for correct entries, ...
    }

Is this the suggested way?

Another question: On saving, does

            'options'              => 'array',

prevent my app from SQL-injection attacks or do I have to manually check the input?

ahoi left a reply on JSON In API Resource Is Quoted?

Hm, that's strange...

In my browser (app) the JSON user.options looks like this:

{"notify_on_mail":true}

But if I try to access user.options.notify_on_mail I am getting undefined. I also renamed notify_on_mail to notify, without success.

01 Mar
1 month ago

ahoi started a new conversation JSON In API Resource Is Quoted?

Hi everybody,

I my API Resource I am accessing $user->options, which is a JSON field:

        Schema::table('users', function (Blueprint $table) {
            $table->json('options');
        });
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Gate;

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

Now my result (seen on my browser's network console) is this:

options: "{\"notify_on_mail\":true}"

How can I return this unquoted?

The problem: I can not access this in Vue.js:

undefined is not an object (evaluating '_vm.user.options.notify_on_mail')

Your help is highly appreciated :-)

20 Feb
2 months ago

ahoi started a new conversation Get ID Of Created Element In Observer

Hey there,

I am using an observer (https://laravel.com/docs/5.7/eloquent#observers) to create a App\Team, once a App\Group is created:

    public function created(Group $group)
    {
        if (request()->has('data.name')) {
            Team::create([
                'name'       => $company->name,
                'owner_id'   => request()->user()->getKey(),
                'group_id'   => $group->id,
            ]);
            
            request()->user()->attachTeam($team);

            $group->team_id = $team->id;
            $group->save();
        }
    }

Unfortunately

'group_id'   => $group->id,

is always saving null, as $group->id is empty. I thought the created event fires after the entry is created? At this moment it should already have an ID?

I am very happy for every hint you can give me :-)

10 Feb
2 months ago

ahoi started a new conversation Axios.get(): Not Allowed By Access-Control-Allow-Headers.

Hello everybody,

at the moment, I am trying to use axios to send a little GET request:

axios.get (process.env.MIX_MATOMO_URL + '/index.php?module=API&method=AjaxOptOut.isTracked&format=json').then ((response) => {
                this.tracked = response.value;
});

This fails with:

Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.

Alright - I added my domain to Matomo's cors_domains - but without success.

Any help is highly appreciated :-)

ahoi started a new conversation Send Verification Mail On Socialite Login

Hello everybody,

actually I am using MustVerifyEmail on user's registration:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Scout\Searchable;


class User extends Authenticatable
    implements MustVerifyEmail
{
    use Notifiable,  Searchable;
}
    

Now I am additionally using Laravel Scout to login using Facebook and Twitter.

I created a login controller and added this:

function findOrCreateUser($providerUser, $provider)
{
    
    $user = User::create([
        'email'     => $providerUser->getEmail(),
        'lastname'  => $providerUser->user['last_name'],
        'firstname' => $providerUser->user['first_name'],
    ]);
    
    
    event(new Registered($user));    
    
    return $user;
}

Now I am triggering this event manually: event(new Registered($user)); to send the verification mail. I am just wondering: Is there a more elegant way to archive this?

03 Feb
2 months ago

ahoi left a reply on Use More Complex Where Clauses In Scout

Hm, unfortunately I did not solve this issue yet.

The problem is that Scout allows only numeric values here.

Scout does not allow < or >.

I solved the status-problem like this:

 /**
     * Get the indexable data array for the model.
     *
     * @return array
     */
    public function toSearchableArray()
    {
        return [
            'id'       => $this->id,
            'status'   => $this->status == 'active' ? 1 : 0,
        ];
    }

But I still can not search for entries that have been published between two dates.

I thought I could use the shouldBeSearchable() like this:

public function shouldBeSearchable()
{
    return $this->starts_on > now();
}

But as I understood it, this method only defines, whether an entry is pushed to Algolia or not. As the entry is not updated between the creation-date and now(), it will not be deleted from Algolia, right?

28 Jan
2 months ago

ahoi started a new conversation Session Expired -> Redirect To / Instead Of /login

Hello everybody,

I am just wondering, why Laravel is redirecting a user to /login by default.

Could it be possible to redirect to / instead?

Maybe by changing the ExceptionHandler?

What's best practice here?

26 Jan
2 months ago

ahoi started a new conversation Use More Complex Where Clauses In Scout

Hi,

I am a happy user of Laravel Scout.

Now I'd like to extend my search:

            $data
                = new UserOverviewResourceCollection(User::search($searchphrase)
                ->currentStatus('active')->orderBy('lastname', 'asc')
                ->orderBy('firstname', 'asc')
                ->paginate(config('pagination.length')));

currentStatus comes from https://github.com/spatie/laravel-model-status .

Now I am getting a response, that currentStatus is not supported. I thought I could be a good idea to filter the result of User::search after it has been returned from scout?

Another idea: I'd like to add more complex where clauses:

>where([
                [
                    'starts_on',
                    '<',
                    Carbon::now()->toDateTimeString(),
                ],
                [
                    'ends_on',
                    '>',
                    Carbon::now()->toDateTimeString(),
                ],
            ])

Maybe you got a better idea?

17 Jan
3 months ago

ahoi left a reply on Install And Laravel-echo-server Multiple Times On The Same Server

Hi and thank you for your response.

I just had a look at laravel-websockets. Is it correct that I still have to register at pusher.com (because the example uses PUSHER_APP_KEY etc.)?

16 Jan
3 months ago

ahoi started a new conversation Install And Laravel-echo-server Multiple Times On The Same Server

Hello everybody,

I am using Laravel Echo Server for a real-time-notification of my users.

As I got a staging-system on the same server as my live-system, I'd like to install (and run) the echo-server twice.

Is that possible?

ahoi left a reply on Using Private Channels On Laravel Echo

Solved it. The variable has to be included somewhere in your JS.

Actually I'm doing it like this at the moment (example with user):

  <script>
        window.App = {!! json_encode([
        'user' => auth()->check() ? auth()->user()->id : null,
    ]) !!};
    </script>
window.Echo.private('App.User.'+window.App.user)

ahoi left a reply on Event Is Emitted Twice?

@BOBBYBOUWMANN - The component was included twice (once for large devices and once for mobile devices).

Thanks to your hint I figured out, how scatterbrained I can be sometimes :-D

Thank you!

15 Jan
3 months ago

ahoi started a new conversation Event Is Emitted Twice?

Hello everybody,

I got the problem that an event is emitted twice somehow. I can not explain this behavior:

This is my bootstrap.js:

//
window._ = require("lodash");

window.Vue = require("vue");

Vue.prototype.$eventHub = new Vue();

Vue.component('messagebar', require('./components/MessageBar.vue'));

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require("axios");

window.axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
  window.axios.defaults.headers.common["X-CSRF-TOKEN"] = token.content;
} else {
  console.error(
    "CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token"
  );
}

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo'

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     encrypted: true
// });


import Echo from 'laravel-echo'

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

window.Echo.private('App.User.'+window.App.user)
.notification((notification) => {
    if(notification.type === "App\Notifications\MessageCreatedNotification"){
        console.log("Trigger in the Listener");
        window.Vue.prototype.$eventHub.$emit('FOO', notification);
    }
});

This is my MessageBar.vue:

<!--
<template>
    <a :href="route" data-uk-icon="icon: mail" title=""
       data-uk-tooltip="Nachrichten"
       aria-expanded="false" class="uk-icon-link uk-icon"> <span v-if="count > 0"
                                                                 class="uk-badge wmp-badge-icon">{{count}}</span></a>

</template>
<script>

export default {
    name: "messagebar",

    props: {
        route: {
            type: String,
            default: ''
        },
    },
    data () {
        return {
            count: null
        }
    },
    computed: {},
    mounted () {
        let vm = this;
        this.$eventHub.$on ('CONVERSATION_MESSAGE_CREATED', function (val) {
            vm.count = val.unread_count;
        });
    },
    created: function created () {
        axios
        .get ('/api/conversation/count/')
        .then ((response) => {
            this.count = response.data;
        });
    },
    watch: {
    },
    methods: {}
};
</script>-->
<template>
    <a :href="route" data-uk-icon="icon: mail" title=""
       data-uk-tooltip="Nachrichten"
       aria-expanded="false" class="uk-icon-link uk-icon"> <span v-if="count > 0"
                                                                 class="uk-badge wmp-badge-icon">{{count}}</span></a>

</template>
<script>

export default {
    name: "messagebar",

    props: {
        route: {
            type: String,
            default: ''
        },
    },
    data () {
        return {
            count: null
        }
    },
    computed: {
    },
    mounted () {
        let vm = this;
        this.$eventHub.$on ('FOO', function (val) {
            console.log("Output: "+val.id);
        });
    },
    created: function created () {
    },
    watch: {
    },
    methods: {
    }
};
</script>

Now I get this output:

> Test
> Output: 1
> Output: 1

I can not explain why this is called twice. FOO does only exist on this two places in my project.

14 Jan
3 months ago

ahoi started a new conversation Prevent Login Of A User, If $user->status == "blocked"

Hello everybody,

I got a default Laravel app using php artisan make:auth.

Now my users should be "excluded" from logging in when their status is "blocked".

$user->status

returns a simply string (as you can read here: https://github.com/spatie/laravel-model-status#retrieving-statuses).

So is there an elegant way to prevent such users from logging in?

ahoi started a new conversation Broadcasting To All Recipients Of A Message

Hello everybody,

I am a little stuck at the moment. So I really hope you can help me out :-)

I am building a little private message system for my Laravel app.

I would like to notify my users on the Event MessageCreated.

This is my event:

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Cmgmyr\Messenger\Models\Message;

class MessageCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    public $message;
    
    /**
     * MessageCreated constructor.
     *
     * @param \App\Message $message
     */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }
    
    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('conversation.'.$this->message->user_id);
    }
}

This is my notification:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Lang;

class MessageCreated extends Notification
{
    use Queueable;
    
    protected $message;
    
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($message)
    {
        $this->message = $message;
    }
    
    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed $notifiable
     *
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }
    
    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed $notifiable
     *
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        
        return (new MailMessage)->subject('...'));
    }
    
    /**
     * Get the array representation of the notification.
     *
     * @param  mixed $notifiable
     *
     * @return array
     */
    public function toArray($notifiable)
    {
        return [//
        ];
    }
}

This is my event subscriber

<?php

namespace App\Listeners;

use App\Message;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\MessageCreated;
use Cmgmyr\Messenger\Models\Thread;
use Illuminate\Support\Facades\Auth;
use App\Notifications\MessageCreated as MessageCreatedNotification;
use App\User;

class MessageEventSubscriber
{
    
    /**
     * MessageEventSubscriber constructor.
     */
    public function __construct()
    {
        //
    }
    
    /**
     * @param \App\Events\MessageCreated $event
     */
    public function handle(MessageCreated $event)
    {
        $participants = Thread::findOrFail($event->message->thread_id)
            ->participantsUserIds();
    
        
        foreach ($participants as $participant) {
            if ($participant != $event->message->user_id) {
                $user = User::findOrFail($participant);
                $user->notify(new MessageCreatedNotification($event->message));
            }
        }
    }
}

I am also working with Laravel Echo:

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

window.Echo.private('conversation.'+App.user)
.listen('MessageCreated', (e) => {
    console.log(e);
});

Well - the Mails are being sent without problems. But now I'm a bit stuck on how to send a broadcast message to all the users in the recipients list. And of course I need to do this the most secure way.

I read the Laravel docs the whole day, but unfortunately I did not get a correct solution yet.

Your help is highly appreciated!

ahoi started a new conversation Using Private Channels On Laravel Echo

Hello everybody,

Actually I am still working on my private messaging app.

To load new notifications, I would like to use a PrivateChannel.

This is what I'm doing at the moment:

bootstrap.js

import Echo from 'laravel-echo'

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

window.Echo.private('conversation.${messageId}')
.listen('MessageCreated', (e) => {
    console.log(e);
});

MessageChannel.php

<?php

namespace App\Broadcasting;

use App\User;
use App\Message;
use Illuminate\Support\Facades\Log;

class MessageChannel
{
    /**
     * Create a new channel instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    
    
    /**
     * @param \App\User    $user
     * @param \App\Message $message
     *
     * @return bool
     */public function join(User $user, Message $message)
    {
        return $user->id === $message->user_id;
    }
}

MessageCreated.php

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Cmgmyr\Messenger\Models\Message;

class MessageCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    public $message;
    
    /**
     * MessageCreated constructor.
     *
     * @param \App\Message $message
     */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('conversation.'.$this->message->id);
    }
}

channels.php

Broadcast::channel('conversation.{messageId}', function($user, $messageId){
    return Auth::check(); //has to be improved. Check, whether the user is in recipients list
});

web.php (test route)

Route::get('test', function(){
    $message = App\Message::find(1);
    broadcast(new \App\Events\MessageCreated($message));
});

Now I'm getting this in my Echo console:

[13:44:07] - Sending auth request to: https://test.app/broadcasting/auth

[13:44:10] - Do63uEo-ePk8Nh9jAAC0 authenticated for: private-conversation.${messageId}
[13:44:10] - Do63uEo-ePk8Nh9jAAC0 joined channel: private-conversation.${messageId}

I got this from https://laravel.com/docs/5.7/broadcasting -> Listening For Event Broadcasts

Echo.private(`order.${orderId}`)
    .listen('ShippingStatusUpdated', (e) => {
        console.log(e.update);
    });

But where does Echo.private get ${orderId} from in this example?

12 Jan
3 months ago

ahoi left a reply on Socialite: GitHub Login Shows 404

Got it: I had to clear and cache my config again, as

GITHUB_CLIENT_ID=...
GITHUB_CLIENT_SECRET=...
GITHUB_REDIRECT=https://.../login/github/callback

were null.

ahoi started a new conversation Socialite: GitHub Login Shows 404

Hello everybody,

I am using laravel/socialite to log in with Facebook and Twitter. Now I'd like to add GitHub.

This is what I am doing:

 public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }
    
    public function handleProviderCallback($provider)
    {
        try {
            if ($provider == 'facebook') {
                $user = Socialite::driver($provider)->fields([
                    'first_name',
                    'last_name',
                    'email',
                ])->user();
            } else {
                $user = Socialite::driver($provider)->user();
            }
        } catch (Exception $e) {
            return redirect('/');
        }
        
        $authUser = $this->findOrCreateUser($user, $provider);
        Auth::login($authUser, true);
        
        return redirect($this->redirectTo);
    }

Now if I try to log in, I am being redirected to GitHub's login page (https://github.com/login?return_to=%2Flogin%2Foauth%2Fauthorize%3Fresponse_type%3Dcode%26scope%3Duser%253Aemail%26state%3D8x3twY...PQEkrUz).

(https://imgur.com/dxKFGz0)

If I enter my Credentials, I am getting 404 (https://github.com/login/oauth/authorize?response_type=code&scope=user%3Aemail&state=8x3twYHo0mArfLd80o...PQEkrUz).

(https://imgur.com/ctbvpnE)

Is this a bug? Did I do something incorrect?

09 Jan
3 months ago

ahoi started a new conversation Revoke Notification (from Queue?) If Model-item Has Been Shown

Hello everybody,

I would like to notify my users if they got a new private message. The private message has a isUnread-property, which is set true on a new message and can be set false if the show action in the controller is called.

Well - now my idea: To prevent thousands of messages, I'd like to revoke the notification from the queue, if the user has seen the new message before the notification has been sent.

Unfortunately I don't get a way to do so. Maybe the community has an idea?

Your help is much appreciated :-)

ahoi started a new conversation Translation Of A Specific Part Of A Notification Does Not Work

Hello,

I got this notification (resources/views/vendor/notifications/email.blade.php):

@lang( "If you’re having trouble clicking the ":actionText" button, copy and paste the URL below\n". 'into your web browser: :actionURL', [ 'actionText' => $actionText, 'actionURL' => $actionUrl, ] )

Now I'd like to translate that one using de.json in resource/lang-directory:

{ 
"If you’re having trouble clicking the \":actionText\" button, copy and paste the URL below into your web browser: [:actionURL](:actionURL)": "Falls Du Probleme dabei hast, den \":actionText\" Button anzuklicken, rufe folgende URL auf: [:actionURL](:actionURL)"
}

All other translations I created this way are working fine

08 Jan
3 months ago

ahoi started a new conversation Send Mail On Model Created

Hello everybody,

I am new to Laravel events and notifications. I'd like to send a simple mail, once a model is created.

 Message::create([
            'user_id'   => auth()->user()->id,
            'body'      => $request->data['message'],
        ]);

Is it possible to fetch this create event and trigger a notification which sends a mail via toMail?

I followed this one: https://sujipthapa.co/blog/automatically-posting-to-facebook-page-via-laravel-notifications

This is my model:

<?php

namespace App;

use Cmgmyr\Messenger\Models\Message as BaseMessage;
use Illuminate\Notifications\Notifiable;

class Message extends BaseMessage
{
    use Notifiable;
}

This is my listener:

<?php

namespace App\Listeners;

use App\Notifications\MessageSaved;

/**
 * Class MessageEventSubscriber
 * @package App\Listeners
 */
class MessageEventSubscriber
{
    
    /**
     * Handle message creating events.
     *
     * @param $message
     */
    public function onSaved($message)
    {
        $message->notify(new MessageSaved());
    }
    
    /**
     * @param $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'eloquent.saved: App\Message',
            'App\Listeners\[email protected]'
        );
    }
}

This is my notification:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class MessageSaved extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

and this is my EventServiceProvider:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen
        = [
            'App\Events\Event'               => [
                'App\Listeners\EventListener',
            ],
            Registered::class                => [
                SendEmailVerificationNotification::class,
            ],
        ];
    
    protected $subscribe = [
        'App\Listeners\MessageEventSubscriber',
    ];
    
    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
        
        //
    }
}

Unfortunately the notification is not being triggered this way.

Your help is highly appreciated :-)

07 Jan
3 months ago

ahoi left a reply on Event Fire On Vendor Package's Model Change?

Thanks for your reply...

Well, I got it working. Maybe you could check my work?

MyController:

<?php
use App\User;
use App\Message;
[...]
//use Cmgmyr\Messenger\Models\Message;
use Cmgmyr\Messenger\Models\Thread;
use Carbon\Carbon;

[...]

public function store(Request $request)
    {
      [...]
        
        // Message
        Message::
            'user_id'   => auth()->user()->id,
            'body'      => $request->data['body']
        
        return response()->json($thread);
    }

The wrapper:

<?php

namespace App;

use Cmgmyr\Messenger\Models\Message as BaseMessage;

class Message extends BaseMessage
{
    protected $dispatchesEvents
        = [
            'saving' => \App\Events\MessageSaving::class,
        ];
}

The event:

<?php

namespace App\Events;

use App\User;
use Cmgmyr\Messenger\Models\Message;
use Illuminate\Queue\SerializesModels;

class MessageSaving
{
    use SerializesModels;
    
    public $message;
    
    /**
     * MessageSaving constructor.
     *
     * @param \App\Message $message
     */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }
}

The Listener:

<?php

namespace App\Listeners;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\MessageSaving as MessageSavingEvent;

class MessageSaving
{
    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(MessageSavingEvent $event)
    {
        app('log')->info($event->message);
    }
}

The Event Service Provider:

protected $listen
        = [
            'App\Events\Event'               => [
                'App\Listeners\EventListener',
            ],
            \App\Events\MessageSaving::class => [
                \App\Listeners\MessageSaving::class,
            ]
        ];

If you see something to improve, please tell me :-)

ahoi started a new conversation Event Fire On Vendor Package's Model Change?

Hello everybody,

I am using https://github.com/cmgmyr/laravel-messenger to create a little messaging-system for my users.

Now I'd like to update them, if there is a new message.

Well: If I created this model, I could add a model event, something like that:

protected $dispatchesEvents = [
    'saving' => \App\Events\MessageSaving::class,
];

But as this is a vendor package, I am not sure, how to do that or whether this is possible at all.

This is the class I'd like to listen for: https://github.com/cmgmyr/laravel-messenger/blob/master/src/Models/Message.php

So my question: Is this possible out of the box or do I have to fire an event by myself, for example in my controller's method, which adds a new message...?

06 Jan
3 months ago

ahoi started a new conversation Create A Custom Mail-template For Verification Mail

Hello everybody,

I'd like to implement MustVerifyEmail (Illuminate\Contracts\Auth\MustVerifyEmail); it already works fine.

I know that the easiest possibility is to translate the message content, which is provided by:

/**
     * Build the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        if (static::$toMailCallback) {
            return call_user_func(static::$toMailCallback, $notifiable);
        }

        return (new MailMessage)
            ->subject(Lang::getFromJson('Verify Email Address'))
            ->line(Lang::getFromJson('Please click the button below to verify your email address.'))
            ->action(
                Lang::getFromJson('Verify Email Address'),
                $this->verificationUrl($notifiable)
            )
            ->line(Lang::getFromJson('If you did not create an account, no further action is required.'));
    }

But now I'd like to create a custom mail-template (HTML) message. How can I do that? Is there any possibility to do that?

Thanks in advance :-)

06 Dec
4 months ago

ahoi left a reply on $collection->filter Removes Array

Hm - it works this way:

'items'        => $this->items->filter(function ($item) {
                if (Gate::allows('view-item', $item)) {
                    $itemresource = new ItemResource($item);
                    
                    return $itemresource->toArray($item);
                }
            }),

So the toArray is not being called in $this->items->filter if I create a new Resource? But why is it the case, if I'm using map()?

ahoi started a new conversation $collection->filter Removes Array

Hi there,

I am using this source to filter an array: I'd like to decide, whether a user is able to see an item or not.

This is my code:

'items' => $this->items->filter(function ($item) {
                if (Gate::allows('edit-item', $item->user_id)) {
                    return new ItemResource($item);
                }
            }),

If I now check the response, I'm getting:

{
    "data": {
        "id": 1,
        "name": "John Doe",
        "items": [
            {
                "id": 14,
                "title": "test",
                "status": "unpublished"
            }
        ],        
        "status": "active"
    }
}

Now it's getting strange (for me ;-) ): If I use map() instead of filter(), I'm getting this:

            'items' => $this->items->map(function ($item) {
                if (Gate::allows('edit-item', $item->user_id)) {
                    return new ItemResource($item);
                }
            }),

This is the response:

{
    "data": {
        "id": 1,
        "name": "John Doe",     
        "items": [
            {
                "id": 14,
                "title": "test",
                "tags": [
                    {
                        "text": "test",
                        "tiClasses": [
                            "valid"
                        ]
                    }
                ],
                "status": "unpublished"
            }
        ],
        "status": "active"
    }
}

As you can see: The tags of the items are gone, if I'm using filter. How can I get a solution, which includes all items I am allowed to see, including the tags?

03 Dec
4 months ago

ahoi left a reply on Using Condition On A ResourceCollection Does Not Work Correctly?

Of course:

/**
 * @return mixed
 */
public function getAvatar()
{
    
    
    $avatars = $this->getMedia('user_images')->all();
    
    foreach ($avatars as $avatar) {
        $is_default = array_key_exists('default_avatar',
                $avatar->custom_properties)
            && $avatar->custom_properties['default_avatar'] === true;
        
        if ($is_default) {
            return $avatar;
        }
    }
    
    
    return false;
}

ahoi left a reply on Using Condition On A ResourceCollection Does Not Work Correctly?

Hi @snapey

I understood this (https://laravel.com/docs/5.7/eloquent-resources) just like I could use $this->when in this context, too?

ahoi started a new conversation Using Condition On A ResourceCollection Does Not Work Correctly?

Hello everybody,

I am using a ResourceCollection. There I'd like to add this:

return [
        'data' => $this->collection->transform(function ($user) {
            return [
                'id'       => $user->id,
                'lastname' => $user->lastname,
                'name'     => $user->name,
                'email'    => $user->email,
                'avatar' => ($user->getAvatar() ? $user->getAvatar()
                    ->getUrl('thumb') : false),
            ];
        }),
    ];

Well: If the user does not have an avatar, the getAvatar method returns false.

I tried to use this:

$this->when($user->getAvatar(), $user->getAvatar()->getUrl('thumb')

But: If $user->getAvatar() returns false, the function $user->getAvatar()->getUrl('thumb') is still being called - PHP returns:

Call to a member function getUrl() on boolean

But it should not do that? Now I am using the ternary operator, but I'd prefer $this->when. What am I doing wrong?

02 Nov
5 months ago

ahoi started a new conversation Mount Vue-Component "on Demand" And Change Bind-value On Click.

Hey there,

I would like to change the value I bind to a component “on demand”. So if the data changes, the content of the passed value should also be changed:

 <user :user_id="selectedUserId"></user>
   <td>
         <a href="#settings-modal" uk-toggle uk-icon="more" @click="setSelectedUserId(user.id)"></a>
   </td>

So - unfortunately this does not happen. What can I do to mount the component with the specific value after the link has been clicked?

ahoi left a reply on Pagination On API Ressource

I think I solved it this way:

I added

            'pagination' => $this->resource->toArray()

to my array.

ahoi left a reply on Where To Add Spate/menu?

I solved it using a Provider :-)

ahoi started a new conversation Pagination On API Ressource

Hi everybody,

I wrote a little API Ressource for my User's model:

use Illuminate\Http\Resources\Json\ResourceCollection;

class User extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection->transform(function ($user) {
                return [
                    'id'         => $user->id,
                    'name'       => $user->name,
                    'email'      => $user->email,
                    'aboutme'    => $user->aboutme,
                    'homepage'   => $user->homepage,
                    'twitter'    => $user->twitter,
                    'created_at' => $user->created_at,
                    'updated_at' => $user->updated_at,
                    'avatar'     => $user->getAvatar(),
                ];
            }),
        ];
        
    }
}

Now I'm trying to fetch my items in my ApiController:

 /**
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getList(Request $request)
    {
        $data =  new UserResourceCollection(User::paginate(1));
        return response()->json($data);
    }

So - actually I'm just getting this:

{
  "data": [
    {
      "id": 1,
      "name": "John Doe",
      "email": "[email protected]",
      "aboutme": "Test",
      "homepage": "http://example.org",
      "twitter": "@example",
      "created_at": {
        "date": "2018-08-20 11:36:25.000000",
        "timezone_type": 3,
        "timezone": "UTC"
      },
      "updated_at": {
        "date": "2018-10-26 19:47:40.000000",
        "timezone_type": 3,
        "timezone": "UTC"
      },
      "avatar": {
        "id": 73,
        "model_type": "App\User",
        "model_id": "1",
        "collection_name": "user_images",
        "name": "Bild",
        "file_name": "Bild.jpg",
        "mime_type": "image/jpeg",
        "disk": "public",
        "size": "70250",
        "manipulations": [],
        "custom_properties": {
          "custom_headers": [],
          "generated_conversions": {
            "preview": true,
            "thumb": true,
            "header": true
          },
          "default_avatar": true
        },
        "responsive_images": {
          "preview": {
            "urls": [
              "Bild___preview_600_540.jpg",
              "Bild___preview_501_450.jpg",
              "Bild___preview_419_377.jpg",
              "Bild___preview_351_315.jpg",
              "Bild___preview_293_263.jpg"
            ],
          },
          "header": {
            "urls": [
              "Bild___header_1800_1200.jpg",
              "Bild___header_1505_1003.jpg",
              "Bild___header_1260_840.jpg",
              "Bild___header_1054_702.jpg",
              "Bild___header_881_587.jpg",
              "Bild___header_737_491.jpg",
              "Bild___header_617_411.jpg",
              "Bild___header_516_344.jpg",
              "Bild___header_432_288.jpg"
            ]
          }
        },
        "order_column": "10",
        "created_at": "2018-10-11 14:49:14",
        "updated_at": "2018-10-21 16:05:31"
      }
    }
  ]
}

Well - all my pagination information is gone :-(

If I do this:

 /**
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getList(Request $request)
    {
        $data =  new UserResourceCollection(User::paginate());

        return response()->json($data);
    }

I'm getting both users:

{
  "data": [
    {
      "id": 1,
      "name": "John Doe",
      "email": "[email protected]",
      "aboutme": "Test",
      "homepage": "http://example.org",
      "twitter": "@example",
      "created_at": {
        "date": "2018-08-20 11:36:25.000000",
        "timezone_type": 3,
        "timezone": "UTC"
      },
      "updated_at": {
        "date": "2018-10-26 19:47:40.000000",
        "timezone_type": 3,
        "timezone": "UTC"
      },
      "avatar": {
        "id": 73,
        "model_type": "App\User",
        "model_id": "1",
        "collection_name": "user_images",
        "name": "Bild",
        "file_name": "Bild.jpg",
        "mime_type": "image/jpeg",
        "disk": "public",
        "size": "70250",
        "manipulations": [],
        "custom_properties": {
          "custom_headers": [],
          "generated_conversions": {
            "preview": true,
            "thumb": true,
            "header": true
          },
          "default_avatar": true
        },
        "responsive_images": {
          "preview": {
            "urls": [
              "Bild___preview_600_540.jpg",
              "Bild___preview_501_450.jpg",
              "Bild___preview_419_377.jpg",
              "Bild___preview_351_315.jpg",
              "Bild___preview_293_263.jpg"
            ]
          },
          "header": {
            "urls": [
              "Bild___header_1800_1200.jpg",
              "Bild___header_1505_1003.jpg",
              "Bild___header_1260_840.jpg",
              "Bild___header_1054_702.jpg",
              "Bild___header_881_587.jpg",
              "Bild___header_737_491.jpg",
              "Bild___header_617_411.jpg",
              "Bild___header_516_344.jpg",
              "Bild___header_432_288.jpg"
            ]
          }
        },
        "order_column": "10",
        "created_at": "2018-10-11 14:49:14",
        "updated_at": "2018-10-21 16:05:31"
      }
    },
    {
      "id": 2,
      "name": "Jonnie Donnie",
      "email": "[email protected]",
      "aboutme": "<p>It's a me</p>",
      "homepage": "https://example.wtf",
      "twitter": "@example2",
      "created_at": {
        "date": "2018-09-25 08:23:18.000000",
        "timezone_type": 3,
        "timezone": "UTC"
      },
      "updated_at": {
        "date": "2018-10-30 07:18:48.000000",
        "timezone_type": 3,
        "timezone": "UTC"
      },
      "avatar": {
        "id": 40,
        "model_type": "App\User",
        "model_id": "2",
        "collection_name": "user_images",
        "name": "16427620_1962599807213714_791945067670209719_n",
        "file_name": "16427620_1962599807213714_791945067670209719_n.jpg",
        "mime_type": "image/jpeg",
        "disk": "public",
        "size": "15466",
        "manipulations": [],
        "custom_properties": {
          "custom_headers": [],
          "generated_conversions": {
            "preview": true,
            "thumb": true,
            "header": true
          },
          "default_avatar": true,
          "default_header": true
        },
        "responsive_images": {
          "preview": {
            "urls": [
              "16427620_1962599807213714_791945067670209719_n___preview_600_540.jpg",
              "16427620_1962599807213714_791945067670209719_n___preview_501_450.jpg",
              "16427620_1962599807213714_791945067670209719_n___preview_420_378.jpg",
              "16427620_1962599807213714_791945067670209719_n___preview_351_315.jpg",
              "16427620_1962599807213714_791945067670209719_n___preview_294_264.jpg",
              "16427620_1962599807213714_791945067670209719_n___preview_245_220.jpg"
            ]
          },
          "header": {
            "urls": [
              "16427620_1962599807213714_791945067670209719_n___header_1800_1200.jpg",
              "16427620_1962599807213714_791945067670209719_n___header_1505_1003.jpg",
              "16427620_1962599807213714_791945067670209719_n___header_1260_840.jpg",
              "16427620_1962599807213714_791945067670209719_n___header_1054_702.jpg",
              "16427620_1962599807213714_791945067670209719_n___header_881_587.jpg",
              "16427620_1962599807213714_791945067670209719_n___header_737_491.jpg",
              "16427620_1962599807213714_791945067670209719_n___header_617_411.jpg",
              "16427620_1962599807213714_791945067670209719_n___header_516_344.jpg",
              "16427620_1962599807213714_791945067670209719_n___header_432_288.jpg",
              "16427620_1962599807213714_791945067670209719_n___header_361_240.jpg"
            ]
          }
        },
        "order_column": "3",
        "created_at": "2018-09-25 08:23:50",
        "updated_at": "2018-10-30 18:06:49"
      }
    }
  ]
}

But still without pagination data?

What am I doing wrong?

29 Oct
5 months ago

ahoi left a reply on Only Allow Access To Route If Two Conditions Are Matching

That's so cool. Thank you very much!

I am using Laravel for a few weeks now and it is just so cool :-)

ahoi started a new conversation Only Allow Access To Route If Two Conditions Are Matching

Hello everybody,

I'd like to publish a route to all users, who:

Now, actually I could use this: https://github.com/spatie/laravel-permission#using-a-middleware

But this only allows me to check the permission - but not whether the user has the permission or has the same id as the user's id that is called in the route.

My question is:

Do I always have to check the user-id in the Controller? If so, I could not use the middleware of laravel-permission, because it would fail, if the user would try to edit his own page, just because he does not have the global permission to edit-pages

I am very thankful for every hint :-)

26 Oct
5 months ago

ahoi started a new conversation Update Array Of Objects

Hello,

I got a little problem.

I got two arrays of objects:

user.roles (comes from spatie/laravel-permission - https://github.com/spatie/laravel-permission/blob/master/README.md#using-direct-permissions-see-below-to-use-both-roles-and-permissions ) -> auth()->user()

user: {
            roles: [{
                "id": 2,
                "name": "admin",
                "guard_name": "web",
                "created_at": "2018-10-21 15:39:14",
                "updated_at": "2018-10-21 15:39:14",
                "pivot": {"model_id": "1", "role_id": "2", "model_type": "App\User"}
            }, {
                "id": 3,
                "name": "super-admin",
                "guard_name": "web",
                "created_at": "2018-10-22 05:16:00",
                "updated_at": "2018-10-22 05:16:00",
                "pivot": {"model_id": "1", "role_id": "3", "model_type": "App\User"}
            }]
        },

And roles (comes from $roles = Role::all();):

roles: [{
            "id": 2,
            "name": "admin",
            "guard_name": "web",
            "created_at": "2018-10-21 15:39:14",
            "updated_at": "2018-10-21 15:39:14"
        }, {
            "id": 3,
            "name": "super-admin",
            "guard_name": "web",
            "created_at": "2018-10-22 05:16:00",
            "updated_at": "2018-10-22 05:16:00"
        }]

As you can see, these objects are a little different... Well - now I'd like to update the array user.roles on checkbox-selection...

<div id="app">
  <div>
    <label>Email</label>
    <input type="text" v-model="user.email" />
  </div>
  <div v-for="role in roles" :key="role.id">
    <label>{{role.name}}</label>
    <input type="checkbox" v-model="user.roles" :value="role"/>
  </div>
  
  <p>User's selected roels</p>
  {{user.roles}}
</div>

The problem: This does not work (see https://jsfiddle.net/xdzs0hnt/1) - I guess this is because the objects are not the same.

How could I solve this?

25 Oct
5 months ago

ahoi left a reply on Check User's Roles In Checkbox

Hi and thank you very much... :-)

I am going to try this - in the meantime I found another possibility:

https://stackoverflow.com/questions/50648407/checkbox-array-in-vue-js

But if I try to adapt this to my app, it does not work. Actually the objects are not exactly the same.

This is my result: https://jsfiddle.net/xdzs0hnt/1/

How can I solve this?

24 Oct
5 months ago

ahoi started a new conversation Check User's Roles In Checkbox

Hello everybody,

I got this array of objects (roles):

Array (2)
0 {id: 2, name: "admin", guard_name: "web", created_at: "2018-10-21 15:39:14", updated_at: "2018-10-21 15:39:14"}
1 {id: 3, name: "super-admin", guard_name: "web", created_at: "2018-10-22 05:16:00", updated_at: "2018-10-22 05:16:00"}

Now I’d like to create some checkboxes that are checked, if the user has one specific role ((`user.rol):

This is the array:


0 {id: 2, name: "admin", guard_name: "web", created_at: "2018-10-21 15:39:14", updated_at: "2018-10-21 15:39:14", …}
1 {id: 3, name: "super-admin", guard_name: "web", created_at: "2018-10-22 05:16:00", updated_at: "2018-10-22 05:16:00", …}

Now I'd like to show checkboxes that are checked, if the user has a role:

<div v-for="role in roles">
                    <label><input class="uk-checkbox" type="checkbox" :value="role"  v-model="user.roles"> {{ role.name }}</label><br />
</div>

Unfortunately this does not work. The checkboxes are not checked :-/

Maybe someone could help me out here? :slight_smile: Thanks in advance :-)

10 Oct
6 months ago

ahoi started a new conversation Crop An Image / Set New Focus

Hello everybody,

I am using Uikit's upload component ( https://getuikit.com/docs/upload ) to upload an image. Now I am using spatie's media library ( https://github.com/spatie/laravel-medialibrary ) to save those images in different conversions.

/**
     * @param \Spatie\MediaLibrary\Models\Media|null $media
     *
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
     */
    public function registerMediaConversions(Media $media = null)
    {
        $this->addMediaConversion('preview')
            ->fit(Manipulations::FIT_CROP, 400, 320)->withResponsiveImages();
        
        $this->addMediaConversion('thumb')
            ->fit(Manipulations::FIT_CROP, 120, 120);
    }
    ```

This works fine - but now I'd like to get the ability to crop the image - the image manipulation does this already, but the user has no possibility to set an own focus or even zoom the image etc. 

I'd like to extend my existing system to let the user choose the focus (maybe this is a possibility: https://docs.spatie.be/image/v1/image-manipulations/resizing-images#focal-crop )

I am happy for every idea :-) 
29 Sep
6 months ago

ahoi left a reply on Search For Custom Properties On Spatie/laravel-medialibrary

That's a good idea, but unfortunately this does not work with my local setup (php artisan serve on Mac OS) as json1 is not installed.

Well: I need to set up a new local dev environment ;-)

27 Sep
6 months ago

ahoi left a reply on Keep Line Breaks From Text Area

Well @click,

the problem is that the content of the textarea is user-provided content and so I am pretty sure it's a bad idea to disable automatic escaping?

My problem: My preferred wysiwyg-editor saves the text as HTML - so now there are p and br tags I have to handle - but I have to make sure that script or img are still escaped.