Everything works great in CRUD, except for update.
My Controller:
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->update($request->all());
return redirect('/posts');
}
To answer this you need to know if that id is coming through properly.
Do a dump($id); This will show you if it's null or something unexpected.
I'd then wrap the $post in logic to rule out nulls or bad data.
Technically if you are doing a post from the front your id will usually be
$request->id this being sent from a hidden input on the front.
I'd also use a first() because everything coming to this function should already be created and not be null since you're populating this from the database.
$post = Post::where('id', $request->id)->first();
Next do a dump on $post dump($post); this will show you the post info.
If you don't have any post info you have trouble and will require more troubleshooting.
Then you can just do your save process, I personally like to to do a 1 to 1 save to make sure all values from the request are being properly handled. So it would be..
$post->column_name = $request->input_name;
$post->save();
return back()->with ('status', 'Record Updated!');
Then on the front you can display that status from session to show it was updated.
One caveat using mass update is that you should make sure that the fields you are updating are fillable in the model.
You need check your model at the first it should be something like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Crud extends Model
{
protected $fillable = [
'first_name', 'lastame', 'id',
];
}
then you have to use
dd('$post')
to see what you have then you can create your update like this:
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->update($request->all());
return redirect('/posts')->with('success', 'Data is successfully updated');;
}
Related
I'm using VueJS and Laravel for an application I'm developing. I've tried to search here for an answer, but I haven't found anything that works. Most of the times, it's because there's really nothing to return, but I've tried to debug my query quite a bit, and I don't understand why I keep getting a null.
So I'm trying to get information about the student who's logged in, so I'm doing an axios get on a route that executes the following:
public function getByUserId($id) {
//$student = $this->studentRepo->findByUserId($id);
$student = Student::where('user_id', $id)->first();
$inscription = Inscription::where('student_id', $student->id)->first();
$student->careers;
$res = $inscription ? new InscriptionResource($inscription) : '';
return response()->json([
'student' => new StudentResource($student),
'inscription' => $res,
]);
}
The thing is, it doesn't find the student with that user_id. I've checked if the user_id (param: $id) is getting there as expected and it is. I've also tried to get the query via ->toSql() and copy pasted the query on the database to test it and I do get the student I'm trying to search for. Thing is, it's not finding it in Laravel for some reason, I'm not sure why.
My student table does have the attribute "user_id", I've checked.
Student file:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Student extends Model {
use SoftDeletes;
protected $dates = ['deleted_at'];
public function charges() {
return $this->hasMany('App\Models\Payment');
}
}
Add the related column in the relation function
public function charges() {
return $this->hasMany('App\Models\Payment', '');
}
I have a problem that I do not know exactly how to solve it, I have a page that shows some questions asked, taken from the database and I made a comments section, how could I get comments according to post_id? I tried to take them and normal but it is not displayed, I did something like:
Route::
Route::get('/viewUserQuestion/{post}', 'PostsController#viewUserQuestion')->name('viewQuestion');
Controller:
public function viewUserQuestion(Post $post, Comment $comment) { return view('viewQuestion', compact('post'), compact('comment'));
Only if I have something like comment [0] -> commentText will be shown to me, if I do not receive an error, a suggestion how can I take them according to the id?
Schema::
$table->id();
$table->integer('post_id')->default();
$table->integer('user_id');
$table->text('commentText');
$table->timestamps();
});```
...
Firstly, when you return your view, you are not passing the variables to it correctly
return view(
'viewQuestion',
compact('post'),
compact('comment')
);
This is going to pass a third argument to the view() method rather than having both post & comment as part of a single array. I'd recommend reading the documentation in compact() here for a better understanding of what it does, but in essence it just makes an assocative array.
You would want to do something like this instead:
return view('viewQuestion', [
'post' => $post
]);
If you have a Post model with a hasMany() relationship to your Comment model
Post Model
/**
* A Post has many Comments.
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function comments()
{
return $this->hasMany(Comment::class, 'post_id');
}
You can access all comments simply by going $post->comments
try this
public function viewUserQuestion(Post $post)
{
$comment = Comment::where('post_id',$post->id)->get();
return view('viewQuestion', compact('post','comment'));
}
Or change route to.
Route::get('/viewUserQuestion/{post}/{comment}', 'PostsController#viewUserQuestion')->name('viewQuestion');
To use this route, you must also send a comment id
Good Luck
I tried to find some suggestions in the web, but I couldn't...
I would like to use some constraints in the save method for a relationship in Laravel, I'll do an example to explain it
Let's suppose I've the 2 models Post and Comment, like in the Laravel documentation:
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
}
and
class Comment extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
}
Now, I would like to do a check on a new comment inserting, for example I would like to avoid the insertion if more than ten comments for that post already exist.
I insert a new comment with these instructions
$comment = new Comment();
$post->comments()->save($comment);
I could check before these lines, but I would like to check in some other point, where all the saves are detected, is there something similar? Otherwise, is there some "standard way" to do it?
There are helper methods in eloquent Model class that are exactly what you need. Since you need to do the check before inserting, you want to use the static::creating or static::saving method. Use saving if you want to validate both when creating and updating a comment. In the Comment model add this:
protected static function boot()
{
parent::boot();
static::creating(function (Comment $comment) {
// Do validation on the $comment model.
// Feel free to make sql queries or do anything you need.
// Throw an exception if your validation fails.
});
}
You can do it with count(). Like beliw you can try. Where if the rows have less than 10 comments then it will save otherwise it will return back to the url.
$comment = new Comment();
If(count ($post->comments) <10){
$post->comments()->save($comment);
}
else
return back() ;//dont save return back;
Hope it will help
In my code, I insert a new row into the database:
$post = new Post;
$post->user_id = Auth::user()->id;
// more inserts
$post->save();
In my Post.php, I have:
protected $with = [
'user', 'answers', 'questions'
];
public function users()
{
return $this->belongsTo('App\User');
}
// etc
But when I return $post after I insert, there are no relationships (users, answers, questions) attached to it.
How can I get all of the default relationships to load after an insert?
The save() method persists the data to the database, but it doesn't do anything about refreshing the data on the Model or reloading relationships.
The easiest solution would be to refresh your object after calling save(). This will automatically eager load the relationships you've defined in your $with property on the model:
// ...
$post->save();
// refresh the post from the database
$post = $post->fresh();
Another option is to just manually reload the relationships yourself, using the load() method.
// ...
$post->save();
// reload the desired relationships
$post->load(['user', 'answers', 'questions']);
However, this duplicates the code that defines the relationships you'd like to be auto loaded (defined once in the Model, and then once in this code). You can mitigate that by creating a new function on your Model.
// in Post model
public function reloadRelations() {
$this->load($this->with);
}
// code usage
// ...
$post->save();
// call your new function to reload the relations
$post->reloadRelations();
However, the only real benefit of going this route over just calling the built in fresh() method is that this won't re-run the query to get the original Post data.
If you're handling 1000s of requests a second, maybe the one query might make a difference, but other than that, I wouldn't worry about it, and just use the fresh() method. But, the options are here for you to choose.
Instead of manually setting the attribute user_id, you should use the associate method from \Illuminate\Database\Eloquent\Relations\BelongsTo class.
$post->user()->associate(Auth::user());
// now you have the user inside your post.
dd($post->user);
May be, in model Post.php:
protected $primaryKey = 'id';
public function users()
{
return $this->hasOne('App\User', 'id', 'user_id');
}
before:
migration "posts"
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
// .....
});
Hopefully this will solve your problem
I'm trying to update a row in a particular table, laravel does not shows any error but value is not updating in database.
this is my update method code:
function update(Request $request){
$product=product::find($request['Id']);
$product->productName=$request['name'];
$product->description=$request['desc'];
$product->discount=$request['discount'];
$product->inventory=$request['inventory'];
$product->save();
return response()->json(['message'=>$product->productName],200);
}
I'm successfully getting all the data and I've checked that my changing the value of response json
the variable $product->productName also shows updated value as it is present after save() method but nothing changes in database.
The problem is with this piece of code as I have checked my model i.e product and its working fine as $product has value.
By default Laravel is protecting all models from mass-assignment vulnerability. So you have to specify either a $fillable (which fields can be modified) or $guarded (which fields can not be modified) property.
In your case add this to the model:
protected $fillable = [
'productName',
'description',
'discount',
'inventory',
];
Are you not trying to update this record?
Why are you using save() method, why not use update() since you are trying to set the given product with new set of values?:
$product->update();
So you can finally have (suggesting a check on if a product exists and if the update was successful - you can disregard it if you like):
function update(Request $request)
{
if(!$product=product::find($request['Id']))
{
return response()->json('Product does not exist', 404);
}
$product->productName=$request['name'];
$product->description=$request['desc'];
$product->discount=$request['discount'];
$product->inventory=$request['inventory'];
if($product->update())
{
return response()->json(['message'=>$product->productName],200);
}
return response()->json('Something went wrong', 500);
}
Hope it helps :)