Cant delete users - php

Hello im tryng to delete users, but this function dosnt work:
public function deleteUser()
{
$user = User::find($id);
$user ->delete();
return redirect('empresa');
}
Error: Undefined variable: id

Hope this helps or answers your question. Try this;
public function deleteUser($id)
{
User::find($id)->delete();
return redirect('empresa');
}

Just to help you visualize what Nigel and Deepak are saying:
deleteUser() has to be accept an argument called $id
deleteUser($id) { ... }
So when you call deleteUser() make sure to pass in your id (parameter) value:
deleteUser(17);
Hopefully that helps you see what they're talking about.

You will first have to find your user to delete them:
$user = User::find($id);
Then you'll be able to call the delete method:
$user->delete();
You may wish to consider handling the possibility that this user might be null. There are a few ways to accomplish this:
Check if the user is null before calling delete
Using the findOrFail method when finding a user
Option 2 will throw a ModelNotFoundException which you can configure your application to handle this globally and return a 404 page or whatever you might want.
Option 1:
public function deleteUser($id)
{
$user = User::find($id);
if (null !== $user) {
$user->delete();
}
return redirect('empress');
}
Option 2:
public function deleteUser($id)
{
$user = User::findOrFail($id);
$user->delete();
return redirect('empress');
}
Notice that on Option 2 we don't need a null check as an exception is thrown if the user is not found by using findOrFail.

Related

Call to a member function update() on null

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.

Laravel 5.2 trying to get user_id post

I am following a Laravel course on Udemy and while I followed everything the instructor did, for some weird reason I am not getting the expected result.
This is the Relationship One to One lesson and I added a function in User Model to check if it has any posts.
Then added the route to display post if user_id equals.
app\User.php
public function post() {
return $this->hasOne('App\Post');
}
app\Http\routes.php
Route::get('/user/{id}/post', function($id) {
return User::find($id)->post;
});
Below is the screenshot from the database showing that I have a post with user_id = 1 in the posts table. I also have a user with id=1 in the user's table.
MySQL data
Why do I get a blank page when visiting domain/user/1/post?
Sohel, i got a result from your function, but had to use
var_dump(User::with('post')->where('id',1)->first());
Then tried something else:
return User::with('post')->where('id',$id)->first();
And this is the result:
{"id":1,"name":"Nick","email":"nick#kriogen.name","created_at":"2018-03-15 09:49:51","updated_at":"2018-03-15 09:49:51","post":null}
Your one to one relationship should go as:
app\User.php
public function post() {
return $this->hasOne('App\Post');
}
app\Post.php
public function user() {
return $this->hasOne('App\User');
}
you can try doing this function in controller:
public function getPost {
$user= User::find($id);
return $user->post();
}
The issue was not with the functions, the issue was in the database.
Column deleted_at was not NULL and it was marking the post as being soft deleted, therefore not being displayed.
Since the "user_id" field is in the "posts" table, the relation in the App\User model need to be:
public function post() {
return $this->hasMany('App\Post');
}
then, call it without the parenthesis to get the result:
public function getPost {
$user= User::find($id);
return $user->post;
}
When you use the parenthesis, you get the builder and not the result. example:
public function getPost {
$user= User::find($id);
return $user->post()->get();
}
OR
public function getPost {
$user= User::find($id);
return $user->post()->where('name', 'like', '%hello%')->get();
}
I think you need ->hasMany() relation if you want to check if user has any posts because the user can has many posts... and the code would be:
public function posts() {
return $this->hasMany('App\Post');
}
The call:
User::find($id)->posts;

Laravel 5.1: Call to undefined method Illuminate\Database\Query\Builder::fill()

I am trying to get this line to work $user->profile()->fill($input['profile'])->save();
Following much discussion and failed attempts
I need help filling an eloquent model
Also had a probelm with guarding
http://laravel.io/forum/01-06-2016-massassignmentexception-ignoring-fillable-guarded-is-set
Which i overcame with protected $guarded = ['id'];
Profile model
public function user(){
return $this->belongsTo('App\User');
}
User Model
public function profile(){
return $this->hasOne('App\Profile', 'user_id');
}
Controller
public function update(Request $request, $id)
{
$user = User::with('profile')->findOrFail($id);
$input = $request->all();
if(is_null($user->profile)){
$profile = new Profile($input['profile']);
$user->profile()->save($profile);
alert()->warning('New profile creation attempt!');
}else{
// $user->profile()->fill($input['profile'])->save();
$user->profile->title = $input['profile']['title'];
$user->profile->facebook_username = $input['profile']['facebook_username'];
$user->profile->meetup_user_id = $input['profile']['meetup_user_id'];
$user->profile->save();
// dump($input['profile']['title']);
// dump($user->profile->title);
//Unless it fails silently like before.
alert()->success('Profile Saved!');
}
return redirect()->route('admin.users.edit', [$id]);
}
Notice how I am manually filling, this is not ideal obviously. this is the result i am trying to achieve
as per my understanding, you want to fill profile Attributes in a single line,
did you try fill() method ??
try this way in your else section or whereever your want it, I hope that might help you
$profile = new Profile;
$profile->fill($input['profile']);
$user->profile()->save($profile);

ModelNotFoundException - No query results for model [App\User]

From the form in my edit view, I'm calling the update function:
public function update(Request $request)
{
$id = Auth::user();
$user = User::findOrFail($id);
$user->update($request->all());
return redirect('user');
}
but I'm getting the following error:
ModelNotFoundException in Builder.php line 125: No query results for model [App\User].
I'm not passing the $id because i'm updating the Auth Id.
Not sure what's wrong and how to debug
Following is just enough in case you want to update logged in User.
public function update(Request $request)
{
Auth::user()->update($request->all());
return redirect('user');
}
#pinkalvansia has a great answer and solution for you.
However, I also wanted to note that I believe you would need to use:
Auth::user()->id to get the currently logged in user's ID. Your code would like this:
public function update(Request $request)
{
$user_id = Auth::user()->id;
$user = User::findOrFail($user_id);
$user->update($request->all());
return redirect('user');
}
Hope this is helpful!

Laravel: Redirecting user to another page with messages

Here is the excerpt from Controller code for adding a new user:
public function store()
{
$input = Input::all();
if (! $this->user->isValid($input))
{
return Redirect::back()->withInput()->withErrors($this->user->errors);
}
...
}
Here the Controller code for the add a new user form:
public function create()
{
return View::make('users.create');
}
Please notice here that I don't need to send inputs and errors to the view, but I can access it there without any issue.
But please have a look at some other code:
Here is my Controller code to delete the user:
public function destroy($id)
{
$user = User::find($id);
$deleted_message = 'User "' . $user->first_name . ' ' . $user->last_name . '" has been deleted.';
User::destroy($id);
return Redirect::route('users.index')->withMessage($deleted_message);
}
Here is my Controller code to show all users:
public function index()
{
$users = User::all();
return View::make('users.index')->withUsers($users);
}
Why I am not getting $message in the view to show all users?
You can send the message with this:
return Redirect::route('your-route')->with('global', 'Your message');
And get it in your template with this:
#if(Session::has('global'))
<p>{{ Session::get('global') }}</p>
#endif
Why I am not getting $message in the view to show all users?
Because you are not retrieving it. Using the withX() magic methods will put your data into the flash storage. That means, you need to retrieve it from there.
<?php
class UserController extends Controller {
public function index()
{
$message = Session::get('message');
$users = [];
return Redirect::make('users.index')->withUsers($users)->withMessage($message);
}
public function destroy()
{
$deleted_message = "Some message that shows that something was deleted";
return Redirect::route('users.index')->withMessage($deleted_message);
}
}
See what I am doing in the first line of the controllers index() method. I am referencing the message key of the Session Storage.
We put it in there when we did:
return Redirect::route('users.index')->withMessage($deleted_message);
withX() are methods automagically made available by laravel (see here). Whatever is appended to with() will be stored as the key into your session data.
Relying on Magic might not be suitable if you're just starting with laravel. To better keep in mind what you're actually doing you may want to use the with() method instead, where you pass a key and a value.
return Redirect::route('users.index')->with('message', $deleted_message);

Categories