mvnobrega

mvnobrega

Member Since 8 Months Ago

Experience Points
3,010
Total
Experience

1,990 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 Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 1
3,010 XP
Sep
18
14 hours ago
Activity icon

Replied to How To Catch A User Who Sent A Message In Chat

I can say it works. But the problem is that in this way, all messages return together.

Imagine that two users have exchanged many messages. This will make the return slower to no avail;

Here's how I get the result:

[
    {
        "id": 2,
        "de_user_id": 1,
        "para_user_id": 2,
        "message": "sou charlote e gostei do seu sonho",
        "created_at": "2020-09-17T20:59:26.000000Z",
        "updated_at": "2020-09-17T20:59:26.000000Z",
        "de_user": {
            "id": 1,
            "lang": "pt-br",
            "username": "charlote",
            "seguidores": 0,
            "seguindo": 0,
            "relatos": 0,
            "avatar": "/avatars/girls/jocelyn.svg",
            "dataNasc": "04/03/1942",
            "genero": "f",
            "subscribe": 1,
            "email": "[email protected]",
            "email_verified_at": null,
            "created_at": "2020-09-17T19:32:43.000000Z",
            "updated_at": "2020-09-17T19:32:43.000000Z"
        }
    },
    {
        "id": 8,
        "de_user_id": 1,
        "para_user_id": 2,
        "message": "mah owww",
        "created_at": "2020-09-17T22:48:21.000000Z",
        "updated_at": "2020-09-17T22:48:21.000000Z",
        "de_user": {
            "id": 1,
            "lang": "pt-br",
            "username": "charlote",
            "seguidores": 0,
            "seguindo": 0,
            "relatos": 0,
            "avatar": "/avatars/girls/jocelyn.svg",
            "dataNasc": "04/03/1942",
            "genero": "f",
            "subscribe": 1,
            "email": "[email protected]",
            "email_verified_at": null,
            "created_at": "2020-09-17T19:32:43.000000Z",
            "updated_at": "2020-09-17T19:32:43.000000Z"
        }
    },
    {
        "id": 11,
        "de_user_id": 1,
        "para_user_id": 2,
        "message": "tudo sim e com vc ?",
        "created_at": "2020-09-18T00:54:14.000000Z",
        "updated_at": "2020-09-18T00:54:14.000000Z",
        "de_user": {
            "id": 1,
            "lang": "pt-br",
            "username": "charlote",
            "seguidores": 0,
            "seguindo": 0,
            "relatos": 0,
            "avatar": "/avatars/girls/jocelyn.svg",
            "dataNasc": "04/03/1942",
            "genero": "f",
            "subscribe": 1,
            "email": "[email protected]",
            "email_verified_at": null,
            "created_at": "2020-09-17T19:32:43.000000Z",
            "updated_at": "2020-09-17T19:32:43.000000Z"
        }
    }
]

Sep
17
1 day ago
Activity icon

Started a new Conversation How To Catch A User Who Sent A Message In Chat

I'm having trouble showing users who have sent messages to other users. See below to understand what I mean:

My Table Messages:

Schema::create('messages', function (Blueprint $table) {
            $table->id();
            $table->integer('de_user_id')->unsigned();
            $table->foreign('de_user_id')->references('id')->on('users');
            $table->integer('para_user_id')->unsigned();
            $table->foreign('para_user_id')->references('id')->on('users');
            $table->text('message');
            $table->timestamps();
        });

I have the page where it will display users who have sent messages to another member:

<section class="conversations">
                <a href="https://www.site.com/profile/messages/username" class="conversation ">
                    <div class="info">
                        <div class="name ">
                            Marcos
                        </div>
                    </div>
                    <div class="date"><span aria-hidden="true" class="fas fa-circle"></span> 3 months ago
                    </div>
                </a>
  </section>

But to display who sent the messages, I need to access the id of who received it in the Message table. Also, I need to get the user who sent it. My problem is that I don't know how to identify who sent it once. So that I get a collection of all messages.

Here's how I'm doing it:

public function msgs(Request $request) {

      $msg = Message::where('para_user_id', $request->user()->id)->get();

      return view('msgs',compact('msg'));
        
    }

But how can I receive many messages from the same user. This solution does not work. I need to catch a single time who sent the message to me, regardless of how many messages were sent. And so, only return the users who sent me messages.

Can you help me ?

Activity icon

Replied to Sort Messages By Date

Thanks :))))

Activity icon

Started a new Conversation Sort Messages By Date

I am creating a simple Chat for my application. I say simple because it will not be in real time.

I only store messages exchanged between two users (one-to-one).

My problem is in displaying the message in order of date. Once the message is received on the left, and the message sent on the right.

The way I am doing it, I am not managing to make this separation. example: https://prnt.sc/uj65qy

In other words, first all messages from one user are displayed and then the message from the other, so that there is no interleaving of data.

I'm doing this...

Chat.vue:

<template>
            <section class="conversation">
                <div class="inner-wrapper">
                    <div class="message own" v-for="my in mymsgs">
                        <div class="body">{{my.message}}</div>
                        <div class="meta">
                            <div title="Mon, Jan 13, 2020 6:31 AM GMT" class="time">You, {{my.formatted_created_at}}</div>
                            <span class="fal fa-trash-alt"></span>
                        </div>
                    </div>
                    <div class="message" v-for="u in usermsgs">
                        <div class="body">{{u.message}}</div>
                        <div class="meta">
                            <div title="Mon, Jan 13, 2020 11:50 AM GMT" class="time">Finley, {{u.formatted_created_at}}</div>
                            <!---->
                        </div>
                    </div>
                </div>
            </section>
            <section class="reply">
                <div>
                    <textarea placeholder="Escreva sua mensagem..." v-model="newmsg"></textarea>
                    <div class="action-row">
                        <div class="actions">
                            <button dusk="send-message-button" @click="sendMsg()" class="btn btn-action-2">
                                <span>Enviar</span>
                            </button>
                        </div>
                    </div>
                </div>
            </section>

</template>

<script>
    export default {
        props: ['avatar','username', 'userid'],
        data(){
            return {
                newmsg: '',
                mymsgs: [],
                usermsgs: [],

            }
        },
        mounted() {
            axios
              .get('/api/chat/getmsgs')
              .then(response => {
                this.mymsgs = response.data.mymsgs;
                this.usermsgs = response.data.usermsgs;
            })
        },
        }
        

    }
</script>

My Controller:

public function getMsgs(Request $request) {

        $mymsgs = Message::where('de_user_id', $request->user()->id)->get()
        ->each(function ($mymsgs) {
            $mymsgs->formatted_created_at = $mymsgs->created_at->format(__('notifications.dateformat'));
            });

        $usermsgs = Message::where('para_user_id', $request->user()->id)->get()
        ->each(function ($usermsgs) {
            $usermsgs->formatted_created_at = $usermsgs->created_at->format(__('notifications.dateformat'));
            });

        return response()->json(['mymsgs' => $mymsgs, 'usermsgs' => $usermsgs]);
        
    }

Is there a solution to my problem within the logic I'm working on?

Note that I store each user's messages in separate variables. Any suggestion?

Sep
14
4 days ago
Activity icon

Started a new Conversation Because My Date Ends With ".000000Z"

I'm having trouble displaying the notification date correctly.

In the laravel notification table, the date is stored correctly like this: 2020-09-14 15:28:21

But when I get this date for display, it is returned like this: created_at: "2020-09-14T15: 28: 21.000000Z"

So my date appears correct on the display, but the time is never the same.

I'm doing this to capture notifications:

$notifications = $request->user()->notifications()
        ->limit(7)
        ->get()
        ->each(function ($notification) {
            $notification->formatted_created_at = $notification->created_at->format(__('notifications.dateformat'));
      });

And I get this:

0:
created_at: "2020-09-14T15:28:21.000000Z"
data: Object
formatted_created_at: "14/09/2020 03:09:21"
id: (...)
notifiable_id: (...)
notifiable_type: (...)
read_at: (...)
type: (...)
updated_at: (...)

Formatted_created_at doesn't seem to be forming the date correctly due to this strange format in created_at (but the database is correct).

That is, when it comes to listing the notifications, the date appears correct, but the time always returns 03:09 and only the seconds vary, that is:

03:09:08 | 03:09:31 | 03:09:54 ...

What is happening ?

Sep
13
5 days ago
Activity icon

Awarded Best Reply on Date Format In Notifications Table

A member of another forum gave the solution. Follow for those who need it:

To return the results fast, you might do something like this:

$notifications = $user->notifications()
    ->limit(7)
    ->get()
    ->each(function ($notification) {
        $notification->formatted_created_at = $notification->created_at->format('d/m/Y');
    });

I suggest that you do it properly and create a new API resource.

use Illuminate\Http\Resources\Json\JsonResource;

class NotificationResource extends JsonResource
{
    /**
     * Transform the notification into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            // ...
            'formatted_created_at' => $this->created_at->format('d/m/Y'),
        ];
    }
}

// In the controller action
$notifications = $user->notifications()
    ->limit(7)
    ->get();

return NotificationResource::collection($notifications);
Activity icon

Replied to Date Format In Notifications Table

A member of another forum gave the solution. Follow for those who need it:

To return the results fast, you might do something like this:

$notifications = $user->notifications()
    ->limit(7)
    ->get()
    ->each(function ($notification) {
        $notification->formatted_created_at = $notification->created_at->format('d/m/Y');
    });

I suggest that you do it properly and create a new API resource.

use Illuminate\Http\Resources\Json\JsonResource;

class NotificationResource extends JsonResource
{
    /**
     * Transform the notification into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            // ...
            'formatted_created_at' => $this->created_at->format('d/m/Y'),
        ];
    }
}

// In the controller action
$notifications = $user->notifications()
    ->limit(7)
    ->get();

return NotificationResource::collection($notifications);
Activity icon

Started a new Conversation Date Format In Notifications Table

I need to define the date format for a collection. I tried it that way, but it doesn't work:

return response()->json($request->user()->notifications()->format('d/m/Y')->limit(7)->get());

How could I set the date format for an entire collection?

Activity icon

Started a new Conversation How To Get Relationship Within "with->"

I need to generate the content url when sending notifications in laravel. And I thought of the following solution:

$url = Comment::where('id', $request->commentId)->with('relato')->get();
$author->notify((new PostSubComment($novo->user,$url))->locale($request->idioma));

So far it's working. But the category relationship remains to be found, which is within Model Relato.

How do I get this Category relationship, which is within the Relato Model?

Is it possible to do this using with->('relato')?

I tried something like this, but it doesn't work: with->(relato()->category);

Any suggestion ?

Sep
12
6 days ago
Activity icon

Replied to Notification Data Empty

Thanks :))

Sep
11
1 week ago
Activity icon

Awarded Best Reply on Notification Data Empty

I found the problem.

Just restarted it: php artisan queue: work

Activity icon

Replied to Notification Data Empty

I found the problem.

Just restarted it: php artisan queue: work

Activity icon

Started a new Conversation Notification Data Empty

Notifications are not recording data in the database. I tried it with toDatabase and it also didn't work. Look:

<?php

namespace App\Notifications;

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

class NovoSeguidor extends Notification implements ShouldQueue
{
    use Queueable;

    private $user;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(user $user)
    {
        $this->user = $user;
    }

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

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line("Novo seguidor: {$this->user}")
                    ->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 [
            'teste' => 'Hello',
        ];
    }
}


My column data return []

Can you help me ?

Activity icon

Started a new Conversation Remove Slow Email Notifications

I plan to prevent the user who issues an email notification from waiting for the email to be sent.

For example, when a user follows another, an email notification is sent, but this takes a few more seconds, so the user has to wait for the email to be sent before "Following" appears.

How can I delay sending email notifications without impacting user experiences?

I'm doing this:

public function follow($userId) {
      $user = User::find($userId);
      $user->followers()->attach(auth()->user()->id);
      $user->increment('seguidores', 1);	

      $author = $user;
      $author->notify(new NovoSeguidor(\Auth::user()));


    }
Sep
09
1 week ago
Activity icon

Started a new Conversation How To Access Two Different Relationships

I need to access a relationship, but it doesn't work the way I'm trying. Look:

Comment Model:

class Comment extends Model
{

    public function relato()
    {
        return $this->belongsTo('App\Relato');
    }

}

Relato Model:

class Relato extends Model
{
    public function grupo()
    {
        return $this->belongsTo('App\Grupo');
    }

}

From the comments model I need to access a table in the group model, so that I can use the decrement in the Comments column in the Groups table.

Here's how I'm doing it:

public function deletecomment($commentId) {

      $comment = Comment::find($commentId);

       if($comment){
          $comment->relato()->decrement('comments', 1);
          $comment->relato()->grupo()->decrement('comments', 1);
          $comment->delete();
       }
           
    }

The decrement in the table relatos works perfectly. however, the following: $comment->relato()->grupo()->decrement('comments', 1); This does not work and returns the error: Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::grupo()

Can you help me ?

Sep
08
1 week ago
Activity icon

Started a new Conversation Get Route With Paramaters In Props And Use V-for Template

I'm having trouble generating urls that need parameters within the v-for in the template. Look:

My component

<template>
<div style="display:contents;">
    <div class="relatos" v-for="r in relatos">
        
        <div class="meta">
            <div class="avatar has-photo"><img src="" /></div>
            <div class="meta-rel"><a class="decoration-none" href="a"><span class="cat-rel">a</span></a></div>
        </div>
        <div class="author">
            <h3><a :href="urlrelato">{{r.titulo}}</a></h3>
        </div>
        <div class="meta-perfil-relatos">
            <div><span aria-hidden="true" class="fas fa-thumbs-up"></span>b</div>
            <div><span aria-hidden="true" class="fas fa-comments"></span>f</div>
            <div><span aria-hidden="true" class="fas fa-calendar-alt"></span>f</div>
        </div>
    </div>

     <div class="mostrar-mais" v-if="relatos.length >= 3" @click="getRelatos()">
        <span class="show-more-message">
        <span>Mostrar mais</span>
        <i class="fas fa-chevron-down" v-if="!loading"></i>
        <i class="fa-spin"v-else></i>
        </span> 
    </div>
</div>
</template>

<script>
    export default {
        props: ['userid','urlrelato'],
        data(){
            return {
                relatos: [],
                page: 1,
                loading: false,
            }
        },
        mounted() {
            axios
              .get('/api/perfil/getrelatos/'+this.userid+'?page='+this.page)
              .then(response => (this.relatos = response.data.data, this.page++))
        },
        methods: {
            getRelatos(){
                this.loading = true;
                axios.get('/api/perfil/getrelatos/'+this.userid+'?page='+this.page, {

                })
                .then(response => {
                    this.page = this.page + 1;  
                    this.relatos = this.relatos.concat(response.data.data);
                    this.loading = false;           
                })
                .catch( error => {
                    this.loading = false;
                });
           },

        }
        

    }
</script>

My blade:

<perfil-tabs 
   userid="{{$user->id}}"
   urlrelato="{{localized_route('relatoUser', [$r->grupo->slug, $r->slug])}}">
 </perfil-tabs>

The urlreport will be generated dynamically according to the data received by axios. However, this url needs two parameters.

If I use laravel's @foreach instead of v-for, I will have trouble creating "Load more" dynamically.

Any suggestions to resolve this?

Sep
07
1 week ago
Activity icon

Replied to Get Array Inside Array

Thanks :))

Activity icon

Started a new Conversation Get Array Inside Array

I am creating an infinite paging system and I came across a small problem. Look:

My component:

<template>
<div>
    <button @click="getRelatos()">Adicionar</button>
    <div class="relatos" v-for="r in relatos">
         
        <div class="meta">
            <div class="avatar has-photo"><img src="" /></div>
            <div class="meta-rel"><a class="decoration-none" href="a"><span class="cat-rel">a</span></a></div>
        </div>
        <div class="author">
            <h3><a href="s">{{r.titulo}}</a></h3>
        </div>
        <div class="meta-perfil-relatos">
            <div><span aria-hidden="true" class="fas fa-thumbs-up"></span>b</div>
            <div><span aria-hidden="true" class="fas fa-comments"></span>f</div>
            <div><span aria-hidden="true" class="fas fa-calendar-alt"></span>f</div>
        </div>
    </div>
</div>
</template>

<script>
    export default {
        props: ['userid'],
        data(){
            return {
                relatos: [],
                page: 1,
            }
        },
        mounted() {
            axios
              .get('/api/perfil/getrelatos/'+this.userid+'?page='+this.page)
              .then(response => (this.relatos = response.data.data, this.page++, console.log(this.relatos)))
        },
        methods: {
            getRelatos(){
                this.loading = 2;
                axios.get('/api/perfil/getrelatos/'+this.userid+'?page='+this.page, {

                })
                .then(response => {
                    this.page = this.page + 1;  
                    this.relatos.push(response.data.data);
                               
                })
                .catch( error => {
                       
                });
           },

        }
        

    }
</script>

As soon as the page loads, the relatos array is created and loaded on the page.

When you click @click, the getRelatos() function is called to display the remaining elements. However, on the second call, the push returns another Array of elements, so that the array is organized in this way:

0: {…}
1: {…}
2: (2) [{…}, {…}, __ob__: Observer]

That is, a new array is added within the arrray that was already created, so that the v-for does not work as expected.

I need the push to add the data so that the result looks like this:

0: {…}
1: {…}
2: {…}
3: {…}

How can I solve this?

Sep
05
1 week ago
Activity icon

Replied to Date Format In Multilingual Site

I appreciate your help. Defining the model as you said seems like a good alternative too.

But I ended up choosing to define the format like this:

{{ $comments->created_at->format( __('dateformat')) }}">
Activity icon

Replied to Date Format In Multilingual Site

but I need to define the format, because I don't want you to display the time

Activity icon

Started a new Conversation Date Format In Multilingual Site

The dates in the comment table follow the laravel's own timestamps pattern. That is, both created_at and updated_at are stored as follows: 2020-09-05 20:04:08

However, the site is multi-language, and I need to format the date according to the language directly on the controller. Look:

Controller Comments:

public function relatoUser(Request $request) {

            $comments = Comment::where('relato_id', $request->id)->paginate(10);
          
            return view('userRelato', compact('comments')); 
        
    }

My blade:

@foreach($comments as $c)

                <card-comment 
                created="{{ $comments->created_at->format('d/m/Y') }}">
                </card-comment>

@endforeach

But in this way, in all languages the graduate will appear in the Brazilian standard. Is there a way for me to determine this format still in the controller after checking the language that makes the request?

So I put just that {{ $comments->created_at }} and the date appears according to the user's language.

Sep
03
2 weeks ago
Activity icon

Started a new Conversation Relationship With Paginate In Foreach

I need to create a dynamic link to take the user to the last page of the laravel page. For example, if there is a pagination, I need to include lastPage () at the end of the url www.site.com/forum/slug?page=2

otherwise it goes to the normal page.

But I need to do this logic on another controller, which in turn is not working. See my relationships and how I'm doing:

public function grupoPerfil($slug) {


        $grupo = Grupo::where('slug', $slug)->first();

        $comments = Comment::whereHas('relato', function ($query) use ($grupo) {
            return $query->where('grupo_id', $grupo->id);
        })->paginate(10);


        if($grupo){

            $rels = $grupo->relatos()->with('user')->paginate(20);
            
            return view('grupo', compact(['grupo', 'rels','comments']));
            
        }

        abort(404);    
        
    }

my blade:

@foreach($rels->sortByDesc('updated_at') as $r)

                <card-relatos 
                url="{{localized_route('relatoUser', [$r->grupo->slug, $r->slug])}}"
                getpaginate="{{ $comments->lastPage() }}"
                </card-relatos>

 @endforeach

But getpaginate always returns 2, as it is not related to relato_id. How do I solve this?

Activity icon

Replied to Relationship Paginate Does Not Work

I just discovered another problem. In my case, I am conducting a foreach to capture all reports. And the solution given does not relate the comment to the "relatos"

That is, That is, I am doing this:

@foreach($rels->sortByDesc('updated_at') as $r)

                <card-relatos 
                url="{{localized_route('relatoUser', [$r->grupo->slug, $r->slug])}}"
                getpaginate="{{ $comments->lastPage() }}"
                </card-relatos>

 @endforeach

But getpaginate always returns 2, as it is not related to relato_id. How do I solve this?

Sep
02
2 weeks ago
Activity icon

Started a new Conversation Relationship Paginate Does Not Work

I need to create a dynamic link to take the user to the last page of the laravel page. For example, if there is a pagination, I need to include lastPage () at the end of the url www.site.com/forum/slug?page=2

otherwise it goes to the normal page.

But I need to do this logic on another controller, which in turn is not working. See my relationships and how I'm doing:

Model Grupo:

class Grupo extends Model
{
   	public function relatos()
        {
        return $this->hasMany('App\Relato');
        }
}

Model Relato:

class Relato extends Model
{

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

}

Getting pagination:

public function grupoPerfil($slug) {


        $grupo = Grupo::where('slug', $slug)->first();

        $comments = $grupo->relatos()->comments()->paginate(10);

            
         return view('grupo', compact(['grupo', 'comments']));
            
        
    }

But when I call the function {{ $comments->lastPage() }}, it always returns 1, and it should return the last page which is 3

Whats wrong ?

Sep
01
2 weeks ago
Activity icon

Replied to Convert Quote To Html

I found this solution, but when I try to test it doesn't work:

$string = "[quote=mvneobux]interessante e bom continue[/quote]";
echo preg_replace('#\[quote=(.+?)\]\[/quote\]#', '<blockquote>Post user: </blockquote>', $string);

It seems to me that the solution is this. But I'm having trouble getting it to work as I need it.

Can someone help me ?

Aug
31
2 weeks ago
Activity icon

Started a new Conversation Convert Quote To Html

I am creating a discussion forum and I need to convert the comments citations to html.

For example, if I want to quote a comment, the text field will appear as follows: [quote=mvneobux]Meu primeiro comentário[/quote]

But I need to convert it to HTML before storing it in the database. Thus:

<div class="quote">
    <div class="author">mvneobux:</div>
 	Meu primeiro comentário.
</div>

And in the same way I need to do the reverse logic if the user wants to edit the comment with a quote.

How can I do this ? Can anyone give me a tip or example of how I could do this logic using VUejs and laravel?

My cardcomment.vue

<template>
<div id="new-comment" class="reply-wrapper" v-if="modalPostComment">
    <h3>Escreva seu comentário</h3>
    <textarea autofocus="autofocus" maxlength="15000" placeholder="Comentário..." v-model="commenttext"></textarea>
    <span v-if="errorPostComment['comment']" class="invalid-feedback" role="alert">
        <strong>* {{errorPostComment['comment'][0]}}</strong>
    </span>
    <div class="action-row">
        <div class="left"></div>
        <div class="right">
            <button class="btn btn-default" @click="modalPostComment = false">Cancelar</button>
            <button class="btn btn-green" v-if="!postCommentLoading" @click="postComment()"><span>Enviar</span></button>
            <button class="btn btn-green" v-if="postCommentLoading" style="background-color: #95cccd;">
                <span><span class="fa-spin"></span> Enviando...</span>
            </button>
        </div>
    </div>
</div>

</template>
export default {
    created() {
        this.$eventBus.$on("commentquote", (comment, username) => {
            this.modalPostComment = true;
            this.commenttext = "[quote=" + username + "]" + comment + "[/quote]";
            this.$nextTick(() => document.getElementById("new-comment").scrollIntoView({ behavior: "smooth" }));
        });
    },
    beforeDestroy() {
        this.$eventBus.$off("commentquote");
    },
    postComment() {
        this.postCommentLoading = true;
        axios
            .post("/api/postcomment", {
                relatoId: this.relatoid,
                grupoId: this.grupoid,
                comment: this.commenttext,
            })
            .then((response) => {
                window.location.href = "";
            })
            .catch((error) => {
                if (error.response.status == 401) {
                    this.$eventBus.$emit("login");
                }
                this.postCommentLoading = false;
            });
    },
};

My usercomment.vue

<button class="btn btn-default quote" @click="$eventBus.$emit('commentquote', getcomment,username)"><span aria-hidden="true" class="fas fa-quote-right"></span></button>
Aug
27
3 weeks ago
Activity icon

Started a new Conversation Use Count Or Total Value In Column

I need to add the number of followers that a given user has. If I use count(), can't that make processing unnecessary every time the page loads?

Let's suppose that a user has 10 million followers, if I use count() a slightly slower processing can occur, right?

In this case, I'm thinking of using a column in the Users table to store the total in one place.

Does it make sense for me to think that way?

Aug
26
3 weeks ago
Aug
25
3 weeks ago
Activity icon

Started a new Conversation Search For Words Between Strings

I want to do a simple search system without using extensions or packages.

Currently my consultation is as follows:

public function sonhos(Request $request) {

        $query = $request->q;

        $terms = preg_split('/\s+/', $query, -1, PREG_SPLIT_NO_EMPTY); 
        
        $result = Grupo::where('lang', \App::getLocale())->where(function ($q) use ($terms) {
                
          foreach ($terms as $key) {
                $q->orWhere('titulo', 'like', "{$key}%");
                $q->orWhere('titulo', 'like', "%{$key}");
          }
        })->get();

        $grupos = Grupo::paginate(9);

        return view('sonhos', compact(['grupos','result']));
    }

The way I'm doing it, he doesn't look for words within a sentence.

But if I enter %{$key}%, then it is no longer necessary, because if I put a letter "a" in the search it returns all records that have that letter.

How do I search only for words within sentences and not for any correspondence?

Activity icon

Started a new Conversation Convert App.js To Components

Is it possible to take app.js from a website and turn it into components?

In other words, I need to decompile it to make it readable.

I am using the structure of a website as references, and I would like to better understand how they organized the components.

is for this app.js: https://static.neris-assets.com/js/app.js?id=95e89f07808781ad9993

Is it possible to do that ?

Aug
22
3 weeks ago
Activity icon

Replied to Open Modal In Other Component

Thanks for the suggestion. I looked for "global event dispatcher" on google and ended up finding this short article that goes straight to the point: https://medium.com/@jeffochoa/vue-basic-component-communication-using-an-event-dispatcher-be4823f006bf

Aug
21
4 weeks ago
Activity icon

Started a new Conversation Open Modal In Other Component

I have the navbar component that has all the login logic and the login modal. However, I need to open this login modal via @click from another component.

How could I set the modalLogin to true in the component navbar with the click performing inside another component?

My navbar.vue:

<div class="app-modal" v-show="modalLogin">
 
</div>

My grupo.vue

<a :href="urlRelato" v-if="$isguest" @click.prevent="$emit('login')" class="btn btn-green">Deixe seu relato</a>

my app.blade:

<nav-bar  :lang="{{ json_encode(__('navbar')) }}" @login="modalLogin = true">  </nav-bar>

My grupo.blade:

<grupo url-relato="{{localized_route('novoRelato', $grupo->slug)}}"></grupo>

I saw on some topics that $emit could work. But it did not work. Can you help me ?

Activity icon

Replied to Vue.prototype Not Working

yes, I fixed it for isguest and changed it to:

Vue.prototype.$isguest = JSON.parse(document.getElementById('app').getAttribute('isguest'));

and it worked perfectly.

I ask you for disruptions once again. Thank you

Activity icon

Replied to Vue.prototype Not Working

God, I tried everything and I didn't find the problem. Thank you and sorry for my carelessness

Activity icon

Started a new Conversation Vue.prototype Not Working

I made a simple prototype, but it doesn't work and I don't understand why.

My prototype:

Vue.prototype.$isguest = document.getElementById('app').getAttribute('isguest');

My app.blade.php

 <div id="app" @auth user="{{ json_encode(Auth::user()) }}" @endauth isquest="{{ json_encode(auth()->guest()) }}">

        <nav-bar 
            :lang="{{ json_encode(__('navbar')) }}">    
        </nav-bar>
</div>

My navbar camponent:

<div class="navbar" v-if="$isguest">
//navbar
</div>

<div v-else>
//navbar
<div>

But it doesn't work as expected. It always falls on the v-else, as if it were not recognizing the value captured in the prototype.

Can anyone tell me what's going on ?

Aug
19
4 weeks ago
Aug
18
1 month ago
Activity icon

Replied to ScrollIntoView On The Search Page

<template>
    <main class="q-ma">
    <main class="section qs-o">
        <section class="profile-link font-color">
            <h1>{{ lang.title }}</h1>
            <p>{{ lang.desc }}</p>
            <div name="buscar">
                <div class="input-wrapper with-icon">
                    <span v-if="!loading" @click.prevent="buscar()" class="fal fa-search"></span>
                    <span v-if="loading" class="fa-spin"></span> 
                    <input @keyup.enter.prevent="buscar()" v-model="keyword" :placeholder="lang.inputPlaceh" required>
                </div>
            </div>
        </section>
        <main class="testimonials view">
            <div class="container">
                <h2 id="buscou" class="blog-h2">
                {{ showTitle ? 'Você buscou por: '+keywordTitle : lang.sonhos }} </h2>
                <section class="list">
                    
                    <div class="testimonial" v-if="maisVistos" v-for="g in maisVistos">
                        <div class="meta">
                            <div class="avatar has-photo"><img :src="'/'+g.foto"></div>
                            <div class="meta-perfil-relatos">
                                <div><span aria-hidden="true" class="fas fa-calendar-alt"></span>0</div>
                                <div><span aria-hidden="true" class="fas fa-thumbs-up"></span>0</div>
                                <div><span aria-hidden="true" class="fas fa-comments"></span>85</div>
                            </div>
                        </div>
                        <div class="author">
                            <h2>{{ g.titulo }}</h2>
                        </div>
                        <div class="btn-sonhos"><a href="http://127.0.0.1:8022/pt-br/sonhos/sonhar-com-freud" class="btn btn-action">{{ lang.entrar }}<span aria-hidden="true" class="far fa-arrow-right"></span></a></div>
                    </div>
                    <div v-else class="not-result">
                        <p>Nenhum resultado</p>    
                    </div>

                </section>
            </div>
        </main>
    </main>
</main>
</template>

<script>
    export default {
        props: ['lang'],
        mounted(){
            axios
              .get('/api/buscar?lang='+document.documentElement.lang)
              .then(response => (this.maisVistos = response.data.data))
        },
        data(){
            return {
                maisVistos: '',
                keyword: '',
                keywordTitle: '',
                showTitle: false,
                loading: false,             
            }
        },
        methods: {
            buscar() {
                this.loading = true;
                axios.get('/api/buscarquery?lang='+document.documentElement.lang+'&chave='+this.keyword, {         

                })
                .then(response => {
                    this.maisVistos = response.data;
                    this.showTitle = true;
                    this.keywordTitle = this.keyword;
                    document.getElementById('buscou').scrollIntoView({ behavior: 'smooth' });
                    this.loading = false;
                    
                })
                .catch( error => {
                    this.loading = false;
                    if (error.response.status == 422) {
                        this.cadastrar.errors = error.response.data.errors;
                       
                    }
                });
            },
        }
        
    }
</script>
Activity icon

Started a new Conversation ScrollIntoView On The Search Page

I have a simple problem, but I don’t know how to solve it.

My search page is done by axios, without realoading the page. When the user searches, the page must be scrolled down to the lowest id.

however, if a user searches and it returns nothing, the following query (which returns content) does not scroll down, as the gift has been dynamically updated. In this case, only the second click would take you down.

My code looks like this:

methods: {
            buscar() {
                axios.get('/api/buscarquery?lang='+document.documentElement.lang+'&chave='+this.keyword, {         

                })
                .then(response => {
                    document.getElementById('buscou').scrollIntoView({ behavior: 'smooth' });
                })
                .catch( error => {

                });
            },
        }

How do I make scrollIntoView work when the result is empty and, consequently, there is no scroll bar. Only after the data is inserted dynamically does the scroll bar appear, but my code doesn’t seem to recognize it at first, but on the second attempt.

can you help me ?

Activity icon

Started a new Conversation Search Multiple Words And Full Text

I need a search field that works for both words and the full text.

What is the best logic to prevent a search for 3 words that exists in the database, also return the result for each word separately?

I'm currently doing this:

 public function search(Request $request) {

    	$busca = $request->chave;

        $terms = preg_split('/\s+/', $busca, -1, PREG_SPLIT_NO_EMPTY); 
        
        $result = Grupo::where('lang',$request->lang)->where(function ($q) use ($terms) {
          foreach ($terms as $key) {
                $q->orWhere('titulo', 'like', "%{$key}%");
          }
        })->get();

        return response()->json($result);
    }
Aug
16
1 month ago
Activity icon

Replied to Schema Database For Quiz Answer

Right!

I'll do it the conventional way then.

Thanks for the suggestions

Activity icon

Replied to Schema Database For Quiz Answer

That's good logic, yes. But I want to avoid using Joins as much as possible. As it is a multi-language site, it can have many users responding and quickly have a very large database.

I'm almost doing it the way you suggested. But using a single column to store all the questions and another column to store all the answers in JSON format, it seems very nice

Is it really a bad idea to store JSON in a single table?

Activity icon

Started a new Conversation Schema Database For Quiz Answer

I am working on a personality test that will contain 112 questions.

Instead of creating 112 columns, like this:

 Schema::create('grupos', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->integer('q1')->default(0);
            $table->integer('q2')->default(0);
            $table->integer('q3')->default(0);
            $table->integer('q4')->default(0);
            //....
            $table->integer('q112')->default(0);	
        });

I thought of creating a single column $table->text('answer'); and store a java script object, like so:

answer: {
    1: 50,
    2: 47,
    3: 12,
    ....
    112: 33,
}

This way my database is cleaner. For I store the answers to the questions in a single column.

But as it will be a field that will be updated whenever a new test is answered, I would like to know your opinion if this is a good practice or if I could have a problem in the future.

What do you think ?

Aug
15
1 month ago
Activity icon

Replied to Update Prototype Outside The Instance

Very good. Thanks (Y)

Activity icon

Started a new Conversation Update Prototype Outside The Instance

My App.js:

Vue.prototype.$user = JSON.parse(document.getElementById('app').getAttribute('user'));

const app = new Vue({
    el: '#app',
});

I'm passing the authenticated user's data to:

<div id="app" @auth user="{{ json_encode(Auth::user()) }}" @endauth>

In the component navbar I insert the image like this:

<div class="avatar"><img :src="$user.avatar"></div>

When the user changes the avatar in the account preferences, I need to dynamically update the navbar avatar without screen refresh. I'm doing this:

updateAvatar(e) {
                  updateAvatar(e) {
                    axios.post('/api/prefer/avatar', {
                        avatar: this.prefer.slugAvatar,
                    })
                    .then(response => {
                        this.$user.avatar = e;
                        window.location.href = '';
                       
                    })
                    .catch( error => {

                    });  
                },

But insert this.$user.avatar = e doesn't work.

ow can I dynamically update this prototype?