I am Newbie. I'm trying to return a view of member profile
At the moment, the user profile is accessible by its ID, like so
profile/7
I would like to access it through the name that I've created
profile/John
this is my route
Route::get('profile/{id}', 'ProfilController#tampilkanID');
this is my controller
public function tampilkanID($id)
{
$auth = Auth::user()->id;
$users=\App\users::all()->whereNotIn('id',$auth);
$tampilkan = Users::find($id);
return view('tampilkan', compact('tampilkan', 'users'));
}
and this how i call it in my blade
#foreach($users as $user)
<tr>
<td><a id="teamname" href="{{ url('profile',$user->id) }}" target="_blank">{{$user->name}}</a></td>
</tr>
#endforeach
thank you
try this:
Route:
Route::any('profile/{name}', 'ProfilController#index')->name('profile.index');
Controller:
public function index(Request $request, $name)
{
$user = User::where('name', $name)->first();
if(isset($user))
return view('tampilkan', ['user' => $user]);
return "user not found!";
}
Blade:
#foreach($users as $user)
<tr>
<td><a id="teamname" href="{{ route('profile.index',['name' => $user->name]) }}" target="_blank">{{$user->name}}</a></td>
</tr>
#endforeach
Suggestion:
if you're doing this, you should also set "name" column to "unique" in users table in order to get exactly one user each time and not confuse users to each other.
You can use laravel Route Model Binding.
What is Route Model Binging?
Route model binding in Laravel provides a mechanism to inject a model instance into your routes.
How can I use it?
Pass object rather then id like
Route::get('users/{user}', function ($user) {
return view('user.show', compact('user'));
});
In your User.php define getRouteKeyName then return whatever you want as a route
public function getRouteKeyName()
{
return 'name'; //this will return user name as route
}
so your route will be users/name
For more information have a look at laravel documentation https://laravel.com/docs/5.5/routing#route-model-binding
Just Customise you RouteServiceProvider as Like below :
public function boot()
{
parent::boot();
Route::bind('user', function ($value) {
return App\User::where('name', $value)->first() ?? abort(404);
});
}
or
customise your route key in model.
For eg :
/**
* Get the route key for the model.
*
* #return string
*/
public function getRouteKeyName()
{
return 'name';
}
Route :
Route::get('users/{user}', function ($user) {
return view('user.show', compact('user'));
});
Related
Here is the Controller code I have
public function index()
{
$ajobs = Job::all();
return view('jobs_all', ['jobs' => $ajobs]);
}
This shows all my Table Data. I have stored user id as another column named created_by
In the View, I get value by ID, how how can I get the Username from Users table.
#foreach ($jobs as $ajob)
{{ $ajob->created_by }} //Here instead of UserID, how can i get Username by matching the UserID with UsersTable ?
#endforeach
Add next method to your "Job" model:
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
now you can add ORM param "with" to your method "index":
public function index() {
$ajobs = Job::with('user')
->all();
return view('jobs_all', ['jobs' => $ajobs]); }
now we have access to user model fields, and you can show them this way:
#foreach($jobs as $ajob)
{{ $ajob->user->name }}
#endforeach
More info about laravel relations here: https://laravel.com/docs/8.x/eloquent-relationships#one-to-one
you can use laravel eloquent belongsTo relationship. in your Job model add the following method.
public function user()
{
return $this->belongsTo(User::class, 'created_by');
//assuming your user model name is User and both models are in the same namespace. if not, adjust according to your structure.
}
and then you can use this relationship to get the user name like
#foreach ($jobs as $ajob)
{{ $ajob->user->name }}
//name is the column name from the user table. change if necessary.
#endforeach
You can use relations but in fast way on your situation you can join your tables:
$user_id = DB::table('jobs')
->select('users.id')
->join('jobs', 'jobs.user_id', '=', 'users.id')
->get();
=> add on your job table as foreginId user
$table->timestamp('created_at')->useCurrent();
$table->foreignId('created_by')->constrained('users')->onUpdate('cascade')->onDelete('cascade');
**That Function add on job model**
public function getCreatedAttribute()
{
return ucfirst($this->user->name);
}
=>relationship add on job table
public function user()
{
return $this->belongsTo(User::class,'id','created_by');
}
=>created display your user name
#foreach ($jobs as $ajob)
{{ $ajob->created}}
#endforeach
=>listing controller
public function index() {
$jobs = Job::with(['user']);
return view('jobs_all', compact('jobs')); }
The blade code:
<td>{{ $employee->first_name }} {{ $employee->last_name }}</td>
<td>{{ __('app-text.indexEdit') }}</td>
<td><form action="{{ route('employee.delete', ['lang' => app()->getLocale(), 'employee' => $employee->id]) }}" method="post">
The controller function:
public function edit(Employee $employee)
{
$companies = Company::get();
return view('employee.edit', compact('employee', 'companies'));
}
The error:
TypeError
Argument 1 passed to App\Http\Controllers\EmployeesController::edit() must be an instance of App\Employee, string given
http://localhost:8000/fr/employee/edit/1
The routes:
Route::group(['prefix' => '{lang}'], function() {
Route::prefix('employee')->name('employee.')->group(function() {
Route::get('/edit/{employee}', 'EmployeesController#edit')->name('edit');
Route::patch('/edit/{employee}', 'EmployeesController#update')->name('update');
I'm trying to make the application a multi-language application so just after I added the lang variable the route won't pass the $employee->id variable. Should I add a variable that's passable to my controller for the lang variable?
any solution? Many thanks.
first you can make a route to change language
Route:: get('lang/{lang}', function ($locale) {
session(['locale' => $locale]);
return \Redirect::back();
})
step 2: middleware
public function handle($request, Closure $next)
{
App::setLocale(session('locale'));
return $next($request);
}
after you can make a group
Route::group(['middleware' => 'language'],function(){
//routes with u want change language
Route::get('/edit/{employee}', 'EmployeesController#edit')->name('edit');
Route::patch('/edit/{employee}', 'EmployeesController#update')->name('update');
});
and you forget to send the language in each route
Your parameters are wrong. As the stack trace says the controller method is expecting an instance of your Employee model but you are passing in a string
Change
public function edit(Employee $employee)
To
public function edit(Request $request, $employeeId) // you can remove $request if you dont intend to perform redirects
So in the end your code looks like
public function edit(Request $request, $employeeId)
{
$employee = Employee::find($employeeId);
$companies = Company::all(); // use all instead of get if you arent going to perform selections.
return view('employee.edit', compact('employee', 'companies'));
}
Note: you may need to handle cases where employee is not found based on the $employeeId supplied
I think you have to modify your routes like these
in web.php
Route::get('your-route/{lang}/{id}','YourController#edit');
In your controller
public function edit($lang,Employee $employee)
{
$companies = Company::get();
return view('employee.edit', compact('employee', 'companies'));
}
if you are passing locale as well in the route then it should be as below:
web.php
Route::get('your-Own-route/{lang}/{employee}','YourController#edit');
Controller edit method
public function edit($lang,Employee $employee)
{
$companies = Company::get();
return view('employee.edit', compact('employee', 'companies'));
}
Am following some code and every time it tries to show posts for users it passes the user id to the url manually like "http://127.0.0.1:8000/home/1".
How can this be done without typing in the url
Home.blade.php
#foreach($user->posts as $post)
<div class="col-4">
<img src="/storage/{{$post->image}}" class="w-30" alt="">
</div>
route
Route::get('/home/{user}', 'HomeController#index')->name('home');
HomeController
public function index(User $user)
{
//
return view('home', compact('user'));
}
Just use like this
or
Here you can get idea how to pass variable.
If you would like to redirect the user after login you can modify the RedirectIfAuthenticated Middleware in app/http/middleware:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->route('home',array('user' => $request->user()));
}
return $next($request);
}
The id was passed to the url in this manner
$user = Auth::guard('web')->id();
return redirect()->route('home',['user'=>$user]);
The user is redirected to the home page with their id upon login in in the following way
login controller
*/
protected function redirectTo()
{
$user = Auth::guard('web')->id();
return route('home',['user'=>$user]);
}
note
The route to the home controller should have the variable 'user'
Route::get('/user/{user}', 'HomeController#index')->name('home');
I am creating a user profile that allows him to modify his information here is the code
class ProfilesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('content.profil');
}
public function editProfile($id)
{
$user = User::find($id);
return view('content.edit', ['user' => $user]);
}
public function updateProfile(Request $request, $id)
{
$user = User::find($id);
$user->name = $request->input('name');
$user->nom = $request->input('nom');
$user->prenom = $request->input('prenom');
$user->adresse = $request->input('adresse');
$user->code_postal = $request->input('code_postal');
$user->ville = $request->input('ville');
$user->pays = $request->input('pays');
$user->num_tele = $request->input('num_tele');
$user->save();
return redirect('/profil');
}
}
Web.php
Route::group(['middleware' =>'auth'], function(){
Route::get('/profil', 'ProfilesController#index')->name('profil');
Route::get('/content', 'ProfilesController#editProfile')->name('profil.edit');
Route::post('/content', 'ProfilesController#updateProfile')->name('profil.update');
});
the view folder tree looks like
view/content/profil.blade.php
view/content/edit.blade.php
the problem is that the routes are defined but it shows me this error message:
(1/1) NotFoundHttpException
I don't know where the problem exists exactly and
thanks in advance
Compared to your routes (web.php) and what you want, this is what your web.php file should be
Route::group(['middleware' =>'auth'], function(){
Route::get('/profil', 'ProfilesController#index')->name('profil');
Route::get('/content/{id}/editProfile', 'ProfilesController#editProfile')->name('profil.edit');
Route::post('/content/{id}', 'ProfilesController#updateProfile')->name('profil.update');
});
Correct your profil.edit route to /content/{id}/editProfile and profil.update in the same way.
And if you have named routes try to use route() helper instead of url() to generate url's, it's cleaner are more universal.
I'm trying to show a list of contacts for the logged in user. But obviously I'm doing something wrong.
I get a error on the contacts list page:
Trying to get property 'name' of non-object
User.php
public function contacts()
{
return $this->belongsToMany(Contact::class);
}
Contact.php
public function users()
{
return $this->belongsToMany(User::class);
}
ContactsController.php
public function index()
{
//
$user = Auth::user();
$user_contacts = $user->contacts()
return view('contacts.list')->with('contacts', $user_contacts);
}
list.blade.php
#foreach ($contacts as $contact)
* {{ $contact->name }} <br>
#endforeach
Table schema:
contacts:
id
created_at
updated_at
name
address
users:
id
name
password
remember_token
created_at
updated_at
contact_user:
contact_id
user_id
If you want to access pivot properties of your many to many relationship table u can access with pivot
#foreach ($contacts as $contact)
* {{ $contact->pivot->name }} <br>
#endforeach
Also creates a relatioship between contact and users
public function contacts()
{
return $this->belongsToMany(Contat::class)->withPivot(['your', 'pivot','columns']);
}
Hope this helps
In your controller you have the following;
public function index()
{
$user = Auth::user();
$user_contacts = $user->contacts()
return view('contacts.list')->with('contacts', $user_contacts);
}
It needs to be the following;
public function index()
{
$user = Auth::user();
$user_contacts = $user->contacts
return view('contacts.list')->with('contacts', $user_contacts);
}
Using $user->contacts()(method) will return an instance of the query builder for that relationship, where as $user->contacts(property) will return a collection with results from a select query.
You must return your pivot table's data in the relation as below:
public function contacts()
{
return $this->belongsToMany(Contat::class)->withPivot(['your', 'pivot','columns']);
}
And you must get relation data like below:
$user_contacts = $user->contacts // Not $user->contacts()