For Button action it is showing "MethodNotAllowedHttpException Laravel 5" - laravel-5

button code
<button type="submit" name="_token" value="<?php echo csrf_token(); ?>" href="{{route('regi') }}" class="btn">Sign up!</button>
route
Route::get('regi', array('as' => 'regi', 'uses' => function()
{
return view('register');
}));
error
in RouteCollection.php line 219
at RouteCollection->methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php line 206
at RouteCollection->getRouteForMethods(object(Request), array('GET', 'HEAD')) in RouteCollection.php line 158
I'm new to Laravel.So I can not figure out error.Please help me.Thanks in advance.

Related

Route Login is not defined in Laravel

I have one problem, why when I accessing the login/register page always given Route [login] is not defined I already try to search for my problem and nothing result happen, I will give my detail in bellow.
User Controller :
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
in that case, I wanna get the token and user detail after successful login, and it's working I got the token and I got the user detail, but when I logout and back into the login or register page, it's error, and for the message Route [login] is not defined, but when I delete the __construct() it's working, but when I login again with my same account, the token and detail user is giving null value, I will give my route detail in the bellow.
Route :
Route::get('/', function () {
return redirect('auth');
});
Route::get('auth', 'UserController#viewLogin');
Route::get('register', 'UserController#viewRegister');
Route::get('dashboard', 'DashboardController#view');
Route::group(['prefix' => 'auth'], function () {
Route::post('login', 'UserController#login');
Route::post('logout', 'UserController#logout');
Route::get('user-profile', 'UserController#userProfile')->middleware('jwt.verify');
});
Update Login Post :
$user_data = [
'email' => $email,
'password' => $password,
'is_active' => 1
];
$user_credentials = JWTAuth::attempt($user_data);
if (!$user_credentials) {
return response()->json([
'error_message' => 'Your account is not registered yet, please register first'
], 401);
} else {
return response()->json([
'user' => JWTAuth::user(),
'token' => $user_credentials,
'success_message' => "Login Successfuly",
]);
}
Form Login :
<form action="javascript:;" method="POST" autocomplete="off">
#csrf
<div class="form-group">
<label class="font-weight-normal">Email</label>
<div class="input-group">
<input type="email" class="form-control" name="email" placeholder="user#mail.com">
<div class="input-group-append">
<div class="input-group-text input-group-email">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<div class="text-danger" id="email-err"></div>
</div>
<div class="form-group">
<label class="font-weight-normal">Password</label>
<div class="input-group">
<input type="password" class="form-control" name="password" placeholder="********">
<div class="input-group-append">
<div class="input-group-text input-group-password">
<span class="fas fa-eye clicked" id="show-hide"></span>
</div>
</div>
</div>
<div class="text-danger" id="password-err"></div>
</div>
<div class="row">
<div class="col-12">
<button type="submit" id="login-process" class="btn btn-block" disabled>Sign In</button>
</div>
</div>
</form>
Javascript :
$("#login-process").on('click', function () {
const emailValue = $("input[name='email']").val();
const passwordValue = $("input[name='password']").val();
$.ajax({
url: "auth/login",
method: "POST",
async: true,
data: {
email: emailValue,
password: passwordValue,
},
success: function (success) {
// describe one by one success method
const accessToken = success['token'];
const successMessage = success['success_message'];
localStorage.setItem('monitoring-barang', accessToken);
window.location.replace('dashboard');
},
});
});
This error is probably related to your XHR request not having the correct Accept header (which should be application/json).
This will make the auth middleware respond, but even though you combined it with api, the lacking Accept header will make the web middleware group respond with it's authentication.
This will effectively fire the redirectTo method in app/Http/Middleware/Authenticate.php where, on line 18, there's a reference to the route named login, a route you have explicitly not added by adding the except parameter to the middleware method in your controller.
The solution is to either comment out redirect out, make a dummy route for the purpose or implement a better strategy like Sanctum

production.ERROR: Route [appraisal.appraisal_goals.manager_employee_goal_list] not defined in Laravel

In Laravel-5.8 application, a form is submitted and notification is submitted through:
$userId = Auth::user()->id;
'actionURL' => route('appraisal.appraisal_goals.manager_employee_goal', ['id'=>$userId]),
This correctly send notification:
[![notification][1]][1]
route:
Route::group(['prefix' => 'appraisal', 'as' => 'appraisal.', 'namespace' => 'Appraisal', 'middleware' => ['auth']], function () {
Route::get('appraisal_goals/goal_review', 'AppraisalGoalsController#goal_review')->name('appraisal_goals.goal_review');
Route::get('appraisal_goals/manager_employee_list', 'AppraisalGoalsController#manager_employee_list')->name('appraisal_goals.manager_employee_list');
Route::get('appraisal_goals/manager_employee_goal/{id?}', 'AppraisalGoalsController#manager_employee_goal')->name('appraisal_goals.manager_employee_goal');
Route::get('appraisal_goals/manager_employee_goal_list/{id?}', 'AppraisalGoalsController#manager_employee_goal_list')->name('aappraisal_goals.manager_employee_goal_list');
});
manager_employee_goal.blade
<td>
#if(in_array($goal->is_approved, [1, 2, 3]))
<a class="btn btn-xs btn-primary" href="{{ route('appraisal.appraisal_goals.manager_employee_goal_list', ['id'=>$goal->id]) }}">
{{ trans('global.view') }}
</a> #endif #if(in_array($goal->is_approved, [1]))
<a class="btn btn-xs btn-info" data-toggle="modal" data-target="#comment{{ $goal->id }}" data-original-title="Comment">Comment</a> #endif
</td>
When the user clicks on the button on the notification as shown in the diagram, it suppose to redirect to:
Route::get('appraisal_goals/manager_employee_goal/{id?}', 'AppraisalGoalsController#manager_employee_goal')->name('appraisal_goals.manager_employee_goal');
But I got error 500 and the browser url has:
http://localhost:8888/myapp/appraisal/appraisal_goals/manager_employee_goal/470
The the Log has this error:
2020-10-22 17:29:51] production.ERROR: Route [appraisal.appraisal_goals.manager_employee_goal_list] not defined. (View: C:\xampp\htdocs\pmyapp\resources\views\appraisal\appraisal_goals\manager_employee_goal.blade.php) {"userId":469,"exception":"[object] (ErrorException(code: 0): Route [appraisal.appraisal_goals.manager_employee_goal_list] not defined. (View: C:\xampp\htdocs\myapp
esources\views\appraisal\appraisal_goals\manager_employee_goal.blade.php) at C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php:388, InvalidArgumentException(code: 0): Route [appraisal.appraisal_goals.manager_employee_goal_list] not defined. at C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php:388)
I didn't call:
appraisal.appraisal_goals.manager_employee_goal_list
Why is it coming up and how do I resolve this error?
Thanks

commenting module by ajax not working in laravel 5

i am working on commenting module in my project by ajax. i am getting this error
POST http://127.0.0.1:8000/comments 500 (Internal Server Error)
and the data not post. what i am doing wrong? My route is a resource route and i want to display it without refreshing the page .
Form
<form action="{{route('comments.store')}}" method="post">
{{ csrf_field() }}
<div class="col-md-11 col-sm-11">
<div class="form-group">
<textarea name="comment-msg" id="comment-name" cols="30" rows="1" class="form-control" placeholder="comment here..."></textarea>
<input type="hidden" id="eventID" name="eventID" value="<?php echo $eventData->id; ?>">
<input type="hidden" id="userID" name="userID" value="<?php echo Auth::user()->id; ?>">
</div>
</div>
<div class="col-md-12">
<button type="submit" id="submit-comment" class="btn-primary pull-right">Comment</button>
</div>
</form>
Ajax Call
<script>
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
});
$( '#submit-comment' ).click(function() {
var formData = {
'message' : $('#comment-msg').val(),
'eventID' : $('#eventID').val(),
'userID' : $('#userID').val(),
};
$.ajax({
type : 'POST',
url : '{{route('comments.store')}}',
data : formData,
dataType : 'json',
encode : true,
success: function (response) {
console.log(response);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
event.preventDefault();
} );
</script>
Controller
public function store(Request $request)
{
$content = $request->input( 'comment-msg' );
$userID = $request->input( 'userID' );
$eventID = $request->input( 'eventID' );
$response=Comment::create([
'user_id' => $userID,
'event_id' => $eventID,
'message' => $content,
]);
return response()->json($response);
}
Route
Route::resource('comments', 'CommentsController');

Laravel not able to pass more than 1 return - how can that be done using similar method?

I have a small problem with redirecting a user once page is created.
Problem is that all together I have 3 returns within 2 functions and obviously that can't be done and I am looking for a way to change this but I don't know what should it be.
Process is like this.
User creates a page: code is saved into javascript variable.
User chooses a name for a page: code is saved into another javascript variable.
Ajax is passing these values to Controller and then:
public function postDB(Request $request) {
$newName = $request->input('name_website');
$newLat = $request->input('newCode');
$websites = new Website();
$websites->name = $newName;
$websites->html = $newLat;
$websites->save();
return $newName;
return $this->website($newName);
}
public function website($newName)
{
dd($newName);
Website::where('name', $newName)->first()->html;
return view('layouts/website');
}
After saving into a database I am returning value of $newName which is the actual name for a website or I should say URL and also return (call another function) which then search for html code that matches a name, and return view that deals with displaying it:
#extends('layouts.master') #section('title', 'Website Builder') #section('content')
<meta name="csrf-token" content="{{ csrf_token() }}" />
{{html_entity_decode($name->html)}}
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.get('/name').then(
html => document.querySelector('html').innerHTML = html
);
</script>
</html>
#endsection #show
So basically after user saved it to database I want to redirect them to a page which is in saved variable $newName and retrieve + display html that matches name that is in the variable.
Route::group(['middleware' => ['web']], function () {
Route::get('home', 'BuilderController#homepage');
Route::get('template', 'BuilderController#templates');
Route::post('template', 'BuilderController#postDB');
Route::get('logout', 'BuilderController#getLogout');
Route::get('/{name}', 'BuilderController#website');
});
template.blade.php
<button onClick=" updateDatabase(this);" type="button" class="form-control margin btn btn-success" id="getRequest changes">
Save Website
</button>
JS:
var web_name;
function updateDatabase(newCode, name_website)
{
code2 = document.getElementById("content-link2").innerHTML;
web_name = ($('#website_name').val());
// make an ajax request to a PHP file
// on our site that will update the database
// pass in our lat/lng as parameters
$.post('http://localhost/template', {
_token: $('meta[name=csrf-token]').attr('content'),
newCode: (code2),
name_website: (web_name),
})
.done(function() {
})
.fail(function() {
alert("error");
});
}
EDIT: I have update my code like I was told in the answer below but now I am getting:
Trying to get property of non-object (View: C:\xampp\htdocs\fyproject\resources\views\layouts\website.blade.php)
in 87bb9cbe60b5bd1fe6f78e1246f2227dbd0f328f.php line 5
at CompilerEngine->handleViewException(object(ErrorException), '1') in PhpEngine.php line 44
at PhpEngine->evaluatePath('C:\xampp\htdocs\fyproject\storage\framework\views/87bb9cbe60b5bd1fe6f78e1246f2227dbd0f328f.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'name' => ' <title>Template 1</title> <link href="http://localhost/templates/css.css" rel="stylesheet" type="text/css"> <div class="logo"> <img class="images" id="image" src="#" alt="Your Logo"> </div> <div contenteditable="true" id="content" class="draggable ui-widget-content refresh ui-draggable ui-draggable-handle" style="position: relative; left: 209px; top: 139px;"><p>Change Text inside this box</p></div> <div id="editTxt" class="refresh" contenteditable="true"> <p>This text can be by the user.</p> </div> ')) in CompilerEngine.php line 59
at CompilerEngine->get('C:\xampp\htdocs\fyproject\resources\views/layouts/website.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'name' => ' <title>Template 1</title> <link href="http://localhost/templates/css.css" rel="stylesheet" type="text/css"> <div class="logo"> <img class="images" id="image" src="#" alt="Your Logo"> </div> <div contenteditable="true" id="content" class="draggable ui-widget-content refresh ui-draggable ui-draggable-handle" style="position: relative; left: 209px; top: 139px;"><p>Change Text inside this box</p></div> <div id="editTxt" class="refresh" contenteditable="true"> <p>This text can be by the user.</p> </div> ')) in View.php line 149
I would suggest something like this:
public function postDB(Request $request) {
$newName = $request->input('name_website');
$newLat = $request->input('newCode');
$websites = new Website();
$websites->name = $newName;
$websites->html = $newLat;
$websites->save();
// Now we go to our other function
$this->website($newName);
}
public function website($newName)
{
// Return our "website" object
$website = Website::where('name', $newName)->first();
// Pass the contents of the "html" property to the view
return view('layouts/website', [
'html' => $website->html
);
}
This will give you access to the content of your "html" attribute in your blade template as $html.
Edit
If you are using your controller for an API you might consider not returning a view but instead a json response which you can listen for:
return response()->json([
'url' => $website->name,
'html' => $website->html
]);
You can then handle the content of the page or redirect using javascript

laravel blade old input

I'm learning Laravel and I have a problem returning the old inputs to the form.
ERROR:
TokenMismatchException in VerifyCsrfToken.php line 67:
ROUTES - all in the file
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('artigo');
$artigo = \App\Comentario::find(2)->artigo;
var_dump($artigo->title);
$comentarios = \App\Artigo::find(1)->comentario;
foreach($comentarios as $comentario){
var_dump($comentario->body);
}
});
Route::post('/', function(){
$rules = array(
'title'=>'required|max:10',
'body'=>'required|max:4'
);
$validator = Validator::make($_POST,$rules);
if($validator->fails())
return Redirect::to('/')->withInput()->withErrors($validator->errors());
return 'yooo';
});
});
BLADE VIEW
<!DOCTYPE html>
<html>
<body>
<form method="post" action="/">
<input type="text" name="title" placeholder="titulo" value="{{ old('title') }}">
<input type="text" name="body" placeholder="body">
<input type="submit" value="go">
</form>
</body>
</html>
Any help?
ATENTION: im not using sessions yet
Assuming you are using version 5.2 this is might be because your requests are not utilising the sessions. In Laravel 5.2 Sessions are available only if you are using the web middleware.
You should include all routes using sessions within a middleware group called web which is defined in app/Http/Kernel.php under $middlewareGroups
Route::group(['middleware' => ['web']], function () {
// Routes using sessions
});

Resources