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'
]);
Related
I have a step2 form which will store Order first in step1 then go to step2 page which the purpose is storing Aircon
When Click "trash icon" should go to route destroy but after return back()
Error: The GET method is not supported for this route. Supported methods: POST.
How to do correctly? passing $order in destroy ?
public function destroy(Aircon $aircon)
{
$aircon->delete();
return back();
}
public function store(Request $request, Order $order)
{
$order = Order::find($order->id);
$attributes = $this->validateAirCon();
$order->aircons()->create($attributes);
return view('pages.user.order-aircons.addAircon',compact('order'));
}
<form action="{{ route('aircon.store', $order) }}" method="post">
#csrf
{{--inputs... --}}
<button type="submit">aircon.store</button>
</form>
#forelse ($order->aircons as $aircon)
<table class="table">
<th>Model Number</th>
{{-- th.. --}}
<tr>
{{-- td... --}}
<td>
{{-- Delete Aircon --}}
<form action="{{ route('aircon.destroy', $aircon) }}" method="post">
#method('DELETE')
#csrf
{{-- button submit --}}
</form>
</td>
</tr>
</table>
#empty
<h1>no data</h1>
#endforelse
Use the route name:
public function destroy(Aircon $aircon)
{
$aircon->delete();
// Put the route name that you want to be redirected to that.
return redirect()->route('YOUR_ROUTE_NAME');
}
Problem solved
Use custom route to pass two parameters Aircon and Order
Route::delete('/aircon/delete/{aircon}/order{order}', [AirConController::class, 'delete'])->name('aircon.destroy');
public function delete(Aircon $aircon, Order $order)
{
$aircon->delete();
return view('pages.user.order-aircons.addAircon', compact('order'));
}
I'm getting all users information at Blade, like this:
#foreach($users as $user)
<tr class="gradeX">
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role->name }}</td>
<td class="actions">
<i class="fa fa-pencil"></i>
<form method="POST" action="{{ route('users.destroy', $user->id) }}">
#csrf
#method('DELETE')
<button class="on-default remove-row btn-svg" title="Delete User"><i class="fa fa-trash-o"></i></button>
</form>
</td>
</tr>
#endforeach
As you can see, for deleting a custom user, I've added this:
<form method="POST" action="{{ route('users.destroy', $user->id) }}">
#csrf
#method('DELETE')
<button class="on-default remove-row btn-svg" title="Delete User"><i class="fa fa-trash-o"></i></button>
</form>
And at destroy method of the Controller:
public function destroy($id)
{
$user = User::findOrFail($id);
$photo = Photo::findOrFail($user->photo_id);
unlink(public_path() . $user->photo->path);
$photo->delete();
$user->delete();
return redirect('admin/users');
}
But now, whenever I try to delete the user from blade, I get 404 Not Found page. However the user still exists at the DB.
And when I add dd($id); at the Controller, I get this as result:
And user 14 exists at the table users just like below:
So what is going wrong here? How can I solve this issue and delete the user properly?
I would really appreciate any idea or suggestion from any of you guys...
Thanks in advance.
There are 2 options left what can be wrong, either you can’t find the user. Or you can’t find the photo. Based on the provided information it think there is no photo. The method findOrFail will return a 404 when the model is not found, see also https://laravel.com/docs/8.x/eloquent#not-found-exceptions.
So what you can do is add a dd before the photo check to see if the user is found. If that is true you can be sure it is the photo model. If that is the case, you should use Photo::find($user->photo_id).
After that you can wrap your unlink in an if statement where you Check if the photo model is not empty
public function destroy($id)
{
$user = User::findOrFail($id);
$photo = Photo::find($user->photo_id);
if (!empty($photo)) {
unlink(public_path() . $user->photo->path);
$photo->delete();
}
$user->delete();
return redirect('admin/users');
}
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.
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');
}
}
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}}">