How to show the users of this specific department? - php

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);
}

Related

Why does nothing appear ? Laravel 8?

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.

Class 'App\Http\Controllers\Controller' not found in Laravel 8

Controller
namespace App\Http\Controllers;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function show($id)
{
$article = Article::find($id);
return view('articles.show', ['article' => $article]);
}
}
Routes
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/about', function () {
return view('about', [
'articles' => App\Models\Article::take(3)->latest()->get()
]);
});
Route::get('/articles/{article}',
'App\Http\Controllers\ArticlesController#show');
show.blade.php
#extends ('layout')
#section ('content')
<div id="wrapper">
<div id="page" class="container">
<div id="content">
<div class="title">
<h3>{{ $article->title }}</h3>
<p>
<img src="/images/banner.jpg" alt=""
class="image image-full"/>
</p>
<p>{{ $article->body }}</p>
</div>
</div>
#endsection
Error
Class 'App\Http\Controllers\Controller' not found
http://localhost:8000/articles/2
I am not sure where I am going wrong. I have looked at the documentation for routes/controllers in Laravel 8, and it looks like what I have should be working.
It seems there is something wrong with your extended controller.
please check Controller.php existed in App\Http\Controllers or not.
All controller same as yours (ArticlesController) extended from Controller

How to link two tables with a pivot table?

Hey so a bit of an overview of the project i want to do. I want to show the user's teams.
When the user logged in and opened the viewteams page. He must show teams he joined/created. To do so i ve done the below processes...
my ViewTeamController
{
public function index()
{
$user=User::first();
$teams=Team::all();
$user->teams()->attach($teams);
return view('teams.viewteams',compact('teams'));
}
public function store()
{
}
}
my User model
public function teams(){
return $this->belongsToMany(Team::class,'team_user','teams_id','users_id');
}
my Team model
public function users(){
return $this->belongsToMany(User::class,'team_user','teams_id','users_id');
}
my migration of the pivot table
public function up()
{
Schema::create('team_user', function (Blueprint $table) {
$table->unsignedBigInteger('users_id');
$table->unsignedBigInteger('teams_id');
$table->index('users_id');
$table->index('teams_id');
$table->timestamps();
});
}
web.php routes
Route::get('/viewteams','ViewTeamController#index');
Route::post('/viewteams','ViewTeamController#store');
my viewteams.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"><h2 style="text-align:center;">Your Teams</h2></div>
<div class="card-body">
#foreach ($teams as $team)
#foreach($team->users as $user)
{{$user->org_name}}
#endforeach
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
my other controller for Creating a team
<?php
namespace App\Http\Controllers;
use App\Team;
use Illuminate\Http\Request;
class CreateTeamController extends Controller
{
public function index(Request $request)
{
return view('teams.createteams');
}
public function store(Request $request)
{
$team=Team::create($request->all());
return redirect()->route('home');
}
}
all my routes
Route::get('/login', function () {
return view('auth/login');
});
Auth::routes();
Route::get('/viewteams','ViewTeamController#index');
Route::post('/viewteams','ViewTeamController#store');
Route::get('/createteams','CreateTeamController#index');
Route::post('/createteams','CreateTeamController#store') ;
Route::get('/home', 'HomeController#index')->name('home');
To achieve currents users teams, first you should get authenticated user id using Auth facade.
After that you can load joined teams for user, using 'with' method. It loads teams relationships.
ViewTeamController
public function index()
{
$user = User::with('teams')->find(Auth::id());
return view('teams.viewteams',compact('user'))
}
viewteams.blade.php
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"><h2 style="text-align:center;">Your Teams</h2></div>
<div class="card-body">
#foreach ($user->teams as $team)
{{ $team->name }}
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
You will need to revisit and update the code which stores data to the users table and the teams user. The easiest way to store the data in a way which populates the pivot table is to use the sync() method as described at https://laravel.com/docs/master/eloquent-relationships#updating-many-to-many-relationships
I'm making some assumptions about names and relationships, buy you may have something like this:
$user = User::find(2);
$user->teams()->sync([4,5]);
In this case, you would put into the pivot table a record for user_id of 2 and team_id of 4, and a second record for a user_id of 2 and a team_id of 5.
If you want to share more code showing route definitions and controllers for how you are currently handling things, we can help with any more specific implementation questions.

Websocket chat in Laravel isnt real time

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?

Enable to show session values in view - Laravel 5

am trying to show a simple value stored in session to a view, it is not working correctly
routes.php file
<?php
Route::get('/', 'Test#index');
Route::get('/nnn', 'Test#nnn');
Route::group(['middleware' => ['web']], function () {
});
controller file
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Session;
class Test extends Controller
{
public function index(){
Session::put('name', 'abcdef');
return view('welcome');
}
public function nnn(){
return view('welcome');
}
}
view file:
<body>
<div class="container">
<div class="content">
<div class="title">Laravel 5</div>
#if(Session::has('name'))
{{ Session::get('name') }}
#endif
</div>
</div>
</body>
when i go to localhost:8000 it is showing session value abcdef
but when i go to localhost:8000/nnn it is not showing any value
try to change your routes file to
<?php
Route::group(['middleware' => ['web']], function () {
Route::get('/', 'Test#index');
Route::get('/nnn', 'Test#nnn');
});
in your controller method nnn(){ echo Session, see what you get ? show me the results that you getting the value or not?
public function nnn(){
echo Session::get('name') ;
return view('welcome');
}
also try this in your view
{!! Session::get('name') !!}
instead
{{ Session::get('name') }}

Categories