Laravel 5.1, passing my ID - laravel

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');
}

Related

Laravel update function data not passing to DB but no error

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');
}

Laravel: Accessing Path Function in Model in Index File

I have set up the following function in my model:
public function path() {
return route('news.show', ['id' => $this->id, 'slug' => $this->slug]);
}
I would now like to access that function in my index.blade.php file -- like this:
#foreach ($articles as $article)
<a href="{{ $article->path() }}">
// rest of code goes here
</a>
#endforeach
But when I try this, I get the following error:
Facade\Ignition\Exceptions\ViewException
Missing required parameters for [Route: news.show] [URI: news/{id}/{slug}]. (View: C:\laragon\www\startup-reporter\resources\views\news\index.blade.php)
Here is what my routes (web.php) looks like:
Route::get('news', 'NewsController#index')->name('news.index');
Route::get('news/create', 'NewsController#create')->name('news.create');
Route::get('news/{id}/{slug}', 'NewsController#show')->name('news.show');
Route::get('news/{id}/edit', 'NewsController#edit')->name('news.edit');
Route::post('news', 'NewsController#store')->name('news.store');
Route::put('news/{id}', 'NewsController#update');
And here is my controller:
// Index
public function index() {
$news = News::latest()->get();
return view('news.index', ['articles' => $news]);
}
// Show
public function show(News $id) {
return view('news.show', compact('id'));
}
Any idea why this is not working and what I need to do to get this to work?
Thanks.
In your routes file you have defined 2 parameters, {id} and {slug}.
But in your controller you have only accepted 1 parameter, $id.
You should amend your show controller method like this:
// Show
public function show(News $id, $slug) {
return view('news.show', compact('id'));
}

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

Laravel5.6 "Call to a member function delete() on null " , delete a row in table

I want to delete a row from table. The function I used in controller is:
public function destroy($id) {
$category = Category::find($id);
$category->delete();
return redirect()->back();
}
However it throws me an error:
Call to a member function delete() on null
When I use this code:
public function destroy($id) {
$category = Category::find($id);
dd($id);
}
It is showing the correct id i.e.
"1"
And when I use
public function destroy($id) {
$category = Category::find($id);
dd($category); // or
dd(Category::find($id);
}
I get the output
null
on the screen.
As mentioned in comments, the error you're getting is probably due to no category exists in the database for the given ID.
Then, when you try to find the category for that ID:
$category = Category::find($id);
The value of $category variable is null. Therefore, you get an error for trying to call delete() method on null. Under the hood, it would be the same as doing the following:
null->delete();
Which, doesn't work.
You could check the value of $category before trying to delete it. Or you may use a query to delete all records matching a given condition, in your case id = $id. This way:
public function destroy($id)
{
Category::where('id', $id)->delete();
return redirect('/')->back();
}
Refer to Deleting Models By Query in the Eloquent docs for details on how that works.
What worked for me is the following (I ensured that the $id was passing from the view):
public function destroy($id)
{
$vendor = Vendor::findorFail($id);
$vendor->delete():
}
for some reason when I did the following it showed null
public function destroy($id)
{
$vendor = Vendor::find($id);
$vendor->delete():
}
This is the view part:
{!! Form::open(array(
'style' => 'display: inline-block;',
'method' => 'DELETE',
'onsubmit' => "return confirm('".trans("global.app_are_you_sure")."');",
'route' => ['vendor.destroy', $vendor->vendor_id])) !!}
{!! Form::submit(trans('global.app_delete'), array('class' => 'btn btn-xs btn-danger')) !!}
{!! Form::close() !!}

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.

Resources