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.
Related
'Redirect to login page instead of going to dashboard page after successful login in laravel.please help me to solve query.I have tried a lot but i cannot find solution.Any help will be appreciated.I have changes form actions but it seems same results ..........................................................................
login.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AdminLTE 3 | Log in</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
<!-- Font Awesome -->
<link rel="stylesheet" href="{{asset('plugins/fontawesome-free/css/all.min.css')}}">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Tempusdominus Bootstrap 4 -->
<link rel="stylesheet" href="{{asset('plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css')}}">
<!-- iCheck -->
<link rel="stylesheet" href="{{asset('plugins/icheck-bootstrap/icheck-bootstrap.min.css')}}">
<!-- JQVMap -->
<link rel="stylesheet" href="{{asset('plugins/jqvmap/jqvmap.min.css')}}">
<!-- Theme style -->
<link rel="stylesheet" href="{{asset('dist/css/adminlte.min.css')}}">
<!-- overlayScrollbars -->
<link rel="stylesheet" href="{{asset('plugins/overlayScrollbars/css/OverlayScrollbars.min.css')}}">
<!-- Daterange picker -->
<link rel="stylesheet" href="{{asset('plugins/daterangepicker/daterangepicker.css')}}">
<!-- summernote -->
<link rel="stylesheet" href="{{asset('plugins/summernote/summernote-bs4.min.css')}}">
<link rel="stylesheet" href="{{asset('plugins/fontawesome-free/css/all.min.css')}}">
<!-- DataTables -->
<link rel="stylesheet" href="{{asset('plugins/datatables-bs4/css/dataTables.bootstrap4.min.css')}}">
<link rel="stylesheet" href="{{asset('plugins/datatables-responsive/css/responsive.bootstrap4.min.css')}}">
<link rel="stylesheet" href="{{asset('plugins/datatables-buttons/css/buttons.bootstrap4.min.css')}}">
<!-- Theme style -->
<link rel="stylesheet" href="{{asset('dist/css/adminlte.min.css')}}">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="{{asset('plugins/jquery/jquery.min.js')}}"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<!-- jQuery UI 1.11.4 -->
<script src="{{asset('plugins/jquery-ui/jquery-ui.min.js')}}"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button)
</script>
<!-- Bootstrap 4 -->
<script src="{{asset('plugins/bootstrap/js/bootstrap.bundle.min.js')}}"></script>
<!-- ChartJS -->
<script src="{{asset('plugins/chart.js/Chart.min.js')}}"></script>
<!-- Sparkline -->
<script src="{{asset('plugins/sparklines/sparkline.js')}}"></script>
<!-- JQVMap -->
<script src="{{asset('plugins/jqvmap/jquery.vmap.min.js')}}"></script>
<script src="{{asset('plugins/jqvmap/maps/jquery.vmap.usa.js')}}"></script>
<!-- jQuery Knob Chart -->
<script src="{{asset('plugins/jquery-knob/jquery.knob.min.js')}}"></script>
<!-- daterangepicker -->
<script src="{{asset('plugins/moment/moment.min.js')}}"></script>
<script src="{{asset('plugins/daterangepicker/daterangepicker.js')}}"></script>
<!-- Tempusdominus Bootstrap 4 -->
<script src="{{asset('plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js')}}"></script>
<!-- Summernote -->
<script src="{{asset('plugins/summernote/summernote-bs4.min.js')}}"></script>
<!-- overlayScrollbars -->
<script src="{{asset('plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js')}}"></script>
<!-- AdminLTE App -->
<script src="{{asset('dist/js/adminlte.js')}}"></script>
<!-- AdminLTE for demo purposes -->
<script src="{{asset('dist/js/demo.js')}}"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="{{asset('dist/js/pages/dashboard.js')}}"></script>
<script src="{{asset('plugins/jquery/jquery.min.js')}}"></script>
<!-- Bootstrap 4 -->
<script src="{{asset('plugins/bootstrap/js/bootstrap.bundle.min.js')}}"></script>
<!-- DataTables & Plugins -->
<script src="{{asset('plugins/datatables/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('plugins/datatables-bs4/js/dataTables.bootstrap4.min.js')}}"></script>
<script src="{{asset('plugins/datatables-responsive/js/dataTables.responsive.min.js')}}"></script>
<script>
$(document).ready( function () {
$('#example1').DataTable();
} );
</script>
<script src="{{asset('plugins/datatables-responsive/js/responsive.bootstrap4.min.js')}}"></script>
<script src="plugins/datatables-buttons/js/dataTables.buttons.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
<script src="plugins/jszip/jszip.min.js"></script>
<script src="plugins/pdfmake/pdfmake.min.js"></script>
<script src="plugins/pdfmake/vfs_fonts.js"></script>
<script src="plugins/datatables-buttons/js/buttons.html5.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.print.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.colVis.min.js"></script>
</head>
</head>
<body class="hold-transition login-page">
<div class="">
<div class="row ">
<div class="login-box">
<div class="login-logo">
<b>Admin</b>Login
</div>
<!-- /.login-logo -->
<div class="">
<div class="card">
<div class="card-body login-card-body">
<p class="login-box-msg">Sign in to start your session</p>
<form action="/adminlogin" method="get">
#csrf
<div class="input-group mb-3">
<input type="email" class="form-control" placeholder="Email" name="email">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<div class="input-group mb-3">
<input type="password" class="form-control" placeholder="Password" name="password">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-8">
<div class="icheck-primary">
<input type="checkbox" id="remember">
<label for="remember">
Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-md-12 ">
<button type="submit" class="btn btn-primary btn-block">Admin Login</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center mb-3">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-primary">
<i class="fab fa-facebook mr-2"></i> Sign in using Facebook
</a>
<a href="#" class="btn btn-block btn-danger">
<i class="fab fa-google-plus mr-2"></i> Sign in using Google+
</a>
</div>
<!-- /.social-auth-links -->
<p class="mb-1">
I forgot my password
</p>
<p class="mb-0">
Register a new membership
</p>
</div>
<!-- /.login-card-body -->
</div>
</div>
</div>
<div class="login-box">
<div class="login-logo">
<b>Normal User</b> Login
</div>
<!-- /.login-logo -->
<div class="">
<div class="card">
<div class="card-body login-card-body">
<p class="login-box-msg">Sign in to start your session</p>
<form action="/loginnormaluser" method="get">
#csrf
<div class="input-group mb-3">
<input type="email" class="form-control" placeholder="Email" name="email">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<div class="input-group mb-3">
<input type="password" class="form-control" placeholder="Password" name="password">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-8">
<div class="icheck-primary">
<input type="checkbox" id="remember">
<label for="remember">
Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-4">
<button type="submit" class="btn btn-primary btn-block">Normal User</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center mb-3">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-primary">
<i class="fab fa-facebook mr-2"></i> Sign in using Facebook
</a>
<a href="#" class="btn btn-block btn-danger">
<i class="fab fa-google-plus mr-2"></i> Sign in using Google+
</a>
</div>
<!-- /.social-auth-links -->
<p class="mb-1">
I forgot my password
</p>
<p class="mb-0">
Register a new membership
</p>
</div>
<!-- /.login-card-body -->
</div>
</div>
</div>
<!-- /.login-box -->
<!-- jQuery -->
</div>
</div>
</body>
</html>
<?php
// khan controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Auth;
//use Session;
class KhanController extends Controller
{
//
function show(){
return view('khn');
}
function insert(Request $request){
$first_name = $request->input('email');
$last_name = $request->input('password');
$data=array('fname'=>$first_name,"lname"=>$last_name);
DB::table('khan')->insert($data);
echo "Record inserted successfully.<br/>";
return view('khn') ;
}
function showdata(){
$data= DB::table('khan')->get();
return view('showdata',['data'=>$data]) ;
}
function edit($id){
$request= DB::table('khan')->find($id);
return view('eidt',['request'=>$request]) ;
}
function update(Request $request){
$id=$request->id;
// return $data;
$data=array('fname'=>$request->fname,'lname'=>$request->lname);
$update = DB::table('khan') ->where('id', $id) ->limit(1) ->update($data);
//return $update;
return redirect('showdata') ;
}
function delete(Request $request){
$id=$request->id;
DB::table('khan')->delete($id);
//return $update;
return redirect('showdata') ;
}
function view($id){
$request= DB::table('khan')->find($id);
return view('view',['request'=>$request]) ;
}
function register(Request $request){
$first_name = $request->input('name');
$email = $request->input('email');
$pass = $request->input('password');
$data=array('name'=>$first_name,"email"=>$email,"password"=>$pass);
DB::table('registration')->insert($data);
echo "Record inserted successfully.<br/>";
return view('login') ;
// $request= DB::table('khan')->find($id)
}
//function login(Request $request){
// $user = DB::table('registration')
// ->where('email',$request->input('email'))
// ->where('password',$request->input('password'))
// ->first();
// if($user)
// {
// $request->Session()->put('loginid',$user->id);
// return $request;
// return redirect('dashboard');
// else{
// return back()->with('fail','Email-Address And Password Are Wrong.');
// }
// echo "hhhhhhhh";
//return redirect('dashboard') ;
//}
function adminlogin(Request $request){
$user = DB::table('registration')
->where('email',$request->input('email'))
->where('password',$request->input('password'))
->first();
if($user)
{
$request->Session()->put('loginid',$user->id);
// return $request;
//echo Session('loginid');
return redirect('dashboard');
}else
{
return back()->with('fail','Email-Address And Password Are Wrong.');
}
}
function logout(Request $request){
if(Session::has('loginid')){
Session::pull('loginid');
return redirect('login');
}
}
function normaluser(Request $request){
return view('normaluser');
}
function normaluserregister(Request $request){
$first_name = $request->input('name');
$email = $request->input('email');
$pass = $request->input('password');
$data=array('name'=>$first_name,"email"=>$email,"password"=>$pass);
DB::table('normaluser')->insert($data);
echo "Record inserted successfully.<br/>";
return view('dashboard') ;
// $request= DB::table('khan')->find($id)
}
function loginnormaluser(Request $request){
$user = DB::table('normaluser')
->where('email',$request->input('email'))
->where('password',$request->input('password'))
->first();
if($user)
{
$request->Session()->put('loginid',$user->id);
// return $request;
//echo Session('loginid');
return redirect('newuser');
}else{
return back()->with('fail','Email-Address And Password Are Wrong.');
// return back()->with('fail','Email-Address And Password Are Wrong.');
}
}
}
<?php
// web.php
use Illuminate\Support\Facades\Route;
//use App\Http\Controllers\KhanController;
use App\Http\Controllers\KhanController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::group(['middleware'=>'web'],function(){
Route::get("/addemployee",[KhanController::class,"show"]);
Route::post("/imi",[KhanController::class,"insert"]);
Route::get("/showdata",[KhanController::class,"showdata"]);
Route::get("/edit/{id}",[KhanController::class,"edit"]);
Route::get("/delete/{id}",[KhanController::class,"delete"]);
Route::get("/view/{id}",[KhanController::class,"view"]);
Route::post("/update",[KhanController::class,"update"]);
//Route::post("/update",[KhanController::class,"update"]);
Route::post("/register",[KhanController::class,"register"]);
Route::get("/login",[KhanController::class,"login"]);
Route::get("/adminlogin",[KhanController::class,"adminlogin"]);
Route::get("/logout",[KhanController::class,"logout"]);
//Route::get("/dashboard",[KhanController::class,"login"]);
Route::view('/dashboard','dashboard');
Route::get("/normaluser",[KhanController::class,"normaluser"]);
Route::post("/normaluserregister",[KhanController::class,"normaluserregister"]);
Route::get("/loginnormaluser",[KhanController::class,"loginnormaluser"]);
Route::view('/newuser','newuser');
Route::view('login','login');
});
//Route::view('/dashboard','dashboard')->middleware('isLoggedIn');
//register view
// Route::view('register','register');
// Route::view('login','login');
//Route::view("/jjj","khn");
//Route::get("/edit/{id}",[KhanController::class,"edit"]);
<?php
// middelware alreadyloggenin
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Session;
class alreadyloggenin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
//echo "hiiiii";
// if(Session()->has('loginid') && (url('login')==$request->url() || url('register')==$request->url() )){
//return back();
// }
// if(!session()->has('loginid')){
// echo"hiiiiiiiiiiiiiiiii";
// }
$path=$request->path();
if(($path=="login" || $path=="register" ) && (Session::get('loginid'))){
return redirect('/');
}
else if($path!='login' && !Session::get('loginid') && $path!='register' && !Session::get('loginid') ){
return redirect('/login');
}
return $next($request);
}
}
// group middleware
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\alreadyloggenin::class
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];```
can you put dd($user) to know which function are you using ,so we can correct the return ? for example try it with admin , because Laravel is maybe using the default login
i want to insert to the database by ajax crud i am inserting but the code dosn't work iam using jquery javascript framework
i want to insert to the database by ajax crud i am inserting but the code dosn't work iam using jquery javascript framework
i dont' know why although i am writing correctly
please help
here is my code
my blade file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</head>
<body>
<div class="container">
<div class="row" style="matgin-top:50px;">
<div class="col-md-6">
<div class="card">
<div class="card-hehader bg-primary text-white">Add new product</div>
<form id="form" action="{{route('products.store')}}" method="post" enctype="multipart/form-data">
#csrf
#method('POST')
<div class="form-group">
<label for="">product name</label>
<input type="text" name="name" class="form-control">
<span class="text-danger error-text product_name_error"></span>
</div>
<div class="form-group">
<label for="">product image</label>
<input type="file" name="image" class="form-control">
<span class="text-danger error-text product_name_error"></span>
</div>
<button type="submit" class="btn btn-info">add</button>
</form>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-header bg-primary">All Products</div>
<div class="card-body">
</div>
</div>
</div>
</div>
</div>
<script src="{{asset('js/app.js')}}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = this;
$.ajax({
url:$(form).attr('action'),
method:$(form).attr('method'),
data:new FormData(form),
processData:false,
dataType:'json',
contentType:false,
beforeSend:function(){
$(form).find('span.error-text').text('');
},
succes:function(data){
if(data.code == 0){
$.each(data.error, function(prefix,val){
$(form).find('span.'+prefix+'_error').text(val[0]);
});
}
else{
$(form)[0].reset();
alert(data.msg);
// fetchAllProducts();
}
}
})
});
});
</script>
</body>
</html>
and my controller store function
public function store(Request $request)
{
$path = 'files/';
$file = $request->file('product_image');
$file_name = time().'_'.$file->getClientOriginalName();
// $upload = $file->storeAs($path, $file_name);
$upload = $file->storeAs($path, $file_name, 'public');
if($upload){
Product::insert([
'name'=>$request->name,
'image'=>$request->image,
]);
return response()->json(['code'=>1,'msg'=>'New product has been saved successfully']);
}
}
I check out your controller portion and found something messy, would you mind trying with the below code:
if ($request->has('image')) {
$fileName = time() . '_' . $request->image->getClientOriginalExtension();
$request->image->storeAs('Files', $fileName, 'image');
$product = new Product();
$product->name = $request->name;
$product->image = $fileName;
$product->save();
return response()->json(['code'=>1,'msg'=>'New product has been saved
successfully']);
}
So i'm making this website where you can buy game consoles, so I made a crud, but I wanted that it was impossible to insert duplicates in the database, but when I create a dupicate you get a laravel error and that is not user friendly. So I wanted to show a normal message saying that you made a duplicate. so I made this.
public function store(Request $request)
{
try
{
$consoles = new consoles();
$consoles->naam = input::get('naam');
$consoles->releasedate = input::get('releasedate');
$consoles->company = input::get('company');
$consoles->price = input::get('price');
$consoles->created_at = null;
$consoles->updated_at = null;
$consoles->save();
}catch (\Exception $e)
{
return Redirect::to('console/create')
->withInput()
->withErrors(array('message' => 'duplicate'));
}
return redirect('consoles');
}
the problem is that ->withErrors(array('message' => 'duplicate')) doesn't show anything. what am I doing wrong.
EDIT
create.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' }).val();
} );
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading"> creating data</div>
<form method="POST" action="{{url('games/store/')}}">
naam: <br>
<input type="text" name="naam" required>*required<br>
releasedate: <br>
<input type="text" name="releasedate" id="datepicker" required>*required<br>
company: <br>
<input type="text" name="company" required>*required<br>
price: <br>
<input type="number" name="price" min="0" value="0" step=".01" required>*required<br>
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<input type="submit" name="create" value="create">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
When you set withErrors you don't need to pass the array, just write the error message like this ->withErrors('Duplicate');
In the view remember to include a check if there are errors
#if ($errors->count())
<div class="col-md-12">
<div class="alert alert-danger text-center">
#foreach ($errors->all() as $error)
<p>{{$error}}</p>
#endforeach
</div>
</div>
#endif
You can simply use with() to send the message to the view like
return Redirect::to('console/create')
->withInput()
->with('message', 'duplicate');
and access that in view as
#if ($message = Session::get('message'))
{{$message}}
#endif
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 got a headache with the ajax return result. Can everybody show me what's wrong with my code?
I have a main layout named "home.php", some important codes in this file as belows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="<?=base_url();?>favicon.ico">
<title>IT Ebooks - Knowledge Sharing<?php if(isset($title_page)) echo " | ".$title_page ?></title>
<link href="<?=base_url();?>css/bootstrap.min.css" rel="stylesheet">
<link href="<?=base_url();?>css/font-awesome.min.css" rel="stylesheet">
<link href="<?=base_url();?>css/custom.css" rel="stylesheet">
</head>
<body>
<div id="main-content" class="col-md-9"><!--I will load the content here based on my controller & action-->
<?php
if($this->router->fetch_class()=="ListBy"){
$this->load->view("listby");
}
elseif($this->router->fetch_class()=="Home"){
$this->load->view("index");
}
elseif($this->router->fetch_class()=="User"){
if($this->router->fetch_method()=="Signup")
$this->load->view('signup.php');
}
?>
</div>
<script src="<?=base_url();?>js/jquery-3.1.1.min.js"></script>
<script src="<?=base_url();?>js/bootstrap.min.js"></script>
<script src="<?=base_url();?>js/bootbox.js"></script>
<script src="<?=base_url();?>js/listby.js"></script><!--this file do ajax function-->
</body>
</html>
My Home controller:
<?php
class Home extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->view('home.php');
}
public function index(){
//Do nothing
}
} //class
?>
My index.php file:
<section id="latest"><!--Latest upload-->
<div class="row">
<div class="col-md-8">
<p class="text-center text-primary header">Latest Uploads</p>
</div>
<div class="col-md-4">
<div class="form-inline">
<label>Books per page : </label>
<select class="form-control" id="PageSize" name="PageSize">
<option value="12" selected>12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
</div>
</div>
<div class="col-md-12" id="ajax-content">Ajax content loaded</div>
</div>
</section>
My ajax function file "listby.js":
$(document).ready(function(){
$.ajax({
type:"POST",
url:"AjaxProcessing1/loadByCategory",
data:"PageNo="+1+"&PageSize="+12,
dataType: "text",
success: function(response){
alert(response);//I used alert to show the problem
//$('#ajax-content').html(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
})
My AjaxProcessing1 controller file:
<?php
class AjaxProcessing1 extends CI_Controller {
public function loadByCategory(){
$PageNo = $this->input->post('PageNo');
$PageSize = $this->input->post('PageSize');
$this->load->model('model_book');
$data['books'] = $this->model_book->get_latest_book($PageSize,$PageNo);
$this->load->view('ajax_result1',$data);
}
} //class
?>
My ajax_result1 page:
<?php
if(isset($books)){
?>
<div class="row">
<?php foreach($books as $book): ?>
<div class="col-md-3 col-sm-6">
<a href="<?=base_url();?>/ListBy/detail/<?=$book->id?>/<?=$book->slug?>">
<img class="anhsach" src="<?=base_url();?>img/cover/<?=$book->image;?>" alt="<?=$book->slug;?>"/>
</a>
</div>
<?php endforeach; ?>
</div>
<?php
}
?>
So, until here. Everything's OK when I'm in home page, the ajax function return the ajax_result1 as expected
[Pic1 - Load as expected][1]
But, when I'm in ListBy controller, the return of the ajax function is the main layout?
My ListBy Controller:
<?php
class ListBy extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('model_book');
}
public function index(){
//Nothing to do here
}
public function ListByCategory($category_id){
$data['title_page'] = "List by category";
$data['num_books'] = $this->model_book->number_of_books_bycategory($category_id);
$data['category_id'] = $category_id;
$this->load->view('home.php',$data);
}
} //class
?>
My listby.php file:
<?php
echo "<h3 class='text-center text-success'>".$num_books." book(s) found</h3>"
?>
<section id="cate">
<div class="row">
<div class="col-md-8">
<p class="text-center text-primary header">Select your books view per page</p>
</div>
<div class="col-md-4">
<div class="form-inline">
<label>Books per page : </label>
<select class="form-control" id="PageSize" name="PageSize">
<option value="12" selected>12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
</div>
</div>
<div class="col-md-12" id="ajax-content">Ajax content loaded</div>
</div>
</section>
<input type="hidden" id="total_record" value="<?=$num_books?>"/>
<input type="text" id="category_id" value="<?=$category_id?>"/>
<div class="row text-center">
<ul class="pagination">
</ul>
</div>
And the result I got when I'm in this controller (return the main layout):
[Not as expected][2]
So, what's going on with my code. Thanks so much for any help or suggestion in advanced.
[1]: https://i.stack.imgur.com/PeADW.png
[2]: https://i.stack.imgur.com/PAiO1.png
My project link in case you need: http://www.mediafire.com/file/ed1e31od1fk5vkg/itebooks-23Oct16.zip
Home extends CI_Controller { public function __construct() { parent::__construct(); //$this->load->view('home.php');
// THE PROBLEM is : you can't load the main/home layout in Home controller construct function }