I'm using voyager admin panel. I want to check the attributes that are changed when I submit the form. I'm using isDirty() & getDirty() but that is not working.
It is showing that the error
Method Illuminate\Http\Request::isDirty does not exist.
Sometimes showing this error.
Call to a member function isDirty() on string
update Controller
public function update(Request $request, $id)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Compatibility with Model binding.
$id = $id instanceof \Illuminate\Database\Eloquent\Model
? $id->{$id->getKeyName()}
: $id;
$model = app($dataType->model_name);
$query = $model->query();
$data = $query->findOrFail($id);
$this->insertUpdateData($request, $slug, $dataType->editRows, $data);
// That part is showing an error
dd($request->isDirty(['status']));
return $redirect->with([
'message' => __('voyager::generic.successfully_updated')." {$dataType->getTranslatedAttribute('display_name_singular')}",
'alert-type' => 'success',
]);
}
Request will not show the results it will work only with the model. So I used $data instead of $request. And I've to show it in an array. Something like this.
$data = $query->findOrFail($id);
$data->status = $request->status;
dd($data->isDirty('status'));
I works on my side.
I started to code new website something like e-commerce but it's just a review website that user makes comment about brands, products and posts of brands. So, i have a polymorphic table for comments.
When somebody tries to add comment, first, i need to define the comment type like Brand, Product or Post. In this case, i'm using switch case to know what user's want to do. I think there would be better way to do that with clean code structure that's why i'm here.
I just want know if this is the proper way to add comment like below.
public function addComment(Request $request, $type, $id, $tab = null)
{
// Error messages
$messages = [
'add_comment.required' => '...',
'add_comment.min' => '...',
'add_comment.max' => '...',
'rating.numeric' => '...',
'rating.min' => '...',
'rating.max' => '...'
];
// Validate the form data
$validator = Validator::make($request->all(), [
'add_comment' => 'required|min:5|max:2000',
'rating' => 'numeric|min:0|max:5'
], $messages);
if($validator->fails())
{
return back()->withErrors($validator);
} else {
$comment = new Comment;
$comment->body = $request->get('add_comment');
$comment->user()->associate(Auth::user()->id);
$comment->star_value = $request->get('rating');
switch ($type) {
case 'Post':
$post = Post::findOrFail($id);
$comment->star_value = NULL;
$post->comments()->save($comment);
break;
case 'Product':
$product = Product::findOrFail($id);
$product->comments()->save($comment);
//Update rating of product
$average = $product->comments()->getAvg();
$product->rating = $average;
$product->save();
break;
default:
$this->postCommentToBrand($comment, $id, $tab);
break;
}
return redirect()->back();
}
}
$request = inputs
$type = commentable_type (Brand, Product, Post)
$id = id of $type
$tab = This is actually for brand. Because brand has customer support and technical support. Need to define it there by using switch case as well.
Split it into separate routes - one for each commentable type, for example:
Route::post('add-comment/post/{post}', 'CommentsController#addPostComment');
Route::post('add-comment/product/{product}', 'CommentsController#addProductComment');
Route::post('add-comment/brand/{brand}/{tab}', 'CommentsController#addBrandComment');
This will take care of your switch - now Laravel's router will see right away what type of commentable entity you are adding comment to. Router will also utilise implicit model binding and will find those models by specified id for you (and return 404 if said row doesn't exist in your DB) so we get rid of those pesky findOrFail calls as well.
Now in your controller you should utilize form requests for validation (instead of creating Validator instance manually). Finally we can group logic of creating new Comment instance (that is common for all commentable types) into separate method. Then your controller will look like this:
protected function getNewCommentFromRequest(Request $request)
{
$comment = new Comment;
$comment->body = $request->get('add_comment');
$comment->user()->associate(Auth::user()->id);
$comment->star_value = $request->get('rating');
return $comment;
}
public function addPostComment(AddCommentRequest $request, Post $post)
{
$comment = $this->getNewCommentFromRequest($request);
$comment->star_value = NULL;
$post->comments()->save($comment);
return redirect()->back();
}
...
Methods addProductComment and addBrandComment won't be much different.
So I got posts page, where I have my post. The post has ID which leads to posts table. For it I have PostsController where everything is accessible thru $post->id, $post->name etc.
But I have another table named orders and on submit button, it needs some of the information from posts table by id.
I have post with url posts/{id} and there's submit button in the view
The button needs to get $post information to OrdersController with submit information.
I've tried this in OrdersController
public function store(Request $request)
{
$this->validate($request, [
]);
$post = Post::all();
$order = new Order;
$order->client = Auth::user()->name;
$order->phone = Auth::user()->phone;
$order->vehicle = $post->id;
$order->date_from = $request->input('date_from');
$order->save();
return redirect('/posts')->with('success', 'Rezervēts');
}
$posts = Post::all(); is getting all array information from table but cannot use specific id.
And I have this in PostsController
public function show($id)
{
$post = Post::find($id);
$images = Image::All();
return view('posts.show')->with(compact('post', 'images'));
}
Route for show function
Error that I'm getting with shown code: Property [id] does not exist on this collection instance.
Expected results:
orders table
Error: Property [id] does not exist on this collection instance.
Problem: Can't get exact id from view to another controller, so I can access posts table records that I need from OrdersController.
Ps. I've been thru most of the pages on this error, but can't seem to find the one that would help.
I would modify the route so that the affected post.
Route:
Route::post('/order/{post}/store', 'OrderController#store')->name('order.store');
Controller (store method):
public function store(Post $post, Request $request){
$this->validate($request, [
]);
$order = new Order;
$order->client = Auth::user()->name;
$order->phone = Auth::user()->phone;
$order->vehicle = $post->id;
$order->date_from = $request->input('date_from');
$order->save();
return redirect('/posts')->with('success', 'Rezervēts');
}
Okay, thanks.
Solved: {{ Form::hidden('id', $post->id) }} in view.
Controller: $post = Post::findorfail($request->id);
Then: $post->(whatever you need from table)
When updating my Post model, I run:
$post->title = request('title');
$post->body = request('body');
$post->save();
This does not update my post. But it should according to the Laravel docs on updating Eloquent models. Why is my model not being updated?
I get no errors.
The post does not get updated in the db.
Besides not being updated in the db, nothing else seems odd. No errors. Behavior as normal.
Result of running this test to see if save succeeded was true.
This Laravel thread was no help
Post model:
class Post extends Model
{
protected $fillable = [
'type',
'title',
'body',
'user_id',
];
....
}
Post controller:
public function store($id)
{
$post = Post::findOrFail($id);
// Request validation
if ($post->type == 1) {
// Post type has title
$this->validate(request(), [
'title' => 'required|min:15',
'body' => 'required|min:19',
]);
$post->title = request('title');
$post->body = request('body');
} else {
$this->validate(request(), [
'body' => 'required|min:19',
]);
$post->body = request('body');
}
$post->save();
return redirect('/');
}
Bonus info
Running dd($post->save()) returns true.
Running
$post->save();
$fetchedPost = Post::find($post->id);
dd($fetchedPost);
shows me that $fetchedPost is the same post as before without the updated data.
Check your database table if the 'id' column is in uppercase 'ID'. Changing it to lower case allowed my save() method to work.
I had the same and turned out to be because I was filtering the output columns without the primary key.
$rows = MyModel::where('...')->select('col2', 'col3')->get();
foreach($rows as $row){
$rows->viewed = 1;
$rows->save();
}
Fixed with
$rows = MyModel::where('...')->select('primary_key', 'col2', 'col3')->get();
Makes perfect sense on review, without the primary key available the update command will be on Null.
I had the same problem and changing the way I fetch the model solved it!
Was not saving even though everything was supposedly working just as you have mentioned:
$user = User::find($id)->first();
This is working:
$user = User::find($id);
You have to make sure that the instance that you are calling save() on has the attribute id
Since Laravel 5.5 laravel have change some validation mechanism I guess you need to try this way.
public function store(Request $request, $id)
{
$post = Post::findOrFail($id);
$validatedData = [];
// Request validation
if ($post->type == 1) {
// Post type has title
$validatedData = $request->validate([
'title' => 'required|min:15',
'body' => 'required|min:19',
]);
} else {
$validatedData = $request->validate([
'body' => 'required|min:19',
]);
}
$post->update($validatedData);
return redirect('/');
}
Running dd() inside a DB::transaction will cause a rollback, and the data in database will not change.
The reason being, that transaction will only save the changes to the database at the very end. Ergo, the act of running "dump and die" will naturally cause the script to cease and no therefore no database changes.
Check your table if primary key is not id ("column name should be in small letters only") if you have set column name with different key then put code in your Model like this
protected $primaryKey = 'Id';
So this might be one of the possible solution in your case also if your column name contains capital letters.
Yes this worked for me fine,
You should have column names in small letter,
If you don't have then mention it in the model file, mainly for primaryKey by which your model will try to access database.
For use save () method to update or delete if the database has a primary key other than "id". need to declare the attribute primaryKey = "" in the model, it will work
Try this
public function store($id,Request $request)
{
$post = Post::findOrFail($id);
// Request validation
if ($post->type == 1) {
// Post type has title
$request->validate([
'title' => 'required|min:15',
'body' => 'required|min:19',
]);
$post->update([
'title' => request('title');
'body' => request('body');
]);
} else {
$request->validate([
'body' => 'required|min:19',
]);
$post->update([
'body' => request('body');
]);
}
return redirect('/');
}
In my experience, if you select an Eloquent model from the db and the primary_key column is not part of the fetched columns, your $model->save() will return true but nothing is persisted to the database.
So, instead of doing \App\Users::where(...)->first(['email']), rather do \App\Users::where(...)->first(['id','email']), where id is the primary_key defined on the target table.
If the (sometimes micro-optimization) achieved by retrieving only a few columns is not really of importance to you, you can just fetch all columns by doing \App\Users::where(...)->first(), in which case you do not need to bother about the name of the primary_key column since all the columns will be fetched.
If you using transactions.
Do not forget call DB::commit();
It must look like this:
try{
DB::beginTransaction();
// Model changes
$model->save();
DB::commit();
}catch (\PDOException $e) {
DB::rollBack();
}
I have the same issue although there are try / catch block in controller#action() but there were no response, it just stops at $model->save(); there is no log entry either in apache error.log or laravel.log. I have just wrapped the save() with try / cactch as follows, that helped me to figure out the issue
try{
$model->save();
}
catch (\PDOException $e) {
echo $e->getMessage();
}
I have been experiencing the same issue and found a workaround. I found that I was unable to save() my model within a function called {{ generateUrl() }} on my home.blade.php template. What worked was moving the save() call to the controller that returns the home.blade.php template. (IE, save()ing before the view is returned, then only performing read operations within {{ generateUrl() }}.)
I was (and am) generating a state to put in a URL on page load:
<!--views/home.blade.php-->
Add Character
Below is what did not work.
// Providers/EveAuth.php
function generateUrl()
{
$authedUser = auth()->user();
if (!$authedUser) {
return "#";
}
$user = User::find($authedUser->id);
$user->state = str_random(16);
$user->save();
$baseUrl = 'https://login.eveonline.com/oauth/authorize?state=';
return $baseUrl . $user->state;
}
This was able to find() the User from the database, but it was unable to save() it back. No errors were produced. The function appeared to work properly... until I tried to read the User's state later, and found that it did not match the state in the URL.
Here is what did work.
Instead of trying to save() my User as the page was being assembled, I generated the state, save()d it, then rendered the page:
// routes/web.php
Route::get('/', 'HomeController#index');
Landing at the root directory sends you to the index() function of HomeController.php:
// Controllers/HomeController.php
public function index()
{
$authedUser = auth()->user();
if ($authedUser) {
$user = User::find($authedUser->id);
$user->state = str_random(16);
$user->save();
}
return view('home');
}
Then, when generating the URL, I did not have to save() the User, only read from it:
// Providers/EveAuth.php
function generateUrl()
{
$authedUser = auth()->user();
$user = User::find($authedUser->id);
$baseUrl = 'https://login.eveonline.com/oauth/authorize?state=';
return $baseUrl . $user->state;
}
This worked! The only difference (as far as I see) is that I'm save()ing the model before page assembly begins, as opposed to during page assembly.
I've created a form which adds a category of product in a Categories table (for example Sugar Products or Beer), and each user has their own category names.
The Categories table has the columns id, category_name, userId, created_At, updated_At.
I've made the validation and every thing is okay. But now I want every user to have a unique category_name. I've created this in phpMyAdmin and made a unique index on (category_name and userId).
So my question is this: when completing the form and let us say that you forgot and enter a category twice... this category exist in the database, and eloquent throws me an error. I want just like in the validation when there is error to redirect me to in my case /dash/warehouse and says dude you are trying to enter one category twice ... please consider it again ... or whatever. I am new in laravel and php, sorry for my language but is important to me to know why is this happens and how i solve this. Look at my controller if you need something more i will give it to you.
class ErpController extends Controller{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('pages.erp.dash');
}
public function getWarehouse()
{
$welcome = Auth::user()->fName . ' ' . Auth::user()->lName;
$groups = Group::where('userId',Auth::user()->id)->get();
return view('pages.erp.warehouse', compact('welcome','groups'));
}
public function postWarehouse(Request $request)
{
$input = \Input::all();
$rules = array(
'masterCategory' => 'required|min:3|max:80'
);
$v = \Validator::make($input, $rules);
if ($v->passes()) {
$group = new Group;
$group->group = $input['masterCategory'];
$group->userId = Auth::user()->id;
$group->save();
return redirect('dash/warehouse');
} else {
return redirect('dash/warehouse')->withInput()->withErrors($v);
}
}
}
You can make a rule like this:
$rules = array(
'category_name' => 'unique:categories,category_name'
);