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);
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 got this piece of code in Laravel:
public function index()
{
$user_id = auth()->user()->id; // gets the current user id
$user = User::find($user_id); // find the specific user id
$validPosts = $user->posts->paginate(5)->whereIn('status', ['Pending', 'Processing']);
return view('home', compact('validPosts'));
}
I want to return all posts that have the status pending and processing with pagination that has the value of 5 but I am getting the following error:
Method Illuminate\Database\Eloquent\Collection::paginate does not
exist.
I know that I have failed somewhere at $user->posts->paginate(5).
What should I do?
Paginate method works with Eloquent models. Retrieve the model, apply whereIn first and then paginate it. Try this:
public function index() {
$user = auth()->user();
$validPosts = $user->posts()->whereIn('status', ['Pending', 'Processing'])->paginate(5);
return view('home', $validPosts);
}
Now in your "home" view file you can use $validPosts
You can try this way
public function index()
{
$user_id = auth()->user()->id; // gets the current user id
$user = User::find($user_id); // find the specific user id
// paginate function should be last
$validPosts = $user->posts()->whereIn('status', ['Pending', 'Processing'])->paginate(5);
// if you want to pass more variable, do it like this
return view('home', ['validPosts' => $validPosts]);
}
or you can do it like this
public function index()
{
$user_id = auth()->user()->id; // gets the current user id
// paginate function should be last
$validPosts = Post::where('user_id', $user_id)->whereIn('status', ['Pending', 'Processing'])->paginate(5);
// if you want to pass more variable, do it like this
return view('home', ['validPosts' => $validPosts]);
}
Hope this help you.
I'm doing a blog with Laravel Framework and I allready have a Login/Register and a thread section. In my Blog you just can edit a thread if you're logged in. Now I have the problem that if I'm logged in, I can edit and delete every thread. It doesn't matter if it's my thread or if it is from another user. Well now I need something to say my laravel code that I'm just allowed to edit/dekete my own threads.
I've found this: https://laravel.com/docs/5.2/authorization#defining-abilities
But I don't really understand how I implement this to my code. And do I need a in my database any reference? like this user belongs to this thread?
Well I'm kind of new in laravel.. I hope someone can help me
PS: I'm sorry for my bad english, I'm from germany.
Edit/Update/Delete function:
public function edit($id)
{
$thread = Thread::query()->findOrFail($id);
return view('test.edit', [
'thread' => $thread
]);
}
public function update($id, StoreRequest $request)
{
$thread = Thread::query()->findOrFail($id);
$thread->fill($request->all());
$thread->save();
return redirect(action('Test\\TestController#show', [$thread->id]));
}
public function destroy($id)
{
$thread = Thread::query()->findOrFail($id);
$thread->delete();
return redirect(action("Test\\TestController#index"));
}
my thread model:
public function user() {
return $this->belongsTo(User::class, "name");
}
How I add a new thread:
If I press "add thread" I'm getting directed to my add function in my controller:
add function:
public function add()
{
return view('test.add', [
'entries' => Thread::query()->get()
]);
}
in my add.blade I have my formular and this formular directs me to my "store function " in my controller:
store function:
public function store(StoreRequest $request)
{
Thread::create($request->all());
return redirect(action('Test\\TestController#index'));
}
You can attach the user_id to the thread so anytime you want to update or delete you check if the current logged in user bears that user_id then you do accordingly.
add user_id to threads table
Then in your save function() do this.
public function save(Request $request){
$thread = new Thread;
$thread->user_id = Auth::user()->id;
// rest of fields goes here
$thread->save();
}
then in your edit, update or delete function
public function edit($id)
{
$thread = Thread::query()->findOrFail($id);
// You can use laravel authorization/policies to achieve this too
if($thread->user_id != Auth::user()->id){
// Return to view with your custom error message telling
// the user he is not authorized to edit this thread
}
return view('test.edit', [
'thread' => $thread
]);
}
public function update($id, StoreRequest $request)
{
$thread = Thread::query()->findOrFail($id);
// You can use laravel authorization/policies to achieve this too
if($thread->user_id != Auth::user()->id){
// Return to view with your custom error message telling
// the user he is not authorized to edit this thread
}
$thread->fill($request->all());
$thread->save();
return redirect(action('Test\\TestController#show', [$thread->id]));
}
public function destroy($id)
{
$thread = Thread::query()->findOrFail($id);
// You can use laravel authorization/policies to achieve this too
if($thread->user_id != Auth::user()->id){
// Return to view with your custom error message telling
// the user he is not authorized to delete this thread
}
$thread->delete();
return redirect(action("Test\\TestController#index"));
}
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!