Laravel Livewire real time chat application part 5
App/Http/Livewire
Messages.php
<?php
namespace App\Http\Livewire;
use App\Models\Message;
use Livewire\Component;
use App\Models\User;
class Messages extends Component
{
public $message;
public $allmessages;
public $sender;
public function render()
{
$users=User::all();
$sender=$this->sender;
$this->allmessages;
return view('livewire.messages',compact('users','sender'));
}
public function mountdata()
{
if(isset($this->sender->id))
{
$this->allmessages=Message::where('user_id',auth()->id())->where('receiver_id',$this->sender->id)->orWhere('user_id',$this->sender->id)->where('receiver_id',auth()->id())->orderBy('id','desc')->get();
}
}
public function resetForm()
{
$this->message='';
}
public function SendMessage()
{
$data=new Message;
$data->message=$this->message;
$data->user_id=auth()->id();
$data->receiver_id=$this->sender->id;
$data->save();
$this->resetForm();
}
public function getUser($userId)
{
$user=User::find($userId);
$this->sender=$user;
$this->allmessages=Message::where('user_id',auth()->id())->where('receiver_id',$userId)->orWhere('user_id',$userId)->where('receiver_id',auth()->id())->orderBy('id','desc')->get();
}
}
Views
livewire/messages.blade.php
<div>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-4">
<div class="card">
<div class="card-header">
Users
</div>
<div class="card-body chatbox p-0">
<ul class="list-group list-group-flush">
@foreach($users as $user)
<a wire:click="getUser({{$user->id}})" class="text-dark link">
<li class="list-group-item">
<img class="img-fluid avatar" src="https://cdn.pixabay.com/photo/2017/06/13/12/53/profile-2398782_1280.png">
<i class="fa fa-circle text-success online-icon"></i> {{$user->name}}
<div class="badge badge-success rounded"> 20 </div>
</li>
</a>
@endforeach
</ul>
</div>
</div>
</div>
<div class="col-md-8">
<div class="card">
<div class="card-header">
@if(isset($sender)) {{$sender->name}} @endif
</div>
<div class="card-body message-box" wire:poll="mountdata">
@if(filled($allmessages))
@foreach($allmessages as $mgs)
<div class="single-message @if($mgs->user_id == auth()->id()) sent @else received @endif">
<p class="font-weight-bolder my-0">{{$mgs->user->name}}</p>
{{ $mgs->message}}
<br><small class="text-muted w-100">Sent <em>{{$mgs->created_at}}</em></small>
</div>
@endforeach
@endif
</div>
<div class="card-footer">
<form wire:submit.prevent="SendMessage">
<div class="row">
<div class="col-md-8">
<input wire:model="message" class="form-control input shadow-none w-100 d-inline-block" placeholder="Type a message" required>
</div>
<div class="col-md-4">
<button type="submit" class="btn btn-primary d-inline-block w-100"><i class="far fa-paper-plane"></i> Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Models
Message.php
public function user()
{
return $this->belongsTo(User::class);
}
No comments