i created a UserController.php
use App\User;
//
class UsersController extends Controller
{
//
public function edit($id, User $user){
$user = $user->find($id);
return view('admin.user.edit' , compact('user'));
}
//
}
And edit views
but when i want to access to this url
url('/users/'. $user->id .'edit')
i got this error
Error edit() must be an instance of App\User, none given
!?
Make sure your route is like:
Route::get(/users/{id}/edit', 'UsersController#edit');
Then use it as:
url('/users/'. $user->id .'/edit');
or
url("/users/{$user->id}/edit");
And then your controller should be as:
public function edit($id) {
$user = User::find($id);
return view('admin.user.edit' , compact('user'));
}
The error says that the edit() function expects $user_id and User instance but you're only providing $user_id. If that's the case your code should look like this:
public function edit($id){
$user = User::find($id);
return view('admin.user.edit' , compact('user'));
}
Related
I'm building my first Laravel app. That's my first problem that I can't overcome.
I tried to google something about it, but I couldn't find something that could help me.
class ProfilesController extends Controller
{
public function index(User $user)
{
return view('profiles.index', compact('user'));
}
public function edit(User $user){
return view('profiles.edit', compact('user'));
}
public function update(User $user){
$data = request()->validate([
'description' => 'required',
]);
$user->profile->update($data);
return redirect("{$user->id}/edit");
}
}
I want to get through that and update $data.
Edit
public function profile() {
return $this->hasOne(Profile::class);
}
public function posts(){
return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
}
Try this:
optional($user->profile)->update($data);
You can see the official documentation of optional() helper here.
I think you cannot update directly on an instance, you'd have to do : User::where('user_id', $user->id);
If you want to "update" an instance, you would have to do : $user->description = $data['description']; $user->save();
Do this:
if($user->profile) {
$user->profile()->update($data);
}
Hope this will help you.
I would imagine this is because the user doesn't have a profile by default.
One way you can get around this is by using withDefault() on your profile relationship in your User model e.g.
public function profile()
{
return $this->hasOne(Profile::class)->withDefault();
}
You would then need to change your controller code slightly since the profile might not exist:
Change:
$user->profile->update($data);
To:
$user->profile->fill($data)->save();
I had the same issue. As it turned out I forgot to create a new empty profile while creating a new user. So i was calling an update on the user's profile in this case null.
Try adding this to the User model and later migrate:fresh your data.
protected static function boot()
{
parent::boot();
static::created(function ($user) {
$user->profile()->create();
});
}
This will create a new profile for user automatically.
I am getting the following error on my query when the interest method exists in my model.
Call to undefined method Illuminate\Database\Query\Builder::interest()
Controller:
public function index() {
$user_id = auth()->user()->id;
$user = User::find($user_id);
$interests = Space::where('user_id', $user_id)->interest()->get();
return view('dashboard')->with('space', $user->space)->with('interest', $interests->space);
}
Space Model:
public function user(){
return $this->belongsTo(User::class);
}
public function interest(){
return $this->hasMany(Interest::class);
}
Interest Model:
public function user(){
return $this->belongsTo(User::class);
}
public function interest(){
return $this->belongsTo(Space::class);
}
Space::where('user_id', $user_id)->interest()->get();
The Line Shows Error Because the method interest is not existed in query builder or Model Scopes
But I think You have Misundestood something
Loading Relation In collection
Space::where('user_id', $user_id)->with('interest')->get();
Will Work
And
$singleFind = Space::findOrFail($yourId)->interest();
Will Work as you expected
Hope its clear
Try with this,
First of all you can access authenticated user id by this auth()->id()
For relationship in controller
$interests = Space::with(['interest'])->where('user_id', $user_id)->get();
For more
Laravel eager loading
Hope this helps:)
I want to be able to restrict users to only be able to see their own profiles in my laravel project. So when a user wants to access their profile, they would go to the url followed by /userprofile/{id}. But as of right now, any user can type in the specific id of a different user and access their profile. So if I'm logged in as the first user to register, I would have an id of 1. But I only want to be able to access my profile. If I try to type in id 2 or 3 in the url I want it to kick me back to the homepage. Any idea how I could accomplish this? Using some sort of middleware perhaps?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
use App\User;
use App\Salutation;
use App\Http\Requests\UserRequest;
use Auth;
class HomeController extends Controller
{
public function index(){
$users_info = User::all();
return view('userprofile.index', compact("users_info"));
}
public function show($user_info){
$user_info = User::find($user_info);
return view('userprofile.show', compact("user_info"));
}
public function create(){
return view('userprofile.create');
}
public function store(UserRequest $request){
$formData = $request->all();
User::create($formData);
return redirect('userprofile');
}
public function edit($user_info) {
$user_info = User::findOrFail($user_info);
return view('userprofile.edit', compact("user_info"));
}
public function update(UserRequest $request, $user_info){
$formData = $request->all();
$user_info = User::findOrFail($user_info);
$user_info->update($formData);
return redirect('userprofile');
}
public function __construct(){
$this->middleware('auth', ['only' =>['create', 'edit',
'destroy']]);
}
}
just compare the current user with param id
example:
public function getProfile(Request $request, $id)
{
if(Auth::id() == $id) {
// valid user
$user_info = Auth::user();
return view('userprofile.show', compact("user_info"));
} else {
//not allowed
}
}
So I was reading about using laravel policies for granting authorities on the resources of my application but there seems to be a problem there though I followed the tutorial.
I have a user model which can't be created via HTTP requests except by other users who have the Entrust role of 'Admin' or 'Broker'. What I understood and succeeded to make it work on other actions like indexing users was the following:
Inside the AuthServiceProvider.php inside the private $policies array, I registered that User class with the UserPolicy class like that
class AuthServiceProvider extends ServiceProvider {
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
User::class => UserPolicy::class,
Insured::class => InsuredPolicy::class
];
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
}
}
Define the UserPolicy controller class:
class UserPolicy {
use HandlesAuthorization;
protected $user;
public function __construct(User $user) {
$this->user = $user;
}
public function index(User $user) {
$is_authorized = $user->hasRole('Admin');
return $is_authorized;
}
public function show(User $user, User $user_res) {
$is_authorized = ($user->id == $user_res->id);
return $is_authorized;
}
public function store() {
$is_authorized = $user->hasRole('Admin');
return $is_authorized;
}
}
Then inside the UserController class, before performing the critical action I use this->authorize() check to halt or proceed depending on the privilege of the user
class UserController extends Controller
{
public function index()
{
//temporary authentication here
$users = User::all();
$this->authorize('index', User::class);
return $users;
}
public function show($id)
{
$user = User::find($id);
$this->authorize('show', $user);
return $user;
}
public function store(Request $request) {
$user = new User;
$user->name = $request->get('name');
$user->email = $request->get('email');
$user->password = \Hash::make($request->get('password'));
$this->authorize('store', User::class);
$user->save();
return $user;
}
}
The problem is that $this->authorize() always halts the process on the store action returning exception: This action is unauthorized.
I tried multiple variations for arguments of the authorize() and can't get it to work like the index action
In store() function of UserPolicy::class you are not passing the User model object:
public function store(User $user) {
$is_authorized = $user->hasRole('Admin');
return true;
}
missing argument User $user.
Maybe this is the cause of the problem.
When I am trying to send mail, everytime a new member is added to the user table, so that they can get a setup password link. I have been trying to get this to work but seem not to be.
public function store(AddUser $request)
{
$user = $request->all();
$user['activate'] = $this->active();
$user['guid'] = $this->guid();
$user['accountno'] = $this->generateAndValidateAccountno();
$check = User::find($user['phone']);
if(!$check) {
$id = User::create($user);
$this->sendEmail($user['accountno']);
}
return redirect('employee');
}
public function sendEmail(Request $request, $id)
{
$user = User::find($id);
Beautymail::send('emails.welcome', [], function($message)
{
$message
->to('$id->email', '$id->fname')
->subject('Welcome!');
});
}
}
Not sure what am doing wrong
Just use the same request class in the controller and the model. In your user model, add use Illuminate\Http\Request at the top of the class to tell it which Request class to use.
Just change:
public function sendEmail(Request $request, $id){...}
to
public function sendEmail($id){...}