Laravel Post Controller Method and PostController not Working - php

My Laravel blog project the get method of postcontroller is working but post method is not working. I redirect The Post Method. But Accordind to my my code it should return to my Admin page.My Controller Code is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
use App\Category;
class PostController extends Controller
{
public function getBlogIndex() {
return view('frontend.blog.index');
}
public function getSinglePost($post_id,$end='frontend') {
return view($end . '.blog.single');
}
public function getCreatePost() {
return view('admin.blog.create_post');
}
public function postCreatePost(Request $request ) {
$this->validate($request, [
'title' => 'required|max:120|unique:posts',
'author' => 'required|max:80',
'body' => 'required'
]);
$post = new Post();
$post->title = $request['title'];
$post->author = $request['author'];
$post->body = $request['body'];
$post->save();
return redirect()->route('admin.index')->with(['success' => 'Post Successfully Created']);
}
}
My Routes file
<?php
Route::group(['middleware' => ['web']], function () {
Route::group([
'prefix' =>'/admin'
], function() {
Route::get('/', [
'uses' => 'AdminController#getIndex',
'as' => 'admin.index'
]);
Route::get('/blog/posts/create', [
'uses' => 'PostController#getCreatePost',
'as' => 'admin.blog.create_post'
]);
Route::get('/blog/post/create', [
'uses' => 'PostController#postCreatePost',
'as' => 'admin.blog.post.create'
]);
});
});
My form is
#extends('layouts.admin-master')
#section('styles')
{!! Html::style('src/css/form.css') !!}
#endsection
#section('content')
<div class="container">
#include('includes.info-box')
<form action="{{ route('admin.blog.post.create') }}" method="post">
<div class="input-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" {{ $errors->has('title') ? 'class=has-error' : '' }} value="{{ Request::old('title') }}">
</div>
<div class="input-group">
<label for="author">Author</label>
<input type="text" name="author" id="author" {{ $errors->has('author') ? 'class=has-error' : '' }} value="{{ Request::old('author') }}">
</div>
<div class="input-group">
<label for="category_select">Add Category</label>
<select name="category_select" id="category_select">
<option value="Dummy Category ID">Dummy Category</option>
</select>
<button type="button" class="btn">Add Category</button>
<div class="added-categories">
<ul></ul>
</div>
<input type="hidden" name="categories" id="categories">
</div>
<div class="input-group">
<label for="body">Body</label>
<textarea name="body" id="body" rows="12" {{ $errors->has('body') ? 'class=has-error' : '' }} >{{ Request::old('body') }}</textarea>
</div>
<button type="submit" class="btn">Create Post</button>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</div>
#endsection
#section('scripts')
{!! Html::script('src/js/posts.js') !!}
#endsection
When I submit My post I shows this
I dont find where the problem is. Plz Help Me

This is an extremely common error and a good one to look out for. Whenever you see:
MethodNotAllowedHttpException in RouteCollection.php
The very first thing you should check is your routes file to make sure you have Route::get or Route::post correctly based on what you are trying to do.
Your issue is that your form sends the data as POST, but your route is GET.
<form action="{{ route('admin.blog.post.create') }}" method="post">
and
Route::get('/blog/post/create', [
'uses' => 'PostController#postCreatePost',
'as' => 'admin.blog.post.create'
]);
Change that to Route::post for it to function correctly.

Related

Laravel 5.7 : Update method return "No message"

I have tried everything and I can't figure out where comes my mistake.
the update() method doesn't update anaything, i only get back "No message" error...
Here's Routes in web.php:
Route::get('/user/edit/{id}', ['as' => 'users.edit', 'uses' => 'UserAdController#edit']);
Route::post('/user/update/{id}', ['as' => 'users.update', 'uses' =>'UserAdController#update']);
the view users/edit.blade.php :
<div class="container">
<br>
<h3>Edit your ad</h3>
<br>
<form method="post" action="{{route('users.update', $ad->id)}}">
<input name="_method" type="hidden" value="PATCH">
{{ method_field('post') }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" id="title" value="{{$ad->title}}">
</div>
<div class="form-group">
<label for="title">Price</label>
<input type="text" name="price" class="form-control" id="title" value="{{$ad->price}}">
</div>
<div class="form-group">
<label for="content">Your content</label>
<textarea name="content" class="form-control" id="content" rows="3">{{$ad->content}}</textarea>
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-info">
</div>
</form>
</div>
#endsection
Update method from UserAdController:
public function update($id, Request $request){
$request->validate([
'title'=>'required',
'price'=> 'required|integer',
'content' => 'required'
]);
$data = \App\Ad::find($id);
$data->title = $request->get('title');
$data->price = $request->get('price');
$data->content = $request->get('content');
$data->save();
return redirect()->back()->with('success', 'Data updated');
}
I'm not a laravel dev. I just stumbled on the documentation. You should also add the csrf field to your blade
In edit.blade.php, add this after the opening <form> tag
{{csrf_field()}}
Also the parameters in your update method aren't well arranged
It should be
public function update(Request $request, $id) {
}
The second parameter($id), comes from what you've defined as your routes in web.php file
Route::post('/user/update/{id}', ['as' => 'users.update', 'uses' =>'UserAdController#update']);
Where {id} would be replaced by the original id
Try this instead
public function update(Request $request){
//your code here
}
Request->only() returns an array with one element, While validator is the most common way to handle validation for the incoming request.
use Validator;
public function update(Request $request, $id){
$v = validator($request->only('title', 'price', 'content'), [
'title' => 'required|string|max:255',
'price' => 'required|integer',
'content' => 'required',
]);
$data = request()->only('title','price','content');
$userData = ([
'title' => $data['title'],
'price' => $data['price'],
'content' => $data['content'],
]);
$data = \App\Ad::find($id);
$data->update($userData);
return response()->json($data);
}
Thank you all !!
Seems like I wasn't doing it right.
I needed to add {{csrf_field()}} in edit form and use $request->only()
I think it would be better if you use put method like this:
Route::put('ad/{ad}', ['as' => 'users.update', 'uses' =>'UserAdController#update']);
update your form to be like this:
<div class="container">
<br>
<h3>Edit your ad</h3>
<br>
<form method="post" action="{{route('users.update', ['ad' => $ad->id])}}">
<input name="_method" type="hidden" value="PATCH">
{{ method_field('put') }}
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" id="title" value="{{$ad->title}}">
</div>
<div class="form-group">
<label for="title">Price</label>
<input type="text" name="price" class="form-control" id="title" value="{{$ad->price}}">
</div>
<div class="form-group">
<label for="content">Your content</label>
<textarea name="content" class="form-control" id="content" rows="3">{{$ad->content}}</textarea>
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-info">
</div>
</form>
and now your update function :
public function update(\App\Ad $ad, Request $request){
$request->validate([
'title'=>'required',
'price'=> 'required|integer',
'content' => 'required'
]);
//$data = \App\Ad::find($id);
$ad->update([
"title" => $request->title,
"price" => $request->price,
"content" => $request->content,
]);
return redirect()->back()->with('success', 'Data updated');
}
when you get use to put, delete and patch methods you can read about Route::resource and your code will be easier.

Laravel 5.7 MethodNotAllowedHttpException

I am getting an MethodNotAllowedHttpException error while im trying to update mine post. So I googled the error and found this laravel throwing MethodNotAllowedHttpException but it get explained that i need to make the route
an post request, where mine form actions go thruw but its already a post and it keeps throwing the same error and i cant figure out if the erros is in the form the web.php or the controller it self
edit.blade.php
<form method="POST" action="/posts/{{ $post->id }}/edit">
{{ csrf_field() }}
#method('PUT')
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" id="title" name="title" value="{{ $post->title }}">
</div>
<div class="form-group">
<label for="body">Body:</label>
<textarea id="body" name="body" class="form-control" rows="10">
{{
$post->body
}}
</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Edit</button>
</div>
#include('layouts.errors')
</form>
Web.php
Route::get('/', 'PostsController#index')->name('home');
Route::get('/posts/create', 'PostsController#create');
Route::post('/posts', 'PostsController#store');
Route::get('/posts/{post}', 'PostsController#show');
Route::get('/posts/{post}/edit', 'PostsController#edit');
Route::post('/posts/{post}/edit', 'PostsController#update');
Route::get('/posts/{post}/delete', 'PostsController#destroy');
PostsController.php
(this is the part that matters out of the controller if u want me to post the hole controller let me know)
public function edit(Post $post)
{
return view('posts.edit', compact('post'));
}
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'body' => 'required'
]);
$post->update($request->all());
return redirect('/')->with('succes','Product updated succesfully');
}
You should try this:
View file:
<form method="POST" action="{{ route('post.update',[$post->id]) }}">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" id="title" name="title" value="{{ $post->title }}">
</div>
<div class="form-group">
<label for="body">Body:</label>
<textarea id="body" name="body" class="form-control" rows="10">
{{
$post->body
}}
</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Edit</button>
</div>
#include('layouts.errors')
</form>
Your Route
Route::post('/posts/{post}/edit', 'PostsController#update')->name('post.update');
You are submitting the form with the put method as defining #method('PUT') will make it a put route. Either define a route for put method like this Route::put('/posts/{post}/edit', 'PostsController#update'); or remove #method('PUT') from your blade file.
This problem 1 week took me but i solve it with routing
In edit.blade.php
{!! Form::open([route('post.update',[$post->id]),'method'=>'put']) !!}
<div class="form-group">
<label for="title">Title:</label>
{!! Form::text('title',$post->title,['class'=>'form-control',
'id'=>'title']) !!}
</div>
<div class="form-group">
<label for="body">Body:</label>
{!! Form::textarea('body', $post->body, ['id' => 'body', 'rows' => 10,
class => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Edit',['class'=>'btn btn-block bg-primary',
'name'=>'update-post']) !!}
</div>
{!! Form::close() !!}
#include('layouts.errors')
In Web.php
Route::resource('posts','PostsController');
Route::get('/posts/{post}/delete', 'PostsController#destroy');
Route::put('/posts/{post}/edit',['as'=>'post.update',
'uses'=>'PostController#update']);
Route::get('/', 'PostsController#index')->name('home');
Laravel will throw a MethodNotAllowedHttpException exception also if a form is placed by mistake this way inside a table:
<table><form><tr><td>...</td></tr></form><table>
instead of this :
<table><tr><td><form>...</form></td></tr></table>

how to include blade file in Laravel 5.2

I am developing Laravel application and I need add comment form to My each task file regarding to each project.
this is comments/form.blade.php
<form class="form-vertical" role="form" method="post" action="{{ route('projects.comments.create', $project->id) }}">
<div class="form-group{{ $errors->has('comments') ? ' has-error' : '' }}">
<textarea name="comments" class="form-control" style="width:80%;" id="comment" rows="5" cols="5"></textarea>
#if ($errors->has('comments'))
<span class="help-block">{{ $errors->first('comments') }}</span>
#endif
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Add Comment</button>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
I am going to include this form file to show.blade.php file in tasks folder in view file.
this is show.blade.php
<h2>{{ $tasks->project->project_name }}</h2>
<hr>
{{$tasks->task_name}}
<hr>
{!!$tasks->body!!}
<hr>
#include('comments.form')
commentController.php
public function postNewComment(Request $request, $id, Comment $comment)
{
$this->validate($request, [
'comments' => 'required|min:5',
]);
$comment->comments = $request->input('comments');
$comment->project_id = $id;
$comment->user_id = Auth::user()->id;
$comment->save();
return redirect()->back()->with('info', 'Comment posted successfully');
}
routes.php
Route::post('projects/{projects}/comments', [
'uses' => 'CommentsController#postNewComment',
'as' => 'projects.comments.create',
'middleware' => ['auth']
]);
but finally got this error massage
Undefined variable: project (View: C:\Users\Nalaka\Desktop\acxian\resources\views\comments\form.blade.php)
how can fix this problem?
You have not defined $project anywhere but you have $tasks from which you are getting project name already in show.blade.php so if you have project id also there in $tasks->project data then you can use this variable in view change form tag in comments/form.blade.php as below:
<form class="form-vertical" role="form" method="post" action="{{ route('projects.comments.create', $tasks->project->id) }}">

Success and error message does'nt show

Hello i am new to laravel i created page to added single post but for some reason success and errors messages doesn't appear at all not matter i successfully insert a new post or submit empty form although some fields are required .. in my controller i am using this method postCreatePost
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Catgory;
class PostController extends Controller {
public function getBlogIndex() {
return view ('frontend.blog.index');
}
public function getSignlePost($post_id, $end = 'frontend') {
return view ($end, '.blog.single');
}
public function getCreatePost() {
return view('admin.blog.create_post');
}
public function postCreatePost(Request $request) {
$this->validate($request, [
'title' => 'required|max:120|unique:posts',
'author' => 'required|max:80',
'body' => 'required'
]);
$post = new Post();
$post->title = $request['title'];
$post->author = $request['author'];
$post->body = $request['body'];
$post->save();
//Attaching categories
return redirect()->route('admin.index')->with(['success','Post sucessfully created!']);
}
}
This is my view
#extends('layouts.admin-master')
#section('styles')
<link rel="stylesheet" href="{{ URL::secure('src/css/form.css') }}" type="text/css" />
#endsection
#section('content')
<div class="container">
#section('styles')
<link rel="stylesheet" href="{{ URL::to('src/css/common.css') }}" type="text/css" />
#append
#if(Session::has('fail'))
<section class="info-box fail">
{{ Session::get('fail') }}
</section>
#endif
{{ var_dump(Session::get('success')) }}
#if(Session::has('success'))
<section class="info-box success">
{{ Session::get('success') }}
</section>
#endif
#if(count($errors) > 0)
<section class="info-box fail">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</section>
#endif
<form action="{{ route('admin.blog.post.create') }}" method="post">
<div class="input-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" {{ $errors->has('title') ? 'claass=has-error' : '' }} />
</div>
<div class="input-group">
<label for="author">Author</label>
<input type="text" name="author" id="author" {{ $errors->has('author') ? 'claass=has-error' : '' }} />
</div>
<div class="input-group">
<label for="category_select">Add Categories</label>
<select name="category_select" id="category_select">
<!-- Foreach loop to output categories -->
<option value="Dummy Category ID">Dummy Category</option>
</select>
<button type="button" class="btn">Add Category</button>
<div class="added-categories">
<ul></ul>
</div>
</div>
<input type="hidden" name="categories" id="categories">
<div class="input-group">
<label for="body">Body</label>
<textarea name="body" id="body" cols="30" rows="10" {{ $errors->has('body') ? 'claass=has-error' : '' }}></textarea>
</div>
<button type="submit" class="btn">Create Post</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
</div>
#endsection
#section('scripts')
<script type="text/javascript" src="{{ URL::secure('src/js/posts.js') }}"></script>
#endsection
My routes inside web middleware
Route::group(['middleware' => ['web']], function () {
Route::get('/about', function() {
return view('frontend.other.about');
})->name('about');
Route::group([
'prefix' => '/admin'
], function() {
Route::get('/', [
'uses' => 'AdminController#getIndex',
'as' => 'admin.index'
]);
Route::get('/blog/posts/create', [
'uses' => 'PostController#getCreatePost',
'as' => 'admin.blog.create_post'
]);
Route::post('/blog/post/create', [
'uses' => 'PostController#postCreatePost',
'as' => 'admin.blog.post.create'
]);
});
});
And the model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories() {
return $this->belongsToMany('App\Category', 'posts_categories');
}
}
You're using wrong syntax. Try this one:
return redirect()->route('admin.index')->with('success','Post sucessfully created!');

Laravel 5.2 Validation Error not appearing in blade

I want to show validation Error in View page while user giving wrong input. It's Ok that it's not saving anything in database while a user giving wrong input. But there is no error message in user view page. If anyone find the error, please help me out.
Here is the controller:
public function saveUser(Request $request){
$this->validate($request,[
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'phone' => 'required|min:11|numeric',
'course_id'=>'required'
]);
$user = new User();
$user->name= $request->Input(['name']);
$user->email= $request->Input(['email']);
$user->phone= $request->Input(['phone']);
$user->date = date('Y-m-d');
$user->completed_status = '0';
$user->course_id=$request->Input(['course_id']);
$user->save();
return redirect('success');
}
Here is the route:
Route::group(['middleware' => 'web'], function () {
Route::get('/', function () {
return view('index');
})->name('main');
Route::post('/saveUser',[
'uses' => 'AppController#saveUser',
'as'=>'saveUser',
]);
});
Here is the blade view page:
#extends('layouts.master')
#section('title')
Create User
#endsection
#section('content')
#include('partials.message-block')
<div class="container" >
<h3> Student Register </h3>
{!! Form::open(array('route' => 'saveUser','class'=>'form-horizontal','method'=>'POST')) !!}
{!! Form::token(); !!}
{!! csrf_field() ; !!}
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required placeholder="Name">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" required placeholder="email">
</div>
<div class="form-group">
<label>Phone Number</label>
<input type="text" name="phone" class="form-control" required placeholder="phone">
</div>
<div class="form-group">
<label for="">Class</label>
<select class="form-control input-sm" name="course_id" >
#foreach($input as $row)
<option value="{{$row->id}}">{{$row->name}}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
{!! Form::close() !!}
</div>
#endsection
And here is the error-message block:
#if(count($errors) > 0)
<div class="row">
<div class="col-md-4 col-md-offset-4 error">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
</div>
#endif
#if(Session::has('message'))
<div class="row">
<div class="col-md-4 col-md--offset-4 success">
{{Session::get('message')}}
</div>
</div>
#endif
Try to remove web middleware if you're using 5.2.27 or higher. The thing is now Laravel automatically applies web middleware to all routes inside routes.php and if you're trying to add it manually you can get errors.
app/Providers/RouteServiceProvider.php of the 5.2.27 version now adds web middleware to all routes inside routes.php:
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
Use Below line in your controller
use Validator;
Add below code in your controller function where your request is sent.
$validator = Validator::make($request->all(), [
'fname' => 'required|max:20|min:4',
'uemail' => 'required|email',
'message' => 'required',
]);
if ($validator->fails()) {
$messages = $validator->messages();
return Redirect::back()->withErrors($messages)->withInput($request->all());
}
In your view page
#if ($errors->any())
<label for="fname" class="error">{{ $errors->first('fname') }}</label>
#endif
For display individual field wise error.
if you are using laravel 5.2+ then please use the below code.
Moved \Illuminate\Session\Middleware\StartSession::class and \Illuminate\View\Middleware\ShareErrorsFromSession::class from web $middlewareGroups to $middleware in app\Http\Kernel.php
Alexey is correct and if you're not comfortable with that then you can just add this code into your view for the session messages to show.
#if(Session::has('message'))
<div class="alert alert-success">{{Session::get('message')}}</div>
#endif
#if(count($errors)>0)
<ul>
#foreach($errors->all() as $error)
<li class="alert alert-danger">{{$error}}</li>
#endforeach
</ul>
#endif
I've done this in laravel 5.5. Please do confirm if this helps you out.

Categories