I am creating a chat in Laravel Websocket i followed a youtube tutorial and the message goes to the other user they can talk with each other but i need to reload the page to get the message that was sent,its not real time.At the console before i send a message it says this error: Failed to load resource: the server responded with a status of 404 (Not Found) and than after sending says this POST http://127.0.0.1:8000/broadcasting/auth 404 (Not Found) .I have run "php artisan websocket:serve" command in terminal.Thanks in advance
ChatsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Message;
use App\Events\MessageSent;
class ChatsController extends Controller
{
public function __construct()
{
$this->middleware('auth');//only authenticated users can acces to chat
}
public function index()
{
return view('chats');
}
public function fetchMessages()
{
return Message::with('user')->get();
}
public function sendMessage(Request $request)
{
$message = auth()->user()->messages()->create([
'message' => $request->message
]);
broadcast(new MessageSent($message->load('user')))->toOthers();
return ['status' => 'success'];
}
}
User.php
public function messages()
{
return $this->hasMany(Message::class);
}
Message.php
public function user()
{
return $this->belongsTo(User::class);
}
web.php
<?php
use App\User;
use App\Department;
use App\Events\WebsocketDemoEvent;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
broadcast(new WebsocketDemoEvent('some data'));
return view('welcome');
});
Route::get('/page', function () {
return view('admin.page');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth','admin']], function () {
Route::get('/role-register','Admin\DashboardController#registered');
Route::delete('/role-delete/{id}', 'Admin\DashboardController#registerdelete');//delete user
Route::post('/save-user', 'Admin\DashboardController#store');
Route::get('/department', 'Admin\DepartmentController#index');
Route::post('/save-department', 'Admin\DepartmentController#store');
Route::get('/department-edit/{id}', 'Admin\DepartmentController#edit');//edit department
Route::put('/department-update/{id}', 'Admin\DepartmentController#update');
Route::delete('/department-delete/{id}', 'Admin\DepartmentController#delete');//delete department
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/chats', 'ChatsController#index');//chats
Route::get('/messages', 'ChatsController#fetchMessages');//messages
Route::post('/messages', 'ChatsController#sendMessage');//messages
Route::get('/dashboard', 'Admin\DashboardController#dbcheck');//DATABASE
Route::get('/user-edit/{id}', 'HomeController#registeredit');
Route::get('/role-edit/{id}', 'Admin\DashboardController#registeredit');//edit user
Route::put('/role-register-update/{id}', 'Admin\DashboardController#registerupdate');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('store_image', 'StoreImageController#index');
Route::post('store_image/insert_image', 'StoreImageController#insert_image');
Route::get('store_image/fetch_image/{id}', 'StoreImageController#fetch_image');
Route::get('/page',array('as'=>'jquery.treeview','uses'=>'Admin\DepartmentController#treeView'));
Route::get('/pageusers', 'Admin\DepartmentController#usersdep');
ChatsComponent.vue
<template>
<div class="row">
<div class="col-8">
<div class="card card-default">
<div class="card-header">Messages</div>
<div class="card-body p-0">
<ul class="list-unstyled" style="height:300px; overflow-y:scroll">
<li class="p-2" v-for="(message, index) in messages" :key="index">
<strong>{{ message.user.name }}</strong>
{{ message.message }}
</li>
</ul>
</div>
<input
#keyup.enter="sendMessage"
v-model="newMessage"
type="text"
name="message"
placeholder="Enter your message"
class="form-control">
</div>
<span class="text-muted">user is typing...</span>
</div>
<div class="col-4">
<div class="card card-default">
<div class="card-header">Active Users</div>
<div class="card-body">
<ul>
<li class="py-2">{{ user.name }}</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props:['user'],
data() {
return {
messages: [],
newMessage:''
}
},
created() {
this.fetchMessages();
Echo.join('chat')
.listen('MessageSent',(event) => {
this.messages.push(event.message);
})
},
methods: {
fetchMessages() {
axios.get('messages').then(response => {
this.messages = response.data;
})
},
sendMessage(){
this.messages.push({
user: this.user,
message: this.newMessage
});
axios.post('messages', {message: this.newMessage});
this.newMessage = '';
}
}
}
</script>
MessageSent.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 App\Message;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
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 PresenceChannel('chat');
}
}
Sorry to post this as an answer, but you need 50 reputation to place a comment.
Did you uncomment the App\Providers\BroadcastServiceProvider::class, line in your config/app.php?
Related
I'm trying to call a variable from a table, but I'm getting an error "Undefined variable $user". I'm trying to make the program display the Username from the user from the table.
I'm using 2 tables, tribes which represents something like a group, and a user which represents.. well.. user.
So I'm trying to connect the two by displaying the creator of a certain "tribe".
User controller:
<?php
namespace App\Http\Controllers;
Use App\Models\User;
use Illuminate\Http\Request;
class tribesController extends Controller
{
public function index($user)
{
$user = User::findOrFail($user);
return view('home',[
'user'=>$user,
]);
}
}
Homepage:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
{{ $user->username }}
</div>
</div>
</div>
</div>
</div>
#endsection
Router:
<?php
use Illuminate\Support\Facades\Route;
/*
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', function () {
return view('home');
});
Route::get('/playlist', function () {
return view('playlist');
});
Route::get('/tribe', function () {
return view('tribe');
});
Route::get('/edit', function () {
return view('edit');
});
Auth::routes();
Route::get('/tribe/{user}', [App\Http\Controllers\TribesController::class, 'index'])->name('tribe.index');
Database file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTribesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tribes', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->string('genre');
$table->string('filepath')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tribes');
}
}
model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class tribe extends Model
{
public function user(){
return $this->belongsTo(User::class);
}
use HasFactory;
}
You are treating the url parameter as a object, it can't be an object until you get it. Pass in a user id and then query the ORM for a user matching that id then you can use it as an object!
web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Auth::routes();
Route::get('/pingu/{id}', [App\Http\Controllers\HomeController::class, 'pingu']);
Auth::routes();
Route::prefix('jobs')->group(function(){
Route::get('create', function () {
return "create";
});
Route::get('update', function () {
return "update";
});
});
TaskController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TaskController extends Controller
{ public function create(){
return view ('create');
}
}
create.blade.php`
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>
<div class="card-body">
<form action="{{route('jobs.store')}}" method="POST">
<input type="text" name="title" class="form-control">
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
I did exactly what to do in the turtorial but it dind't appear , please find fix that works. I use laravel 8 i tried to config :cache clear a nd then artisan serve again butdind't work .If you know a laravel enough ( 8 ) you should know that everything is done right .
Picture 1
The issue is with your route.
Route::prefix('jobs')->group(function(){
Route::get('create', function () {
return "create";
});
That will return the word create. You most likely actually want:
Route::prefix('jobs')->group(function() {
Route::get('create', [App\Http\Controllers\TaskController::class, 'create']);
});
The above tells Laravel to use the create function on your TaskController which returns your create view.
You also don't need to include Auth::routes() more than once. Include it before your routes just once.
Update
For the Did not work; here is a working example in black and white for you.
https://phpsandbox.io/n/round-morning-pqpk-dm8j1
Instead of return "create";, I think you meant to return view('create'). Please check and confirm.
Hi I am trying to build a laravel real time chat. I configured websockets and it seems to be connecting, but now I am trying to send a message and its working but to the other user the message is not displayed unless I refresh the page. I was following a tutorial in youtube did everything like in the tutorial and I dont know why I am receiving this errors. If you can have a look I would appreciate it.
Errors I am receiving
DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/js/utf8.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
ChatsComponent.vue
<template>
<div class="row">
<div class="col-8">
<div class="card card-default">
<div class="card-header">Messages</div>
<div class="card-body p-0">
<ul class="list-unstyled" style="height:300px; overflow-y:scroll">
<li class="p-2" v-for="(message,index) in messages" :key="index">
<strong>{{ message.user.name }}</strong>
{{ message.message }}
</li>
</ul>
</div>
<input
#keyup.enter="sendMessage"
v-model="newMessage"
type="text"
name="message"
placeholder="Enter your message..."
class="form-control">
</div>
<span class="text-muted">User is typing...</span>
</div>
<div class="col-4">
<div class="card card-default">
<div class="card-header">Active Users</div>
<div class="card-body">
<ul>
<li class="py-2">Harish</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props:['user'],
data(){
return {
messages:[],
newMessage:'',
}
},
created(){
this.fetchMessages();
Echo.join('chat')
.listen('MessageSent', (event) => {
this.messages.push(event.message);
});
},
methods:{
fetchMessages(){
axios.get('messages').then(response =>{
this.messages = response.data
})
},
sendMessage(){
this.messages.push({
user:this.user,
message:this.newMessage
});
axios.post('messages', {message: this.newMessage});
this.newMessage='';
}
}
}
</script>
Message Model
class Message extends Model
{
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
And I added this to User model
public function messages()
{
return $this->hasMany(Message::class);
}
ChatsController
use Illuminate\Http\Request;
use App\Message;
use App\Events\MessageSent;
class ChatsController extends Controller
{
public function _construct(){
$this->middleware('auth');
}
public function index()
{
return view('chats');
}
public function fetchMessages()
{
return Message::with('user')->get();
}
public function sendMessages(Request $request)
{
$message = auth()->user()->messages()->create([
'message' => $request->message
]);
broadcast(new MessageSent($message->load('user')))->toOthers();
return ['status' =>'success'];
}
}
MessageEvent event
App\Message; use App\User;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
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 PresenceChannel('chat');
}
}
Routes
Route::get('/chats','ChatsController#index')->middleware('auth');
Route::get('/messages','ChatsController#fetchMessages');
Route::post('/messages','ChatsController#sendMessages');
Broadcast::channel('chat', function ($user) {
return $user;
});
Chat view
#extends('layouts.app')
#section('content')
<div class="container">
<chats :user="{{ auth()->user()}}"></chats>
</div>
#endsection
I cannot get my events working on laravel 7.x, pusher, laravel-echo. I have set up everything correctly but still getting 401 error. I have also set up broadcast_driver as pusher in .env file. If anyone can help, I will appreciate.
CommentEvent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class CommentEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $comment;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($comment)
{
$this->comment =$comment;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('comment-channel');
}
public function broadcastAs()
{
return 'newComment';
}
}
CommentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Events\CommentEvent;
use App\Comment;
class CommentController extends Controller
{
public function index(){
return view('comments');
}
public function fetchComments(){
$comments =Comment::all();
return response()->json($comments);
}
public function store(Request $request){
$comment =Comment::create($request->all());
event(new CommentEvent($comment));
return response()->json('ok');
}
}
/routes/channels.php
<?php
use Illuminate\Support\Facades\Broadcast;
/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/
// Broadcast::channel('App.User.{id}', function ($user, $id) {
// return (int) $user->id === (int) $id;
// });
Broadcast::channel('comment-channel', function () {
return true;
});
bootstrap.js
window._ = require('lodash');
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.moment = require('moment');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
window.axios.defaults.headers.common.crossDomain = true;
// window.axios.defaults.baseURL = '/api';
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://adonisjs.com/docs/4.1/csrf');
}
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,
forceTLS: true
});
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);
export const store =new Vuex.Store({
state:{
//stores all the comments in this array//
comments:[]
},
getters:{
//returns the comments array//
comments:state=>{
return state.comments
}
},
mutations:{
//populates the comments array in the state with the comments from the database//
getComments:(state,comments)=>{
state.comments =comments
},
addComment:(state,comment)=>{
state.comments = state.push(comment)
}
},
actions:{
/* gets all the comments from comments endpoint api*/
getComments:({commit})=>{
axios.get(`http://127.0.0.1:8000/api/comments`)
.then(res=>{
//commits getcomments mutation and passes a parameter of comments from the response//
commit('getComments',res.data)
})
.catch(err=>{
console.log(err)
})
},
addComment:({commit},comment)=>{
return new Promise((resolve,reject)=>{
axios.post(`http://127.0.0.1:8000/api/comments`,{
author:comment.author,
content:comment.content
})
.then(res=>{
resolve(res)
}).catch(err=>{
reject(err)
})
})
}
}
})
MainApp.vue
<template>
<div class="container">
<div class="row">
<div class="col">
<div class="card">
<div class="card-body">
<form #keyup.enter="postComment">
<div class="form-group">
<input type="text" class="form-control" placeholder="Author's Name" v-model="comment.author">
</div>
<div class="form-group">
<textarea name="comment" id="" rows="6" class="form-control" v-model="comment.content" >
</textarea>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-success" #click.prevent="postComment">
</div>
</form>
</div>
</div>
</div>
<div class="col">
<div class="card">
<div class="card-body">
<div class="media" v-for="comment in comments" :key="comment.id">
<img class="mr-3" src="https://api.adorable.io/avatars/48/#adorable.io.png" alt="Generic placeholder image">
<div class="media-body">
<h5>{{comment.author}}</h5>
{{comment.content}}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import {store} from '../store';
import {mapGetters} from 'vuex';
import {mapActions} from 'vuex';
export default {
store:store,
data:function(){
return{
comment:{
author:'',
content:''
}
}
},
mounted() {
//calls the action getcomments from store.js//
this.$store.dispatch('getComments');
Echo.channel('comment-channel')
.listen('.newComment', (e)=>{
console.log(e)
})
},
computed:{
//gets the comments array from store.js//
...mapGetters([
'comments'
])
},
methods:{
postComment:function(){
this.$store.dispatch('addComment',this.comment)
.then(res=>{
if(res==='ok'){
console.log('success')
}
}).catch(err=>{
console.log(err)
})
}
}
}
</script>
Make sure to pass $user into the channel route callback. replace this code with your channel route. then you are good to go :)
Broadcast::channel('comment-channel', function ($user) {
return true;
});
I have a function that shows the department as treeview,it checks for the root node and then checks if this department has child.When i click in a department it should redirect me at another page that shows the users of this department that was clicked.I have tried to write this code and it shows me all the users but i want only those of this department
DepartmentController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Department;
use App\User;
use Illuminate\Support\Facades\DB;
class DepartmentController extends Controller
{
public function usersdep(){
//THIS IS THE ADDED CODE
$users = DB::table('users')
->join('departments', 'users.department', '=', 'departments.id')
->select('users.id','users.lastname','users.name as username','departments.name')->get();
return view('admin.page-users')->with('users', $users);
//ADDED CODE
}
public function treeView(){
$departments = Department::where('parent', '=', 0)->get();
$tree='<ul id="browser" class="filetree">';
foreach ($departments as $department) {
$tree .='<li class="tree-view closed "'.$department->name.''; //first department
if(count($department->childs)) {
$tree .=$this->childView($department);// if this department has children
}
}
$tree .='</ul>';
//return $tree;
return view('admin.page',compact('tree'));
}
public function childView($department){
$html ='<ul>';
foreach ($department->childs as $arr){
if(count($arr->childs))
{
$html .='<li class="tree-view closed">'.$arr->name.'';
$html.= $this->childView($arr);
}
else
{
$html .='<li class="tree-view" >'.$arr->name.'</a>';
$html .="</li>";
}
}
$html .="</ul>";
return $html;
}
page-user.blade.php
#extends ('layouts.master')
#section('title')
Users | Admin
#endsection
#section('content')
<div class="row">
<div class="col-md-12">
<div class="card">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<div class="card-header">
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead class=" text-primary">
<th>Name</th>
<th>Department</th>
</thead>
<tbody>
#foreach($users as $row)
<tr>
<script>console.log($row)</script>
<td>{{ $row->username }}</td>
<td>{{ $row->name}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
#endsection
web.php
<?php
use App\User;
use App\Department;
use App\Events\WebsocketDemoEvent;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
broadcast(new WebsocketDemoEvent('some data'));
return view('welcome');
});
Route::get('/page', function () {
return view('admin.page');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth','admin']], function () {
Route::get('/role-register','Admin\DashboardController#registered');
Route::delete('/role-delete/{id}', 'Admin\DashboardController#registerdelete');//delete user
Route::post('/save-user', 'Admin\DashboardController#store');
Route::get('/department', 'Admin\DepartmentController#index');
Route::post('/save-department', 'Admin\DepartmentController#store');
Route::get('/department-edit/{id}', 'Admin\DepartmentController#edit');//edit department
Route::put('/department-update/{id}', 'Admin\DepartmentController#update');
Route::delete('/department-delete/{id}', 'Admin\DepartmentController#delete');//delete department
Route::get('/page-users/{id}', 'Admin\DepartmentController#usersdep');//show users
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/chats', 'ChatsController#index');//chats
Route::get('/messages', 'ChatsController#fetchMessages');//messages
Route::post('/messages', 'ChatsController#sendMessage');//messages
Route::get('/dashboard', 'Admin\DashboardController#dbcheck');//DATABASE
Route::get('/user-edit/{id}', 'HomeController#registeredit');
Route::get('/role-edit/{id}', 'Admin\DashboardController#registeredit');//edit user
Route::put('/role-register-update/{id}', 'Admin\DashboardController#registerupdate');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('store_image', 'StoreImageController#index');
Route::post('store_image/insert_image', 'StoreImageController#insert_image');
Route::get('store_image/fetch_image/{id}', 'StoreImageController#fetch_image');
Route::get('/page',array('as'=>'jquery.treeview','uses'=>'Admin\DepartmentController#treeView'));
Route::get('/pageusers', 'Admin\DepartmentController#usersdep');
User.php
public function department()
{
return $this->belongsTo(Department::class);
}
Department.php
public function users()
{
return $this->hasMany(User::class,'department','id');
}
Change you method like this, you need to find department by id passed to route and then get department users. You can also do it using eager loading.
EDITED: You don't have to take id from request, but as route param, so this have to work
public function usersdep($id){
$department = Department::with('users')->find($id);
return view('admin.page-users')->with('users', $department->users);
}