Laravel update function data not passing to DB but no error - laravel

Hey guys we are new to Laravel and Stack(hope this is a clear question) and recently made a post trying an update method with ajax and js but returned many problems, and since returned to a basic Laravel function. For some reason we can't quite understand why this function is not returning any data, there aren't any errors since we had parsed through them all.. sql constraints, null data, Symfony handler etc etc.. as well as obviously reading other similar stack questions but with no resolution. We have tried to change the controller function, the method calls (PUT PATCH POST) Does anybody have any suggestions what is going wrong here? I'm sure its really obvious.. thank you!
Quindi.. User clicks edit post, makes edit, confirm.. page refreshes with no changes, no error and no data in database.
<form id="form-edit-post" action="/posts/{{ $post->id }}/update" method="POST" data-parsley-validate>
{{ csrf_field() }}
{{ method_field('PATCH') }}
Route::patch('/posts/{id}/update', [PostsController::class, 'update'])->name('post.update');
public function update(Request $request, Post $post)
{
$this->validate($request, array(
'content' => 'required',
'location' => 'required',
));
$post->user_id = Auth::user()->id;
$post->content = $request['content'];
$post->location = $request['location'];
$post->update();
return back()->with('success','Post Updated Successfully');
}

credit to #Brian Thompson!
Such a simple fix. use find method to find the id in controller (obviously), use save() not update().
public function update(Request $request, $id)
{
$post = Post::find($request->input('postid'));
$this->validate($request, array(
'content' => 'required',
'location' => 'required',
));
$post->user_id = Auth::user()->id;
$post->content = $request['content'];
$post->location = $request['location'];
$post->save();
return back()->with('success','Post Updated Successfully');
}

Related

Form submit intercepted by auth middleware in laravel 5

I've been working on a laravel 5.7 blog project. I want to comment an article.
I need to achieve this:
Before logging in, I can type anything in comment textarea
I submit comment (of course it would be intercepted by auth middleware)
then I'm redirected to login page
After logging in, I hope my app could submit previous form data (or comment) automatically instead of typing the same comment again
I think that's a very common business logic in many websites nowadays, but how am I supposed to achieve this?
My comments controller here:
public function __construct()
{
$this->middleware('auth');
}
public function store(Post $post) {
$comment = Comment::create([
'body' => session('comment')?:request('body'),
'post_id' => $post->id,
'user_id' => auth()->user()->id
//before logging in, you don't have an user_id yet.
]);
return back()->with('success', 'Add comment succeeded');
}
web.php Route here:
Route::post('/posts/{post}/comments', 'CommentsController#store')->name('addComment');
Basically auth middleware intercepted my form data submit, I want to go across the auth middleware with my form data. Not lost them after logging in.
Here is the solution.A little tricky.Save comment to the session first before go to auth middleware.After logging in, GET that route to create comment.
Route:
Route::get('/posts/{post}/comments', 'CommentsController#store')->name('addComment');
Route::post('/posts/{post}/comments', 'CommentsController#commentSave');
Comments controller:
public function __construct()
{
$this->middleware('auth', ['except' => ['commentSave']]);
}
public function commentSave(Request $request){
$url = \URL::previous();
session(['comment' => $request->input('body')]);
return redirect("$url/comments");
}
public function store(Post $post){
if(session('comment')){
$comment = Comment::create([
'body' => session('comment'),
'post_id' => $post->id,
'user_id' => auth()->user()->id
]);
session(['comment' => null]);
return redirect("posts/$post->id")->with('success', 'Add comment succeeded');
}
return redirect("posts/$post->id");
}
I think the solution to your problem is here:
https://laravel.com/docs/5.7/session#storing-data

Laravel 5.1, passing my ID

I'm trying to pass an ID of a past and insert it into another database.
I got a page with shows posts like this
/posts/{id}
. From there on i want to add a comment section, so i got my form set up like this:
<form method="POST" action="/posts/{{ $post->id }}/comments">
(When i inspect the code, it inserts the right id and the "{{ $posts->id }}" spot.
inside my routes.php i got the folling route:
Route::post('/posts/{post}/comments', 'CommentsController#store');
and inside CommentsController.php i got the following
public function store(Post $post)
{
Comment::create([
'body' => request('body'),
'post_id' => $post->id
]);
return back();
}
When ever i try to add a comment i get this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id'
cannot be null
When i change my code from CommentsController.php to this:
'post_id' => "2"
it works fine (but the comment will always be added at post with ID 2)
I can't seem to find out why my id wont go trough.
Anny help with this?
Try this
public function store(Request $request, Post $post)
{
$comment= new Comment;
$comment->body = $request->body;
$comment->post_id = $post->id;
$comment->save();
return back();
}
The route model binding allows you to convert the Post ID passed into the route into the actual post object in the controller method. It may even work smoother if you use a relationship between a post and a comment, like so:
public function store(Request $request, Post $post)
{
$post->comments->create([
'body' => $request->body
]);
return back();
}
Inside post model
public function comments()
{
return $this->hasMany('App\Comment','post_id');
}

Laravel undefine variable in view

I'm new to laravel. Using version 5.4 and tried to search but don't see what I'm doing wrong. I keep getting an "Undefined variable: post" in my view. I'm also doing form model binding. Model binding works properly when manually entering URL. Just can't click on link to bring up edit view.
My routes:
Route::get('test/{id}/edit','TestController#edit');
My controller:
public function edit($id)
{
$post = Post::find($id);
if(!$post)
abort(404);
return view('test/edit')->with('test', $post);
}
My form:
{{ Form::model($post, array('route' => array('test.update', $post->id), 'files' => true, 'method' => 'PUT')) }}
You're assigning the post value to 'test', so should be accessible with $test rather than $post.
You probably want to do either of these two things instead:
return view('test/edit')->with('post', $post);
or
return view('test/edit', ['post' => $post]);
https://laravel.com/docs/5.4/views
Your controller is sending a variable named "test", but your error says that your blade file doesn't have the $post variable passed into it. This can be fixed by changing "test" to "post" in your controller.

Laravel Editing post doesn't work

There are routes
Route::get('posts', 'PostsController#index');
Route::get('posts/create', 'PostsController#create');
Route::get('posts/{id}', 'PostsController#show')->name('posts.show');
Route::get('get-random-post', 'PostsController#getRandomPost');
Route::post('posts', 'PostsController#store');
Route::post('publish', 'PostsController#publish');
Route::post('unpublish', 'PostsController#unpublish');
Route::post('delete', 'PostsController#delete');
Route::post('restore', 'PostsController#restore');
Route::post('change-rating', 'PostsController#changeRating');
Route::get('dashboard/posts/{id}/edit', 'PostsController#edit');
Route::put('dashboard/posts/{id}', 'PostsController#update');
Route::get('dashboard', 'DashboardController#index');
Route::get('dashboard/posts/{id}', 'DashboardController#show')->name('dashboard.show');
Route::get('dashboard/published', 'DashboardController#published');
Route::get('dashboard/deleted', 'DashboardController#deleted');
methods in PostsController
public function edit($id)
{
$post = Post::findOrFail($id);
return view('dashboard.edit', compact('post'));
}
public function update($id, PostRequest $request)
{
$post = Post::findOrFail($id);
$post->update($request->all());
return redirect()->route('dashboard.show', ["id" => $post->id]);
}
but when I change post and click submit button, I get an error
MethodNotAllowedHttpException in RouteCollection.php line 233:
What's wrong? How to fix it?
upd
opening of the form from the view
{!! Form::model($post, ['method'=> 'PATCH', 'action' => ['PostsController#update', $post->id], 'id' => 'edit-post']) !!}
and as result I get
<form method="POST" action="http://mytestsite/dashboard/posts?6" accept-charset="UTF-8" id="edit-post"><input name="_method" type="hidden" value="PATCH"><input name="_token" type="hidden" value="aiDh4YNQfLwB20KknKb0R9LpDFNmArhka0X3kIrb">
but why this action http://mytestsite/dashboard/posts?6 ???
Try to use patch instead of put in your route for updating.
Just a small tip you can save energy and a bit of time by declaring the Model in your parameters like this:
public function update(Post $id, PostRequest $request)
and get rid of this
$post = Post::findOrFail($id);
EDIT
You can use url in your form instead of action :
'url'=> '/mytestsite/dashboard/posts/{{$post->id}}'
Based on the error message, the most probable reason is the mismatch between action and route. Maybe route requires POST method, but the action is GET. Check it.
Try to send post id in hidden input, don't use smt like that 'action' => ['PostsController#update', $post->id]
It contribute to result action url.

Redirect back to same page (with variables) on form submit in Laravel 5

On my page events.index, I first display a list of events for the logged on user.
On my index page I have a form with option/select to let the user select and display the events of another user. When he submits that form, I would like my index function (controller) to use the $user_id value (from the form) and display the events.index page again, but for events of that selected user.
I'm not sure what would be the best approach:
Set a session variable to keep the user_id value? Not sure how to do that with a form.
Submit the form with a get method (and get an ugly ?user_id=1 URL)
Change my index route to accept the post method (although I already have that post/events route taken (by Route::post('events', 'EventsController#store'))
Not sure what would be a clean way to do this:
My route for events/index:
Route::get('events', [
'as' => 'event.index',
'uses' => 'EventsController#index'
]);
Events Controller
public function index()
{
// How to get the $user_id value from form?
if (empty($user_id))
{
$user_id = \Auth::user()->id;
}
$events = Event::where('events.user_id','=','$user_id');
$users = User::all();
return view('events.index')->with(['events' => $events])->with(['users' => $users]);
}
View for index
{!! Form::open(['route' => 'events.index', 'method' => 'get']) !!}
<select id="user_id" name="user_id">
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
{!! Form::submit('Show events for this user') !!}
{!! Form::close() !!}
#foreach($events as $event)
...
#endforeach
You can get the user_id from a Request object, you just need to inject it in the index method:
public function index(Request $request)
{
$user_id = $request->get('user_id') ?: Auth::id();
$events = Event::where('events.user_id','=','$user_id')->get();
$users = User::all();
return view('events.index')->with(['events' => $events])->with(['users' => $users]);
}

Resources