I am working on this project from a tutorial but i get this TokenMismatchException in VerifyCsrfToken.php line 67 Error when i try to add new category to the view i tried everything on the internet as :-
adding
<input type="hidden" name="_token" value="{{ Session::token() }}">
or adding
<meta name="csrf-token" content="{{ csrf_token() }}" />
to my code also removed th CSRF middileware nothing worked
here is the original code
The View
#extends('layouts.admin-master')
#section('styles')
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="{{ URL::secure('src/css/categories.css') }}" type="text/css" />
#endsection
#section('content')
<div class="container">
<section id="category-admin">
<form action="" method="post">
<div class="category-input">
<label for="name">Category Name</label>
<input type="text" name="name" id="name">
<button type="submit" class="btn">Create Category</button>
</div>
</form>
</section>
<section class="list">
#foreach($categories as $category)
<article>
<div class="category-info" data-id="{{ $category->id }}">
<h3>{{ $category->name }}</h3>
</div>
<div class="edit">
<nav>
<ul>
<li class="category-edit"><input type="text"></li>
<li>Edit</li>
<li>Delete</li>
</ul>
</nav>
</div>
</article>
#endforeach
</section>
#if($categories->lastPage() > 1)
<section class="pagination">
#if($categories->currentPage() !== 1)
<i class="fa fa-caret-left"></i>
#endif
#if($categories->currentPage() !== $categories->lastPage())
<i class="fa fa-caret-right"></i>
#endif
</section>
#endif
</div>
#endsection
#section('scripts')
<script type="text/javascript">
var token = "{{ Session::token() }}";
</script>
<script type="text/javascript" src="{{ URL::secure('src/js/categories.js') }}"></script>
#endsection
Here is the Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
use Illuminate\Support\Facades\Response;
class CategoryController extends Controller{
public function getCategoryIndex()
{
$categories = Category::orderBy('created_at', 'desc')->paginate(5);
return view('admin.blog.categories',['categories' => $categories]);
}
public function postCreateCategory(Request $request)
{
$this->validate($request, [
'name' => 'required|unique:categories'
]);
$category = new Category();
$category->name = $request['name'];
if($category->save()){
return Response::json(['message' => 'Category Created Successfully!'], 200);
}
return Response::json(['message' => 'Error During Creation'], 404);
}
}
thats the Js file
var docReady = setInterval(function(){
if (document.readyState !== "complete"){
return;
}
clearInterval(docReady);
document.getElementsByClassName('btn')[0].addEventListener('click',createNewCategory);
var _token = document.getElementsByName('_token')[0].value;
//and append the value to form data
formdata.append("_token", _token);
},100);
function createNewCategory(event) {
event.preventDefault();
var name = event.target.previousElementSibling.value;
if(name.length === 0) {
alert("Please A Valid Category Name!");
return;
}
ajax("POST","/admin/blog/category/create", "name=" + name, newCategoryCreated, [name]);
}
function newCategoryCreated(params, success, responseObj){
location.reload();
}
function ajax(method, url, params, callback, callbackParams){
var http;
if (window.XMLHttpRequest){
http = new XMLHttpRequest();
}else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
http.onreadystatechange = function(){
if (http.readyState == XMLHttpRequest.DONE){
if (http.status == 200){
var obj = JSON.parse(http.responseText);
callback(callbackParams, true, obj);
}else if(http.status ==400){
alert("Category Could Not Be Saved. Please Try Again");
callback(callbackParams, false);
}else {
var obj = JSON.parse(http.responseText);
if (obj.message){
alert(obj.message);
}else {
alert("Please Check The Name");
}
}
}
}
http.open(method, baseUrl + url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http.send(params + "&_token=" + token);
}
and that`s the routes
Route::post('/blog/category/create',[
'uses' => 'CategoryController#postCreateCategory',
'as' => 'admin.blog.category.create'
]);
Route::get('/blog/categories',[
'uses' => 'CategoryController#getCategoryIndex',
'as' => 'admin.blog.categories'
]);
PLEASE Help me with this Error I have been stuck with it for three days Now
Set your post_max_size = 100 mb or as much you require.
Add <input type="hidden" name="_token" value="{{ csrf_token() }}"> before every input field like
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="last_name" id="last_name" placeholder="Last Name" class="form-control">
Related
In my Laravel-5.8, I am using the index as the search page:
public function index()
{
$search = '';
if (request('search'))
{
$search = request('search');
return redirect()->route('client', [$search]);
}
return view('index', ['search' => $search]);
}
public function client($clientid)
{
$myparam = $clientid;
$client = new Client();
$res = $client->request('GET','https://example/{$myparam}', [
'query' => ['key' => 'jkkffd091']
])->getBody();
$geoLocation = json_decode($res->getContents(), true);
return view('client', [
'geoLocation' => $geoLocation
]);
}
Here is my index blade:
<form method="GET" action="{{ route('index', ['search' => $search]) }}">
<div class="field">
<label class="label blog-sidebar-label" for="search">
<input class="search-field" type="search" name="search" id="search" placeholder="client id..." value="{{ $search }}">
</label>
</div>
</form>
I have this route:
Route::get('/', [HomeController::class, 'index'])->name('index');
Route::get('client/{search}', [HomeController::class, 'client'])->name('client');
What I want to achieve is that when the search button for index is submitted with the clientid in the text input field, it should take the clientid as parameter and pass it to client controller. Also redirect to client blade.Then when nothing is in the text input field, it should indicate.
But it is not redirecting. How do I achieve this?
Thanks
Probably you want to submit without a submit button. Then you can submit with JS :
<form id="submitForm" method="GET" action="{{ route('index', ['search' => $search]) }}">
<div class="field">
<label class="label blog-sidebar-label" for="search">
<input class="search-field" type="search" name="search" id="search" placeholder="client id..." value="{{ $search }}">
</label>
</div>
</form>
<!-- JS code below -->
<script>
document.getElementById("search").onchange = function() {myFunction()};
function myFunction() {
document.getElementById("submitForm").submit();
}
</script>
* While posting data in database in codeigniter first time my data is post to database , but when second time i am try to post data in database then it give me 403 ERROR .First Time code is work ,when second time i am post it give me 403 error data is not post or save in my database. *
View Page Code :
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h2>Register</h2>
<!-- <form id="saveEmpForm"> -->
<?php
$attributes = array('id' => 'saveEmpForm');
echo form_open('register/insert', $attributes);
?>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter password" name="pswd">
</div>
<button type="submit" class="btn btn-primary" id="btn_add">Submit</button>
</form>
</div>
<div class="col-md-3"></div>
</div>
</div>
<script type="text/javascript">
var csrf_token = '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
<script type="text/javascript">
$('#saveEmpForm').submit('click',function(){
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>register/insert",
dataType : "JSON",
data : {name:name, email:email, password:password, csrf_test_name: csrf_token},
success: function(response){
$('#name').val("");
$('#email').val("");
$('#password').val("");
alert('Success');
}
});
return false;
});
</script>
</body>
</html>
Controller code:
defined('BASEPATH') OR exit('No direct script access allowed');
class Register extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('register_model');
}
public function index()
{
$this->load->view('register_view');
}
public function insert(){
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$result=$this->register_model->insert_data($data);
echo json_encode($data);
}
}
Model Code :
class Register_model extends CI_Model{
public function insert_data($data)
{
$this->db->insert('emp',$data);
return $this->db->insert_id();
}
}
?>```
In my laravel project I am using resource controller for update. but it is not working. I tried but it failed.
my blade
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<title>{{ config('app.name') }}</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
<link href="{{ asset('css/style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>{{ config('app.name') }}</h1>
<form class="dis-none" id="FormAjax">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="address">Address</label>
<textarea class="form-control" rows="3" id="address"></textarea>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="country">Country</label>
<input type="text" class="form-control" id="country" />
</div>
</div>
</div>
<button type="submit" id="SaveAjax" class="btn btn-success">Save Form</button>
<button type="button" id="cancel" class="btn btn-danger">Cancel</button>
</form>
<div id="ShowAjax" class="row">
<button type="button" id="AddForm" class="btn btn-success">Add Form</button>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Country</th>
<th>Action</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#AddForm").click(function () {
$("#FormAjax").fadeIn();
$("#ShowAjax").hide();
$('#UpdateForm').text('Save Form');
});
$("#SaveAjax").click(function () {
$("#FormAjax").hide();
$("#ShowAjax").fadeIn();
});
$(document).on('click', '#cancel', function () {
$('#name').val('');
$('#country').val('');
$('#address').val('');
});
$(document).on('click', '#edit', function () {
$("#FormAjax").fadeIn();
$("#ShowAjax").hide();
name = $(this).parent().parent().find('#ename').text();
address = $(this).parent().parent().find('#eaddress').text();
country = $(this).parent().parent().find('#ecountry').text();
$('#name').val(name);
$('#address').val(address);
$('#country').val(country);
$('#SaveAjax').text('Edit');
$('#SaveAjax').prop('id', 'UpdateForm');
$('#UpdateForm').attr('data-id', $(this).data('id'));
});
$(document).on('click', '#UpdateForm', function () {
name = $('#name').val();
country = $('#country').val();
address = $('#address').val();
url = "peoples";
id = $(this).data('id');
editUrl = url + '/' + id + '/edit';
$.get( {{ route('editUrl') }}, {name:name, country:country, address:address, id:id}, function (data) {
console.log('success');
});
});
});
</script>
</body>
</html>
route/web.php
Route::resource('peoples', 'PeopleController');
PeopleController.php
public function edit(People $people)
{
if($request->ajax()) {
$request->validate([
'name' => 'required',
'address' => 'required',
'country' => 'required',
]);
$people = People::find($request->id);
$people->name = $request->name;
$people->address = $request->address;
$people->country = $request->country;
$people->save();
return response()->json();
}
}
When I try type in browser http://localhost:8000/peoples I see this error.
Route [editUrl] not defined. (View: C:\xampp\htdocs\Tutorials
Laravel\Ajax\resources\views\peoples.blade.php)
You cannot use the route() helper here as you have not named your routes. Instead, try using the url() helper to generate the URL.
url(id . '/edit')
But, here I see another problem as the id will come in dynamically when the JS executes by which time the Laravel helper would have already executed. So, I would suggest the following approach:
url = {{ base_url() }} + '*apiPrefix*' + '/peoples/' + id + '/edit'
I am creating a simple upload files web application using laravel in the backend and I am trying to print the response that is sent from the server -which is supposed to be informed about the uploaded file- in the console, but it shows me an empty string.
here is my controller:
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Storage;
class UploadsController extends Controller
{
public function getUpload(){
return view('upload');
}
public function postUpload(request $request){
// //
$result = print_r($request,true);
$time = Carbon::now();
if ($request->hasFile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$fileName = $file->getClientOriginalName();
//$upload_success = $file->storeAs('public',$file->getClientOriginalName());
$upload_success=Storage::disk('local')->put($fileName, fopen($file, 'r+'));
if ($upload_success) {
return response()->json(['request'=>$request->getContent()], 200);
}
else {
return response()->json('error', 400);
}
}
return response()->json('no file to upload', 400);
}
}
and my view where I am printing the response:
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="/js/xhr2.js"></script>
<script type="text/javascript">
$(function(){
$('#upload').on("click",function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#file").upload("/upload",function(data){
$('#spin').css('display','none');
$('#msg').css('display','block');
console.log(data);
},function(prog,val){
$('#prog').html(val+"%");
$('#prog').width(''+val+'%');
if(val == 100){
$("#prog").html('Completed');
$('#spin').css('display','block');
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div style="margin-top:5px"><input type="file" id="file" name="file" ></div>
<div style="margin-top:5px;margin-bottom: 5px">
<input type="button" id="upload" value="upload" class="btn btn-success btn-lg">
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuemin="0" aria-valuemax="100" id="prog"></div>
</div>
<div id="spin" style="display:none">
<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
</div>
<div class="alert alert-success" style="display: none" id="msg" style="text-align: center">
<strong>Success!</strong>You have uploaded the file successfully
</div>
</div>
</body>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>
and here is a sample of what I get:
I would know if I am doing it wrong, and if not, why it is empty,
Thanks.
You're not using a form element.
Wrap your inputs in a basic html form:
<form method="POST" action="#">
#csrf
...
</form>
Then use jquery to post the form to the laravel route.
I just started using the dropzone plugin and i'm using laravel in my project. I want to know how to get the files uploaded so i can store them in my database. this is my view :
<form action="{{route('realisation.storeimg')}}" method="POST" files="true" enctype="multipart/form-data"
data-toggle="validator" role="form" class="dropzone" id="my-awesome-dropzone">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="table table-striped" class="files" id="previews">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail/></span>
</div>
<div>
<p class="name" data-dz-name></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div>
<p class="size" data-dz-size></p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"
aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
<div>
<button class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start</span>
</button>
<button data-dz-remove class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel</span>
</button>
<button data-dz-remove class="btn btn-danger delete">
<i class="glyphicon glyphicon-trash"></i>
<span>Delete</span>
</button>
</div>
</div>
</div>
<input type="hidden" name="realisation_id" value="{{$realisation->id}}">
</form>
my route for the upload:
Route::post('/storeimg',[
'as'=>'realisation.storeimg',
'uses'=>'RealisationController#storeimg'
]);
my controller:
public function storeimg (Request $request)
{
$realisation = Realisation::where('id','realisation_id')->first();
if($request->file('image')) {
foreach ($request->file('image') as $image) {
$realisation_image = Realisationimg::where('realisation_id','realisation_id')->first();
File::delete($realisation_image->image);
File::delete($realisation_image->image_thumb);
$extension = $image->getClientOriginalExtension();
$name = substr($image->getClientOriginalName(), 0, -4);
list($width, $height) = getimagesize($image);
$imgname = str_slug($name, '_');
$filename = $imgname.'.'.$extension;
if(file_exists('uploads/realisationimg/cover/' . $filename)){
do {
$newname = $imgname.'_'.str_random(3) . '.' . $extension;
}
while(file_exists('uploads/realisationimg/cover/' . $newname));
$filename = $newname;
}
$path = 'uploads/realisationimg/cover/'.$filename;
$path_thumb = 'uploads/realisationimg/thumb/'.$filename;
$save = Image::make($image->getRealPath())->resize(1600, null, function ($constraint){
$constraint->aspectRatio();
})->save($path);
$save = Image::make($image->getRealPath())->resize(1600, null, function ($constraint){
$constraint->aspectRatio();
})->save($path_thumb);
$realisation_image->image = $path;
$realisation_image->image_thumb = $path_thumb;
$realisation_image->realisation_id = $id;
$realisation_image->save();
}
}
Session::flash('ajouter','ok');
return redirect(route('realisation.edit',['id'=>$request->get('realisation_id')]));
}
in the dropzone.js file i changed the default options to the following:
uploadMultiple: true,
paramName: "image",
when i submit the dropzone form nothing gets executed (no files are stored and nothing in my database). can someone point to me my mistake? thanks.
Here is s sample code that might help.
Route:
Route::post('/storeimg', 'GalleryController#storeimg')
->name('realisation.storeimg');
Controller:
public function storeimg(Request $request)
{
$path = $request->file('file')->store('public/photo');
if (!$path)
return url('storage');
$dirs = explode('/', $path);
if ($dirs[0] === 'public')
$dirs[0] = 'storage';
$data['image'] = url(implode('/', $dirs));
Photo::create($data);
session()->flash('success', 'Photos uploaded successfully');
return response()->json(['success'=>$data['image']]);
}
View: Just open file to send files to controller.
{!! Form::open([ 'route' => [ 'realisation.storeimg'], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'image-upload' ]) !!}
{!! Form::close() !!}
<link rel="stylesheet" href="../dropzone.min.css">
<script src="../dropzone.min.js"></script>
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize : 1,
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
//Remove Photo
$("body").on("click",".remove-item",function(){
var id = $(this).parent("td").data('id');
var c_obj = $(this).parents("tr");
console.log(id);
$.ajax({
dataType: 'json',
type:'delete',
url: url + '/' + id,
}).done(function(data){
c_obj.remove();
});
});
</script>
This is result in a dropzone box where you can add multiple photos at a time