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}}">
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 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 am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).
Here is the code of my project:
HTML:
<div class="table-responsive">
<table class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th><strong>No</strong></th>
<th><strong>Nama Petani</strong></th>
<th><strong>Alamat</strong></th>
<th><strong>No. Handphone</strong></th>
<th><strong>Lokasi</strong></th>
</tr>
</thead>
<tbody>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tbody>
</table>
</div>
PHP:
In my listpetani.blade.php I have an empty table and I want to show data from database tbl_user:
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
});
And the table in my page: view in browser
I want to show all the data from database into my view in laravel 5.4. Can anybody help me?
[SOLVE]
Thank you guys, I already solve this problem
This is the solved code
web.php (routes)
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->get();
return view('listpetani', ['petani' => $petani]);
});
and in my listpetani.blade.php
#foreach($petani as $key => $data)
<tr>
<th>{{$data->id_user}}</th>
<th>{{$data->nama_user}}</th>
<th>{{$data->alamat}}</th>
<th>{{$data->no_telp}}</th>
<th>{{$data->id_lokasi}}</th>
</tr>
#endforeach
You can get data from database in view also
#php( $contacts = \App\Contact::all() )
#php( $owners = \App\User::all())
<select class="form-control" name="owner_name" id="owner_name">
#foreach($contacts as $contact)
<option value="{{ $contact->contact_owner_id }}">{{ $contact->contact_owner }}</option>
#endforeach
</select>
It would be better if you pass data from controller to view.
return view('greetings', ['name' => 'Victoria']);
Checkout the docs:
https://laravel.com/docs/8.x/views#passing-data-to-views
Alternatively you can use #forelse loop inside laravel blade
#forelse($name as $data)
<tr>
<th>{{ $data->id}}</th>
<th>{{ $data->name}}</th>
<th>{{ $data->age}}</th>
<th>{{ $data->address}}</th>
</tr>
#empty
<tr><td colspan="4">No record found</td></tr>
#endforelse
In your controller:
$select = DB::select('select * from student');
return view ('index')->with('name',$select);
In Your view:
#foreach($name as $data)
<tr>
<th>{{ $data->id}}</th> <br>
<th>{{ $data->name}}</th> <br>
<th>{{ $data->age}}</th> <br>
<th>{{ $data->address}}</th>
</tr>
#endforeach
I hope this can help you.
#foreach($petani as $p)
<tr>
<td>{{ $p['id_user'] }}</td>
<td>{{ $p['username'] }}</td>
<td>{{ $p['alamat'] }}</td>
<td>{{ $p['no_telp'] }}</td>
<td>{{ $p['id_lokasi'] }}</td>
</tr>
#endforeach
**In side controller you pass this **:
$petanidetail = DB::table('tb1_user')->get()->toArray();
return view('listpetani', compact('petanidetail'));
and Inside view you use petanidetail variable as follow:
foreach($petanidetail as $data)
{
echo $data;
}
I hope you already know this, but try use Model and Controller as well,
Let the route take the request, and pass it to controller
and use Eloquent so your code can be this short:
$petani = PetaniModel::all();
return view('listpetani', compact('petani));
and instead using foreach, use forelse with #empty statement incase your 'listpetani' is empty and give some information to the view like 'The List is Empty'.
Try this:
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
on your view iterate $petani using foreach() like:
foreach($petani as $data)
{
echo $data->id_user; // $petani is a Std Class Object here
echo $data->username;
}
Other answers are correct, I just want to add one more thing, if your database field has html tags then system will print html tags like < p > for paragraph tag. To remove this issue you can use below solution:
You may need to apply html_entity_decode to your data.
This works fine for Laravel 4
{{html_entity_decode($post->body)}}
For Laravel 5 you may need to use this instead
{!!html_entity_decode($post->body)!!}
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);
}