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');
});
Related
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'
]);
I just want to show data from database using compact method, but it seem like it doesn't work , and I don't know what is wrong.
Controller:
public function index()
{
$sections = Sections::all();
return view('sections', compact('sections'));
}
View:
#foreach($sections as $section)
<tr>
<td>#</td>
<td>{{ $section->section_name }}</td>
<td>{{ $section->description }}</td>
<td>{{ $section->Created_by }}</td>
<td>
</tr>
#endforeach
route web.php
Route::resource('sections', 'SectionsController');
in web.php route for resource write it like
Route::resource('sections', SectionsController::class);
=>on laravel 8 use this route and import on top on route like
use App\Http\Controllers\SectionsController;
Route::resource('sections', SectionsController::class);
import top on your controller
use App\Models\Sections;
its working your fine.i can try your code its work.
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 have a table view in which I can click an button icon and redirect to another page carrying the id of the row that has been clicked.
#foreach ($patients as $patient)
<tr>
<td>{{ $patient->pID }}</td>
<td>{{ $patient->pName }}</td>
<td>{{ $patient->pAddress }}</td>
<td>{{ $patient->pBday }}</td>
<td>{{ $patient->pPhone}}</td>
<td>{{ $patient->pEcon }}</td>
<td>{{ $patient->pDreg }}</td>
<td></td>
<td>
<a href="{{ URL::to('visit/'.$patient->pID) }}">
<img src="../images/viewvisit.png" style="width:30px; height:30px;">
</a>
</td>
<td>
<a href="{{ URL::to('addeditvisit/'.$patient->pID) }}">
<img src="../images/visit.png" style="width:30px; height:30px;">
</a>
</td>
<td>
<a href="{{ URL::to('editpatient/'.$patient->pID) }}">
<img src="../images/update.png" style="width:30px; height:30px;">
</a>
</td>
<td>
<a href="{{ URL::to('deletepatient/'.$patient->pID) }}">
<img src="../images/delete.png" style="width:30px; height:30px;">
</a>
</td>
</tr>
#endforeach
what I want is to get the id from the URL and put it in a variable so that I can utilize it my other page.
I'm currently stuck with this controller function.
public function index(Request $request) {
$doctors = Doctor::where('dStatus', 0)
->lists('dName', 'dID');
$beds = Bed::where('bStatus', 0)
->lists('bName', 'bID');
$patient = Patient::patient();
// $uri = $request->path('patient');
return View::make('pages.addeditvisit', [
'doctors'=>$doctors,
'beds'=>$beds,
'patient'=>$patient->pID
]);
}
This is late. But for the benefit of others like me;
If you do not have to do it in a method like the answers above have shown, As of Laravel 5.0 (Not sure about previous versions), you can do
$request->route('id');
That returns the value of the id parameter on the route.
Or just use it within Blade: {{ request()->route('id') }}
Basically when you are defining the routes, you use something called route parameters, something like this
Route::get('/visit/{id}', 'Controller#someMethod');
This id will be available as a parameter in your handler funtion,
public function someMethod($id) {
// you have the id here
}
Simple example:
as link=> example.com/user/1
as rout=> Route::get('user/{id}', 'UserController#user');
as UserController function
public function user($id){
echo $id;
}
output => 1
The trick is to declare the url's structure at routes including the id, for example:
// {{ URL::to('editpatient/'.$patient->pID) }}
Route::get('editpatient/{patientId}', 'MyController#index');
Then, just inject the id in the controller's function:
public function index($patientId){
// $patientId is the variable from url
}
Please refer to the answered question for how to get a parameter from a route. But if you stumbled on this old Laravel thread looking for how to retrieve a model by its ID, the simplest way is to instantiate the model in the controller's request parameter:
Route::get('/retrieve_product/{product}', 'SearchController#getProduct');
Then over in your controller, you simply need:
use App\Product;
class SearchController extends Controller
{
public function getProduct( Product $product ) {
return $product;
}
}
That's it. No find, no where, no get, no first etc.
So, in this example, if you visit /retrieve_product/1 the first product is returned to you.
Route::get('post/user/{id}','ProductController#allpost')->where('id', '[0-9]+');
Controller
public function allpost($id)
{
$products = Product::where('uploadby', $id)->orderBy('created_at','desc')->paginate(5); <br>
return view('product.user_product')->with('products', $products);
}