How to Fix CodeIgniter Base_url and css link - codeigniter

I'm New to Code-igniter and I'm trying to create login form with session.I'm stuck at a point where username and password field is empty than its not showing CSS.
i research a bit more about it and found that when i first open my project_login form at that moment css link looks likes this localhost/ci_project/assets/bower_components/bootstrap/dist/css/mystyle.css
after click on login button when username and password are empty at that moment css link look like this (Auth is my controller where i written login function)
localhost/ci_project/Auth/assets/bower_components/bootstrap/dist/css/mystyle.css
login.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AdminLTE 2 | Log in</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.7 -->
<link rel="stylesheet" href="<?php base_url()?>assets/bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="<?php base_url()?>assets/bower_components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="<?php base_url()?>assets/bower_components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="<?php base_url()?>assets/dist/css/AdminLTE.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="<?php base_url()?>assets/plugins/iCheck/square/blue.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Google Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<b>VEMS</b> ER
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<h4><p class="login-box-msg">VEMS ENGINEERING MULTI SERVICE</p></h4>
<form action="<?php echo base_url()?>Auth/login_validation" method="post">
<div class="form-group has-feedback">
<input type="username" name="username" class="form-control" placeholder="Email">
<span class="text-danger"><?php echo form_error('username'); ?></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" class="form-control" placeholder="Password">
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
<div class="row">
<?php echo $this->session->flashdata("error"); ?>
<div class="col-xs-8">
<div class="checkbox icheck">
<label>
<input type="checkbox" class="login-check" checked="checked"> Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
<!-- <div class="social-auth-links text-center">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-social btn-facebook btn-flat"><i class="fa fa-facebook"></i> Sign in using
Facebook</a>
<a href="#" class="btn btn-block btn-social btn-google btn-flat"> Sign in using
Google+</a>
</div> -->
<!-- /.social-auth-links -->
I forgot my password<br>
<!-- Register a new membership -->
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<!-- jQuery 3 -->
<script src="<?php base_url()?>assets/bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="<?php base_url()?>assets/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="<?php base_url()?>assets/plugins/iCheck/icheck.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' /* optional */
});
});
</script>
</body>
</html>
Auth.php (Controller)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('Auth_model');
}
public function index(){
$this->load->view('pages/login');
}
public function login_validation(){
$this->load->library('form_validation');
$data['title'] = "Login";
$this->form_validation->set_rules('username', 'Username', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run()){
//get value from login form by post method
$username = $this->input->post('username'); //email
$username = $this->input->post('password'); //password
//model function
$this->load->model('Auth_model');
if($this->Auth_model->can_login($username, $password)){
$session_data = array(
'username' => $username
);
$this->session->set_userdata($session_data);
redirect(base_url(). 'Auth/enter');
}
else{
$this->session->set_flashdata('error', 'Invalid Username Or password');
redirect(base_url(). 'Auth');
}
}
else{
$this->load->view('pages/login');
}
}
public function enter(){
if($this->session->userdata('username') != ''){
echo "<h2>Welcome".$this->session->userdata('username')."</h2>";
echo '<a href="'.base_url().'Auth/logout>LOGOUT</a>';
}
else{
redirect(base_url(). 'Auth');
}
}
public function logout(){
$this->session->session_destroy();
redirect('pages/login');
}
}
$config['base_url'] = 'http://localhost/ci_project/'
;

Related

Redirect to login page instead of going to dashboard page after successful login in laravel.please help me to solve query

'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

laravel using withErrors in a try catch

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

Response is empty string

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.

Insert data in codeigniter

I am trying to make an insert function in codeigniter using php and bootstrap. But when i press add button, nothing happens, my new data are not added in my db table. Please Help me.
My code:
department.php
<?php
/*
* File Name: employee.php
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class department extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the employee model
$this->load->model('department_model');
}
//index function
function index()
{
//fetch data from department and designation tables
// $data['department'] = $this->department_model->get_department();
//set validation rules
$this->form_validation->set_rules('id', 'Employee ID', 'trim|required|numeric');
$this->form_validation->set_rules('department_emer', 'Department Name', 'trim|required|callback_alpha_only_space');
$this->form_validation->set_rules('pershkrimi', 'Description', 'trim|required');
//$this->form_validation->set_rules('id_departament', 'Department', 'callback_combo_check');
if ($this->form_validation->run() == FALSE)
{
//fail validation
$this->load->view('department_view');
}
else
{
//pass validation
$data = array(
//'id' => $this->input->post('id'),
'department_emer' => $this->input->post('department_emer'),
'pershkrimi' => $this->input->post('pershkrimi'),
);
//insert the form data into database
$this->db->insert('department', $data);
//display success message
$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Department details added to Database!!!</div>');
redirect('department/index');
}
}
//custom validation function to accept only alpha and space input
function alpha_only_space($str)
{
if (!preg_match("/^([-a-z ])+$/i", $str))
{
$this->form_validation->set_message('alpha_only_space', 'The %s field must contain only alphabets or spaces');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>
department_model.php
<?php
/*
* File Name: employee_model.php
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class department_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//get department table to populate the department name dropdown
}
?>
department_view.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeIgniter | Insert Employee Details into MySQL Database</title>
<!--link the bootstrap css file-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- link jquery ui css-->
<link href="<?php echo base_url('assets/jquery-ui-1.11.2/jquery-ui.min.css'); ?>" rel="stylesheet" type="text/css" />
<!--include jquery library-->
<script src="<?php echo base_url('assets/js/jquery-1.10.2.js'); ?>"></script>
<!--load jquery ui js file-->
<script src="<?php echo base_url('assets/jquery-ui-1.11.2/jquery-ui.min.js'); ?>"></script>
<style type="text/css">
.colbox {
margin-left: 0px;
margin-right: 0px;
}
</style>
<script type="text/javascript">
//load datepicker control onfocus
$(function() {
$("#hireddate").datepicker();
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-offset-3 col-lg-6 col-sm-6 well">
<legend>Add Department Details</legend>
<?php
$attributes = array("class" => "form-horizontal", "id" => "departmentform", "name" => "departmentform");
echo form_open("department/index", $attributes);?>
<fieldset>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="department_emer" class="control-label">Name</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="department_emer" name="department_emer" placeholder="department_emer" type="text" class="form-control" value="<?php echo set_value('department_emer'); ?>" />
<span class="text-danger"><?php echo form_error('department_emer'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="mbiemer" class="control-label">Description</label>
</div>
<div class="col-lg-8 col-sm-8">
<textarea class="form-control" rows="5" id="pershkrimi" name="pershkrimi" placeholder="pershkrimi" value="<?php echo set_value('pershkrimi'); ?>" ></textarea>
<span class="text-danger"><?php echo form_error('pershkrimi'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-md-8 text-left">
<input id="btn_update" name="btn_update" type="submit" class="btn btn-primary" value="Add" />
<input id="btn_cancel" name="btn_cancel" type="reset" class="btn btn-danger" value="Cancel" />
</div>
</div>
</fieldset>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
</div>
</div>
</div>
</body>
</html>
In department.php replace
$this->db->insert('department', $data);
with
$this->load->model('department_model.php');
$this->department_model.php->insert($data);
And in department_model.php create a function insert
public function insert($data) {
if($this->db->insert('table_name', $data)) {
//Success message or anything which you want
}
}
This will solve your problem.
Let me know if you require any further help!!!
Please load the CI database library before inserting the data, or you can load it in your constructor method.
$this->load->library('database');
Hopefully it can help you.

(CodeIgniter) Ajax return the main layout instead of the needed view

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 }

Resources