How to view the streams of a department - php

I have a department that has many streams. How can I manage all the streams from a specific department?
For now I have a route for the departments:
Route::resource('/manage/department', 'DepartmentController');
The index controller for the department
public function index()
{
$departments = Department::all();
return view('admin.department.index', compact('departments'));
}
The index file looks like this:
#if($departments)
<table class="table">
<thead>
<tr>
<th>Dept Code</th>
<th>Name</th>
</tr>
</thead>
<tbody>
#foreach($departments as $department)
<tr>
<td>{{ $department->dept_code }}</td>
<td>{{ $department->name }}</td>
<td><a class="btn-primary btn" href="#">Streams</a></td>
<td><a class="btn btn-primary" href="{{route('department.edit', $department->id)}}">Edit</a></td>
<td>
{!! Form::open(['method' => 'DELETE', 'action'=>['DepartmentController#destroy', $department->id]]) !!}
{!! Form::submit('Delete', ['class'=>'btn btn-danger']) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
</tbody>
</table>
#endif
Now, when I click under on the streams button, I want to be able to view all the streams of that particular department as well as add a new stream.
How can I achieve that?
How would my new route be in case I have to add a new one, how do I do in the controller?

It looks like you want to manage Streams related to a department and by managing i think you mean the CRUD operations , a clean way to do that is to define a sub-resource related to the department manager :
Routes
Route::group( [ 'prefix' => '/manage/department/{department_id}'], function ( Router $router ) {
$router->resource( 'streams', 'StreamsController',['as'=>'department'] ); // here 'as' acts as a prefix for streams resource named routes
} );
Now you got a sub resource controller with a department_id as a required parameter in every method ( you should add it ) like this :
StreamsController
public function index($department_id){
// here you list the streams of a certain department smth like
$streams = Stream::where('department_id',$department_id)->get();
return view('admin.stream.index', compact('streams'));
}
public function create($department_id){
// here you add your create view
}
public function store(Request $request , $department_id){
// your post request
}
Finally in your index file you can call the index method like this :
Index
<td><a class="btn-primary btn" href="{{route('department.streams.index',[$department->id])}}">Streams</a></td>

The answer is actually simpler than what I imagined.
I added this route to my index:
<td><a class="btn-primary btn" href="{{route('course.show', $department->id)}}">Courses</a></td>
Then in the show method of the streams controller I did this:
public function show($id)
{
$department = Department::findOrFail($id);
$courses = $department->courses;
return view('admin.department.show', compact('courses'));
}
No extra routes have to be added because when I created the model it already came with the resources.

Related

How to display customer which have particular id?

I want to display user which have particular id. For example for id 1 should display customer which have id 2. Now redirect me to customers/1 but show empty page. What can I do that display user ?
route
Route::get('/', function () {
return redirect()->route('customers.index');
});
Route::get('/customers', '\App\Http\Controllers\CustomerController#index')->name('customers.index');
Route::get('/{id}', '\App\Http\Controllers\CustomerController#show')->name('customers.show');
controller
public function show(Customer $customer)
{
return view('show', compact('customer'));
}
view customers
a href=" {{ route('customers.show', ['id' => $customer->id]) }} ">
view customers/1
<tr>
<td>{{ $customer->first_name }}</td>
<td>{{ $customer->last_name }}</td>
<button type="submit" class="btn btn-danger">Delete</button>
<button type="submit" class="btn btn-success ms-1">Updated</button>
</tr>
Route: you can customize the route as you like, but the standard is as follows:
Route::get('/customers/{customer}', '\App\Http\Controllers\CustomerController#show')->name('customers.show');
CustomerController: when you do route model binding, it will do the findOrFail, so if you pass a customer that doesn't exist, you will get a 404 error automatically.
public function show(Customer $customer)
{
return view('customers.show', compact('customer'));
}
customers.show view: basic view to show data compacted from the controller
<tr>
<td>{{ $customer->first_name }}</td>
<td>{{ $customer->last_name }}</td>
</tr>
Simple, yet elegant :)
You can read how laravel prefers to structure routes here: https://laravel.com/docs/9.x/controllers#actions-handled-by-resource-controller
You can also go 1 step further, and let laravel do everything for you with the simple artisan command:
php artisan make:model Customer -mcr
Which will create, a resource, a migration, and a full resource controller.
Then in your web.php route:
Route::resource('customers', 'CustomerController');
Try change you code in routes file to:
Route::prefix('/customers')->group(function () {
Route::get('/customers', '\App\Http\Controllers\CustomerController#index')->name('customers.index');
Route::get('/{id}', '\App\Http\Controllers\CustomerController#show')->name('customers.show');
});

Route Model Binding Problem Does Not Seem To Be Working

I'm working with Laravel 8 and I have made a table like this at Blade:
<div class="card-body table-responsive p-0">
<table class="table table-hover">
<tr>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th>Actions</th>
</tr>
#foreach($roles as $role)
#if(count($role->users))
#foreach($role->users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $role->name }} | {{ $role->label }}</td>
<td>
<form action="{{ route('levels.destroy' ,$user->id) }}" method="post">
#method('DELETE')
#csrf
<div class="btn-group btn-group-xs">
Edit
<button type="submit" class="btn btn-danger">Delete</button>
</div>
</form>
</td>
</tr>
#endforeach
#endif
#endforeach
</table>
</div>
And the result perfectly showing up:
But now I got problem with Edit & Delete buttons that I have specified $user->id as parameter for both of them.
And when I hover over the buttons I can see the user id properly defined:
But when it comes to edit method which is using Route Model Binding, it does not find the user:
public function edit(User $user)
{
dd($user->id); // return null
}
However if I do not use Route Model Binding and say this instead:
public function edit($id)
{
dd($id); // return 1
}
It properly shows the user id!
I don't know why the Route Model Binding not working here, so if you know what's going wrong or how to fix this issue, please let me know...
You are trying to access the User Model which in this case doesn't know what id is, so you should be passing the id of the user to the edit route using either Get by passing it to the url endpoint , so now you can get it like
public function edit($id)
{
dd($id); // return null
}
or by sending it as a POST form and get it like
public function edit(Request $request)
{
dd($request->id); // return null
}
I saw comments, your resource controller name is not matching with your variable name "$user".
You can look here on official laravel docs.
In your situation, this might help;
Route::resource('levels', LevelController::class)->parameters([
'levels' => 'user'
]);

My Laravel Vue App Does Not Delete a Record. Do I need to Bind my Button so that it will redirect to the controller?

Hi I am currently making an app with a simple CRUD operation and I am bothered why my code isn't deleting a record whenever I press the delete button. I am a newbie in Laravel and Vue and currently familiarizing the functions and workflows of the 2 frameworks. I have a table called posts and it contains id, title and body. The app will add a new post and also edits the post and deletes a record. But what actually happened is that the app does not delete a record and I am not sure if a button must bind in order to pass the id to the controller. Can you help me please?
Here is my vue page (IndexComponent.vue):
<template>
<div>
<h1>Posts</h1>
<div class="row">
<div class="col-md-10"></div>
<div class="col-md-2">
<router-link :to="{ name: 'create' }" class="btn btn-primary">Create Post</router-link>
</div>
</div><br />
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="post in posts" :key="post.id">
<td>{{ post.id }}</td>
<td>{{ post.title }}</td>
<td>{{ post.body }}</td>
<td><router-link :to="{name: 'edit', params: { id: post.id }}" class="btn btn-primary">Edit</router-link></td>
<td><button class="btn btn-danger">Delete</button></td>
</tr>
</tbody>
</table>
<script>
import axios from 'axios';
export default {
data(){
return {
posts: []
}
},
created(){
let uri = "/api/posts";
axios.get(uri).then(response => {
this.posts = response.data.data;
});
},
methods: {
deletePost(id) {
let uri = `/api/post/delete/${id}`;
axios.delete(uri).then(response => {
this.posts.splice(this.posts.indexOf(id), 1);
});
}
}
}
This is what's inside my PostController.php :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Resources\PostCollection;
use App\Post;
public function delete($id) {
$post=Post::find($id);
$post->delete();
return response()->json('Successfully deleted!');
}
This will be my Route:
Route::delete('/post/delete/{id}', 'PostController#delete');
Inside my Post.php (Model):
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'body'];
}
Everything is actually working except the delete operation and I am still bothered until now. I haven't worked any solution to this problem.
AND BY THE WAY: For the UI. i am using bootstrap 4.3.1 and bootstrap-vue 2.0.4
<tr v-for="post in posts" :key="post.id">
<td>{{ post.id }}</td>
<td>{{ post.title }}</td>
<td>{{ post.body }}</td>
<td><router-link :to="{name: 'edit', params: { id: post.id }}" class="btn btn-primary">Edit</router-link></td>
<td><button #click="deletePost(post.id)" class="btn btn-danger">Delete</button></td>
</tr>
The reason why it is not deleting because you're not trigging the deletePost function. You should call it on the click event like the code above.

Fetching data from Database in Laravel

I want to fetch data from database table named 'users' and display the output in a table.
I have written below code but it's not working.
I am using Laravel 5.5
#extends('layouts.app')
#section('content')
<div class="container">
<h2>Admin Panel</h2>
<p>Data of the Registered Users.</p>
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
$users = DB::table('users')->select('id','name','email')->get();
#foreach($users as $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
Error: Undefined Variable: users
The problem is that you're trying to mix PHP within your (Blade) template. Although it is possible to do so with #php directives, this is bad practice: your view should not contain any business logic.
Ideally you want to pass this data from your controller. It should look something like this:
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
return view('some-view')->with('users', $users);
}
}
Read more on passing data to views here.
You are doing it all wrong, the point of MVC design is to have your controllers do the application logic, your views to represent a representation of that data and models to contain the data you need, in your case you are missing the point completely by using DB::table inside of your view, so here is an example code which you might need to correct a bit:
The example below doesn't show MVC pattern since the data is passed from inside a closure of a route
web.php
Route::get('/', function () {
$users = DB::table('users')->select('id','name','email')->get();
return view('VIEW-NAME-HERE', compact('users'));
});
view.blade.php
#foreach($users as $user)
{{ $user->id }} {{ $user->name }} {{ $user->email }}
#endforeach
Change VIEW-NAME-HERE with the name of your view file, for example index or users.index
You Are using php in blade file
first make controller
for controller run a command in terminal
php artisan make:controller usercontroller
then write this:
class usercontroller extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
$data = compact('users')
return view('your-view-name')->with('$data');
}
}

Passing Parameters from one view to another Laravel

I'm new with Laravel and there are some concepts that I don't understand very well. I really need your help on this because I've read many many pages, tutorials and stackoverflow solutions and I dont get the results that I need.
I have a list of "patients" shown on a index page from a database.
Here is the code:
#if($data)
<table class="table">
<thead>
<tr>
<td>Nombre de Paciente</td>
<td>Cedula</td>
<td>Fecha</td>
<td>Telefono</td>
<td>Email</td>
<td>Direccion</td>
<td>Fecha de Creación</td>
<td></td>
</tr>
</thead>
<tbody>
#foreach($data as $row)
<tr>
<td>
{{ $row->paciente }}</td>
<!--<td>{{ $row->paciente }}</td>-->
<td>{{ $row->cedula }}</td>
<td>{{ $row->fecha_nacimiento }}</td>
<td>{{ $row->telefono }}</td>
<td>{{ $row->email }}</td>
<td>{{ $row->direccion }}</td>
<td>{{ $row->created_at }}</td>
<td>
</td>
</tr>
</tbody>
#endforeach
</table>
#endif
What I want to do, and as you can see, the "patient" name is a link, which referese to (in this case)a form.
I want to get two things from this.
ONE: I want to get the id of the patient I'm clicking on and the name of the "patient" and send it to the form page.
TWO: on the form page I want to show the "patient" name on the top of the form, and have the "patient_id" hidden to save it on the form table (this patient_id will be a foreing key)
This are my current components:
ROUTE:
Route::get('/care/{id}', [
'as' => 'create',
'uses' => 'CareController#create' ]);
CONTROLLER
public function create($id)
{
//
return view ($this->path.'.care',['id'=>$id]);
}
VIEW:
<div class="form-group">
<label for="exampleInputEmail">Paciente </label>
<input type="hidden" name="id" value="{{$id}}">
</div>
But whenever I load the page, it shows a blank page and on the url I see the following:
http://hospital.dev/care/$row->id
I really appreciate your help with this.
UPDATE:
THANKS.
Its sending now the id. But when trying to display the form page, it still sends the blank page, and the url is the following:
"http://hospital.dev/care/1"
I dont know if it is something on the controller:
CONTROLLER:
public function create($id)
{
//
return view ($this->path.'.care',['id'=>$id ]);
}
how should I pass the id value no to the url but to the view?
You could simply concatenate the href:
<a href='/care/{{$row-id}}'></a>
Once you have passed the id into your route. You can then handle with the route definition and pass it to your other controller.
for example a view that creates dynamic links:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Endpoint</div>
</div>
<table class="table table-bordered" id="endpoint-table">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>ip</th>
<th>mac</th>
<th>proxy</th>
<th>model</th>
</tr>
</thead>
<tbody id="endpoint-table-body">
#foreach($endpoints as $endpoint)
<tr><td>{{$endpoint->id}}</td><td>{{$endpoint->name}}</td><td>{{$endpoint->ip}}</td><td>{{$endpoint->mac}}</td><td>{{$endpoint->proxy}}</td><td>{{$endpoint->model}}</td></tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endsection
then in your routes/web.php:
Route::get('/endpoint/{id}', 'EndpointController#show');
then it gets passed to the controller # function show where you can do some logic:
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$endpoint = Endpoint::getObjectById($id);
$e = new \stdClass();
$e->id = $endpoint->id;
$e->name = $endpoint->name;
$e->ip = $endpoint->ipaddress;
$e->mac = $endpoint->macaddress;
$e->model = $endpoint->model_id;
$e->proxy = $endpoint->proxy_id;
$endpoint = $e;
$endpoints = array();
$endpoints[] = $endpoint;
return view('endpoints', ['endpoints' => $endpoints]);
}
and when you return your view. You can pass it data passed from the function you defined on your controller. In this instance that function is show() on the EndpointController.
The reason that the url is http://hospital.dev/care/$row->id is because you are using single quotes, so it won't get the value of the variable.
In the list replace:
{{url('/care/$row->id')}}
With:
{{url('/care/'+$row->id)}}
Here you're echoing variable $row->id as a string <a href="{{url('/care/$row->id')}}">, you need to print the value.
Since you've got you routes named I suggest you rewrite it like this using route() helper:
<a href="{{ route('create', ['id' => $row->id]) }}">
Here I called the route() helper, passed the route name create as first argument and the {id} that the route expects as second argument.
Another way would be to just correct your method, by moving the variable out of '' and appending it to the url like this:
<a href="{{url('/care/' . $row->id)}}">
Period . appends a string to another string in php, not +
The link you are using is like id')}}">
so here you are printing the id as a string. But you need to use this like
id)}}">
OR
id}}">

Categories