Laravel Tutorials
- What is laravel
- Laravel Installation
- Directory Structure
- htaccess
- Remove public from url
- Artisan Command
- Laravel Configuration
- Routing Configuration
- Namespaces
- Request
- Response
- Controller
- Model
- User Authentication
- Multi User Authentication
- Database Seeding
- Database
- Database Query
- ORM
- One-to-One Relationship
- One-to-Many Relationship
- Many to Many Eloquent Relationship
- Has One Through
- Has Many Through
- Querying Relations
- Middleware
- Laravel Views
- Blade Views
- Print data on view page
- Get Site URL
- Get URL Segment
- Get images from Storage folder
- Clear cache
- Form Class not found
- Flash Message in laravel
- Redirections
- path
- CRUD Projerct
- CRUD in Laravel
- CRUD progran
- Laravel Validation
- Jquery Validation
- Cookie
- Session
- Email Send in laravel
- File uploading
- CSRF Protection
- Helper in Laravel
- Helper Functions
- Guzzle Http Client
- Paypal Payment Gatway Integration
- Cron Job in laravel
- Flash message
- path
- Errors Handling
- Date Format
- Date Format Validation
- Display Image on View Page
- Update User Status using toggle button
- Delete Multiple Records using Checkbox in Laravel?
- Confirmation Before Delete Record
- Delete image from storage
- Remove/Trim Empty & Whitespace From Input Requests
- Block IP Addresses from Accessing Website
- How to Disable New User Registration in Laravel
- Redirect HTTP To HTTPS Using Laravel Middleware
- CKEditor
- slug generate unique
- Prevent Browser's Back Button After Logout
- Datatable dunamically
- encrypt & Decript
- Download File
- Rest API
- Shopping Cart
- Shopping Cart Example
- Dynamic Category-Subcategory Menu
- Ajax Search
- Interview Question
- laravel Tutorilal link
- laravel Tutorilal
Important Links
CRUD in Laravel.
Login Controller
File name : LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Response;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (\Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
$request->session()->regenerate();
//return response(['success' => true], Response::HTTP_OK);
return redirect('/home')->with('loginmsg', 'Login Successfull');
}
else
{
//return redirect()->route('/admin')->with('error','Email-Address And Password Are Wrong.');
return back()->with('error', 'Sorry! Your Email and Password are Invalid.');
}
}
/*public function redirectTo()
{
// do whatever you want
return '/dashboard';
}*/
public function logout(Request $request)
{
Auth::logout();
$request->session()->flush(); // it remove the all session data
//$request->session()->forget('username'); // it remove the single session data
return redirect('/admin');
/*
// Forget a single key...
$request->session()->forget('key');
// Forget multiple keys...
$request->session()->forget(['key1', 'key2']);
*/
}
}
LoginController Controller
File name : LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Response;
use Session;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
//protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
/* ################ Multiple Authentication ###################### */
$input = $request->all();
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
{
if (auth()->user()->is_admin == 1) {
return redirect()->route('admin.home');
}
elseif(auth()->user()->is_admin == 2){
return redirect()->route('home');
}
}else{
return redirect()->route('login')
->with('error','Email-Address And Password Are Wrong.');
}
/* ################ End Multiple Authentication ####################### */
/* ################ Single Authentication #######################
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (\Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
$request->session()->regenerate();
//return response(['success' => true], Response::HTTP_OK);
return redirect('/home')->with('loginmsg', 'Login Successfull');
}
else
{
//return redirect()->route('/admin')->with('error','Email-Address And Password Are Wrong.');
return back()->with('error', 'Sorry! Your Email and Password are Invalid.');
}
################ End Single Authentication ####################### */
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->flush(); // it remove the all session data
Session::flush(); // it remove the all session data
$request->session()->forget('email'); // it remove the single session data
return redirect('/login');
/*Auth::logout();
header("cache-Control: no-store, no-cache, must-revalidate");
header("cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
Session::flush();
$request->session()->regenerate();
Session::flash('succ_message', 'Logged out Successfully');
return redirect('/admin');
*/
}
public function signout_user(Request $request)
{
Auth::logout();
$request->session()->flush(); // it remove the all session data
Session::flush(); // it remove the all session data
$request->session()->forget('mobile'); // it remove the single session data
return redirect('/');
}
public function user_login(Request $request)
{
/* $input = $request->all();
$this->validate($request, [
'emailid' => 'required|email',
'password' => 'required',
]);
if(auth()->attempt(array('email' => $input['emailid'], 'password' => $input['password'])))
{
if (auth()->user()->is_admin == 0) {
return redirect('/');
}
}
*/
$validator = \Validator::make($request->all(), [
'mobile' => 'required|digits:10',
'password' => 'required|alphaNum|max:20|min:4',
//'phone' => 'required|digits:10', // work fine
//'phone' => 'required|numeric|digits:10|starts_with: 6,7,8,9'
]);
if ($validator->fails())
{
//return response()->json(['errors'=>$validator->errors()->all()]);
return response()->json(['errors'=>$validator->errors()]);
}
$input = $request->all();
if(auth()->attempt(array('mobile' => $input['mobile'], 'password' => $input['password'])))
{
if (auth()->user()->is_admin == 0) {
return response()->json(array('loginmsg'=> "Thankyou for User Login!"));
}
}else{
return response()->json(array('errormsg'=> "Sorry Your Credential Wrong!"));
}
}
public function loginuser(Request $request)
{
$input = $request->all();
$this->validate($request, [
'mobile' => 'required|digits:10',
'password' => 'required|alphaNum|max:20|min:4',
]);
if(auth()->attempt(array('mobile' => $input['mobile'], 'password' => $input['password'])))
{
if(auth()->user()->is_admin == 0) {
return redirect()->route('checkout-cart');
}
}
else{
return redirect()->route('checkout-cart')->with('error','Mobile No And Password Are Wrong.');
}
}
}
Register Controller
File name : RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\User;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
protected function register(Request $request)
{
$validator = \Validator::make($request->all(), [
//'name' => 'required|alpha_spaces',
'fname' => 'regex:/([A-Za-z])+/',
'lname' => 'regex:/([A-Za-z])+/',
'email' => 'required|email',
'password' => 'required|alphaNum|max:20|min:4',
//'confpassword' => 'required|same:password|min:6',
'mobile' => 'required|digits:10',
//'phone' => 'required|numeric|digits:10|starts_with: 6,7,8,9'
//'phone' => 'required|numeric|between:9,11',
//'phone' => 'required|min:10|numeric',
//'phone' => 'required|regex:/(01)[0-9]{9}/',
//'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10'
]);
if ($validator->fails())
{
//return response()->json(['errors'=>$validator->errors()->all()]);
return response()->json(['errors'=>$validator->errors()]);
}
$data = $request->all();
$user_array = [
'first_name' => $data['fname'],
'last_name' => $data['lname'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'mobile' => $data['mobile'],
];
User::create($user_array);
//auth()->login($user);
//return redirect()->to('/');
return response()->json(array('registermsg'=> "Thankyou for User Registration!"));
}
}
Controller
File name : AboutusController.php
<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Aboutus;
use DB;
//use Illuminate\Support\Facades\Validator;
use Validator;
class AboutusController extends Controller
{
public function index()
{
return view('admin.aboutus');
}
public function add_aboutus(Request $request)
{
$data = request()->all();
//$data = $request::all();
//$title = $request->get('title');
$rule = array(
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif',
'content' => 'required',
'status' => 'required',
);
$this->validate($request,$rule);
$image = $request->file('image');
//$image = $request->image;
$image_name = uniqid() . '_' . time(). '.' . $image->getClientOriginalExtension();
/* $aboutus['datainfo'] = array(
'title' => $data['title'],
'image'=> $image_name,
'content'=> $data['content']
);
*/
$aboutus = new Aboutus([
'title' => $data['title'],
'image'=> $image_name,
'content'=> $data['content'],
'status'=> $data['status'],
]);
$aboutus->save();
//$uploaded_path = public_path('gallery');
$uploaded_path = storage_path('app\public\aboutus');
if (! is_dir($uploaded_path))
{
mkdir($uploaded_path);
chmod($uploaded_path, 0777);
}
$image->move($uploaded_path,$image_name);
return redirect()->back()->with('msg', 'Your Data is successfully Submitted!');
}
public function add_aboutus_model(Request $request)
{
//$image = \Input::file('image');
//$title = \Input::get('title');
//$content = \Input::get('content');
$validator = \Validator::make($request->all(), [
'title' => 'required',
'content' => 'required',
]);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
$data = request()->all();
$aboutus = new Aboutus([
'title' => $data['title'],
//'image'=> $image_name,
'content'=> $data['content']
]);
$aboutus->save();
return response()->json(array('success'=> "Your data is successfully Submitted!"));
}
public function show(Request $request)
{
$aboutus = Aboutus::get();
return view('admin.aboutus-show',compact('aboutus'));
}
public function delete_aboutus(Request $request)
{
$id = $request->input('id');
//$id = $request->get('id');
//$gallery = Gallery_detail::find($id)->delete($id);
$aboutus = Aboutus::find($id);
$image_name = $aboutus->image;
if($aboutus->delete())
{
//return response()->json(['success' => '1','successmsg' => "Your Data Successfully Deleted" ]);
/*if(\Storage::exists('app/public/gallery/'.$image_name))
{
\Storage::delete('app/public/gallery/'.$image_name);
}*/
if(file_exists(Storage_path('app/public/aboutus/'.$image_name))){
unlink(Storage_path('app/public/aboutus/'.$image_name));
}
$msg = "Your Data Successfully Deleted";
return response()->json(array('successmsg'=> $msg, 'status'=>"success"), 200);
}
else{
return response()->json(['error' => '0','errormsg' => "Sorry Data Not Deleted" ]);
}
//return response()->json(['success' => '1','successmessage' => "Your Data Successfully Deleted" ]);
exit;
}
public function editaboutus($id)
{
//$id = $request->get('id');
$aboutusinfo = Aboutus::find($id);
//$aboutusinfo = Aboutus::findOrFail($id);
return response()->json(['data' => $aboutusinfo]);
exit;
}
public function update_aboutus(Request $request)
{
$id = $request->get('hidden_id');
$data = request()->all();
$image = $request->file('image');
if($image != '')
{
$image_name = uniqid() . '_' . time(). '.' . $image->getClientOriginalExtension();
$aboutus = array(
'title' => $data['title'],
'image'=> $image_name,
'content'=> $data['content']);
//$aboutus->save();
Aboutus::whereId($id)->update($aboutus);
//$uploaded_path = public_path('gallery');
$uploaded_path = storage_path('app\public\aboutus');
if (! is_dir($uploaded_path))
{
mkdir($uploaded_path);
chmod($uploaded_path, 0777);
}
$image->move($uploaded_path,$image_name);
}
else
{
$oldimagename = $request->get('oldimagename');
$aboutus = array(
'title' => $data['title'],
'image'=> $oldimagename,
'content'=> $data['content']);
//$aboutus->save();
Aboutus::whereId($id)->update($aboutus);
}
return redirect()->back()->with('msg', 'Your Data is successfully Updated!');
}
public function aboutuspage_edit(Request $request,$id)
{
$aboutus = Aboutus::where('id',$id)->get();
return view('admin.edit-aboutus',compact('aboutus'));
}
public function aboutuspage_update(Request $request,$id)
{
$data = $request->all();
//$about = Aboutus::where('id', '=', $id)->first();
$obj = Aboutus::where('id',$id)->first();
//$obj = Aboutus::find($id);
$obj->title = $data['title'];
$obj->image = $data['oldimage'];
$obj->content = $data['content'];
$obj->status = $data['status'];
$obj->save();
return redirect()->back()->with('msg', 'Your Record is successfully Updated!');
//Aboutus::where('id',$id)->update(['title'=> $data['title'], 'image' => $data['oldimage'],]);
//DB::table('Aboutus')->where('id', $id)->update(['title' => $data['title']]);
}
public function delete_item($id)
{
$obj = Aboutus::find($id);
$obj->delete();
// using destroy method.
//Aboutus::destroy($id);
//Aboutus::destroy(1, 2, 3);
//Aboutus::where('id', '>', 10)->delete();
}
}
Gallery Controller
File name : GalleryController.php
<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Gallery;
use Illuminate\Support\Facades\Validator;
use Response;
use Image;
class GalleryController extends Controller
{
public function index()
{
/* php artisan cache:clear */
// \Artisan::call('cache:clear');
/* php artisan config:clear */
// \Artisan::call('config:clear');
/* php artisan migrate */
// \Artisan::call('migrate');
/* php artisan migrate */
// \Artisan::call('db:seed', array('--class' => "AdminSeeder"));
return view('admin.gallery');
}
public function add_gallery(Request $request)
{
$data = request()->all();
//$data = $request::all();
//$title = $request->get('title');
$rule = array(
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif',
'description' => 'required'
);
$this->validate($request,$rule);
$image = $request->file('image');
//$image = $request->image;
/* if($request->hasfile(image))
{
// it determined file is present or not
}
*/
//$request->image->store('images','public'); // it store the image
$image_name = uniqid() . '_' . time(). '.' . $image->getClientOriginalExtension();
/* $aboutus['datainfo'] = array(
'title' => $data['title'],
'image'=> $image_name,
'description'=> $data['description']
);
*/
$gallery = new Gallery([
'title' => $data['title'],
'image'=> $image_name,
'description'=> $data['description']
]);
$gallery->save();
//$uploaded_path = public_path('gallery');
$uploaded_path = storage_path('app\public\gallery');
/* ###### it create directory ##########
$file = public_path('images/gallery');
$result = File::makeDirectory($file);
File::deleteDirectory($folderPath); // delete directory
// ###### it create directory ########## */
if (! is_dir($uploaded_path))
{
mkdir($uploaded_path);
chmod($uploaded_path, 0777);
}
$image->move($uploaded_path,$image_name);
return redirect()->back()->with('msg', 'Your Data is successfully Submitted!');
}
public function file_upload(Request $request)
{
$image = $request->file('image');
//$image = $request->image;
$path = $request->photo->path();
$extension = $request->photo->extension();
if($request->hasfile(image))
{
$path = $request->image->store('images','public');
// If you do not want a file name to be automatically generated, you may use the storeAs method, which accepts the path, file name, and disk name as its arguments:
// $path = $request->photo->storeAs('images', 'filename.jpg');
}
}
public function show()
{
$gallery = Gallery::get();
return view('admin.gallery-show',compact('gallery'));
}
public function updateStatus(Request $request)
{
$obj = Gallery::findOrFail($request->id);
$obj->status = $request->status;
$obj->save();
return response()->json(['message' => 'User status updated successfully.']);
}
public function galleryimagedelete(Request $request)
{
$id = $request->input('id');
//$id = $request->get('id');
//$gallery = Gallery_detail::find($id)->delete($id);
$gallery = Gallery::find($id);
$image_name = $gallery->image;
if($gallery->delete())
{
//return response()->json(['success' => '1','successmsg' => "Your Data Successfully Deleted" ]);
/*if(\Storage::exists('app/public/gallery/'.$image_name))
{
\Storage::delete('app/public/gallery/'.$image_name);
}*/
if(file_exists(Storage_path('app/public/gallery/'.$image_name))){
unlink(Storage_path('app/public/gallery/'.$image_name));
}
$msg = "Your Data Successfully Deleted";
return response()->json(array('successmsg'=> $msg, 'status'=>"success"), 200);
}
else{
return response()->json(['error' => '0','errormsg' => "Sorry Data Not Deleted" ]);
}
//return response()->json(['success' => '1','successmessage' => "Your Data Successfully Deleted" ]);
exit;
}
public function editgallery($id)
{
//$id = $request->get('id');
$galleryinfo = Gallery::find($id);
//$galleryinfo = Gallery::findOrFail($id);
return response()->json(['data' => $galleryinfo]);
exit;
}
public function update_gallery(Request $request)
{
$id = $request->get('hidden_id');
$data = request()->all();
$image = $request->file('image');
if($image != '')
{
$image_name = uniqid() . '_' . time(). '.' . $image->getClientOriginalExtension();
$gallery = array(
'title' => $data['title'],
'image'=> $image_name,
'description'=> $data['description']);
Gallery::whereId($id)->update($gallery);
//$uploaded_path = public_path('gallery');
$uploaded_path = storage_path('app\public\gallery');
$image->move($uploaded_path,$image_name);
}
else
{
$oldimagename = $request->get('oldimagename');
$gallery = array(
'title' => $data['title'],
'image'=> $oldimagename,
'description'=> $data['description']);
Gallery::whereId($id)->update($gallery);
}
return redirect()->back()->with('msg', 'Your Data is successfully Updated!');
}
public function update_gallery_ajax(Request $request)
{
$request->validate([
'title' => 'required|max:255',
'description' => 'required',
]);
$id = $request->id;
$dataarray = array(
'id' => $request->id,
'title' => $request->title,
'description' => $request->description,
);
//$post = Gallery::updateOrCreate($dataarray);
Gallery::whereId($id)->update($dataarray);
return response()->json(['success'=> "Data Updatd successfully"]);
/*
$image = $request->image;
if($image != '')
{
$image_name = uniqid() . '_' . time(). '.' . $image->getClientOriginalExtension();
$dataarray = array(
'id' => $request->id,
'title' => $request->title,
'description' => $request->description,
'image' => $image_name );
//$post = Gallery::updateOrCreate($dataarray);
Gallery::whereId($id)->update($dataarray);
$uploaded_path = storage_path('app\public\gallery');
$image->move($uploaded_path,$image_name);
return response()->json(['success'=>'Gallery Updatd successfully with New Image']);
}
else{
$oldimagename = $request->oldimagename;
$gallery = array(
'id' => $request->id,
'title' => $request->title,
'description' => $request->description,
'image'=> $oldimagename,
);
Gallery::whereId($id)->update($gallery);
return response()->json(['success'=> "Data Updatd successfully with old Image"]);
}
//return response()->json(['code'=>200, 'msg'=>'Post Created successfully','data' => $post], 200);
*/
exit;
}
public function destroy(Request $request,$id)
{
//Gallery::where('id',$id)->delete();
$gallery = Gallery::find($id)->delete($id);
//return back();
return response()->json();
}
public function image_preview() {
return view('admin.image-preview');
}
public function saveimage(Request $request)
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($image = $request->file('image')) {
//$image = $request->image->store('public/images');
//$request->photo->storeAs('image', 'filename.jpg');
$image_name = uniqid() . '_' . time(). '.' . $image->getClientOriginalExtension();
$uploaded_path = storage_path('app\public\gallery');
$image->move($uploaded_path,$image_name);
return Response()->json([
"success" => true,
"image" => $image
]);
}
return Response()->json([
"success" => false,
"image" => ''
]);
}
public function resizeImage()
{
return view('admin.resizeImage');
}
public function resizeImagePost(Request $request)
{
$this->validate($request, [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$input['imagename'] = time().'.'.$image->extension();
$destinationPath = public_path('/thumbnail');
$img = Image::make($image->path());
$img->resize(100, 100, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input['imagename']);
$destinationPath = public_path('/images');
$image->move($destinationPath, $input['imagename']);
return back()
->with('success','Image Upload successful')
->with('imageName',$input['imagename']);
}
} // End Controller
Product Controller
File name : ProductController.php
<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Product;
use App\Productimage;
class ProductController extends Controller
{
public function index(Request $request)
{
return view('admin.product-add');
}
public function product_add(Request $request)
{
$validator = \Validator::make($request->all(), [
'name' => 'required',
'price' => 'required',
'slug' => 'required',
'quality' => 'required',
'discription' => 'required',
'images' => 'required',
])->validate();
$pro_obj = new Product();
$pro_obj->name = $request->name;
$pro_obj->slug = $request->slug;
$pro_obj->price = $request->price;
$pro_obj->quality = $request->quality;
$pro_obj->discription = $request->discription;
$pro_obj->save();
if($request->hasfile('images'))
{
foreach ($request->file('images') as $image) {
$image_name = uniqid() . '_' . time(). '.' . $image->getClientOriginalExtension();
$productImage = new Productimage;
//$uploaded_path = public_path().'images/products/'.$pro_obj->id.'/'.$image_name;
$uploaded_path = storage_path('app\public\products');
$image->move($uploaded_path,$image_name);
$productImage->product_id = $pro_obj->id;
$productImage->image = $image_name;
$productImage->save();
}
}
return redirect()->back()->with('msg', 'Product Details added successfully!');
}
public function show_products(Request $request)
{
//$products = Product::find(1);
$products = Product::get();
//$products->productimage->image;
//$products = Productimage::all();
//$products->product->name;
return view('admin.productslist',compact('products'));
}
public function viewbyid(Request $request,$id)
{
//$product = Productimage::find($id);
$product = Productimage::where('product_id', '=', $id)->get();
return view('admin.productview',compact('product'));
}
public function add_attribute(Request $request,$id)
{
$product_id = $id;
return view('admin.add-attribute',compact('product_id'));
}
public function delete_product(Request $request,$id)
{
$product = Product::find($id);
$product->delete();
return redirect()->back()->with('msg', 'Record Deleted Successfully');
}
}
Modal popup COntroller
File name : ModalpopupController.php
<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Response;
use Illuminate\Support\Facades\Validator;
class ModalpopupController extends Controller
{
public function index(Request $request)
{
return view('admin.modalpopup');
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
$input = $request->all();
if ($validator->passes()) {
// Store your user in database
return Response::json(['success' => '1']);
}
return Response::json(['errors' => $validator->errors()]);
}
}
Search Product
File name : Search.php
public function search_products(Request $request)
{
if($request->isMethod('post'))
{
$data = $request->all();
//echo "<pre>";
//print_r($data);
//die();
//$category = Category::with('categories')->where(['parent_id' => 0])->get();
$category = DB::table('categories')->where(['parent_id' => 0])->get();
$search_products = $data['product'];
$productAll = Product::where('name','like','%'.$search_products.'%')->orwhere('slug',$search_products)->where('status',1)->get();
$products = Product::all();
return view('product-listing')->with(compact('category','productAll','search_products','products'));
}
}
File name : index.php
File name : index.php
File name : index.php
File name : index.php
File name : index.php
File name : index.php
Script
File name : footer.php
<!-- Bootstrap core JavaScript -->
<script src="{{asset('assets/vendor/jquery/jquery.min.js')}}"></script>
<script src="{{asset('assets/vendor/bootstrap/js/bootstrap.bundle.min.js')}}"></script>
<!-- select2 Js -->
<script src="{{asset('assets/vendor/select2/js/select2.min.js')}}"></script>
<!-- Owl Carousel -->
<script src="{{asset('assets/vendor/owl-carousel/owl.carousel.js')}}"></script>
<!-- Custom -->
<script src="{{asset('assets/js/custom.js')}}"></script>
<script type="text/javascript">
$("#user_login").click(function(e) {
e.preventDefault();
//var email = $('#email').val();
var mobile = $('#user_mobile').val();
var password = $('#user_password').val();
var token = $("meta[name='csrf-token']").attr("content");
//var token = $(this).data("token");
$('#user_mobile-error').html(" ");
$('#user_password-error').html(" ");
$.ajax({
//url:'patient_login',
url:'login_user',
type: "post",
data:{mobile:mobile,password:password,_token:token},
success:function(response){
if(response.errors)
{
/* $('.alert-danger').html('');
$.each(response.errors, function(key, value){
$('.alert-danger').show();
$('.alert-danger').append('<li>'+value+'</li>');
});
*/
if(response.errors.mobile){
$( '#user_mobile-error' ).html( response.errors.mobile[0] );
}
if(response.errors.password){
$( '#user_password-error' ).html( response.errors.password[0] );
}
}
if(response.loginmsg)
{
e.preventDefault();
$("#login_success").show();
$("#login_success").html(response.loginmsg);
// Set the message text.
//$("#register_success").text(response.registermsg);
$("#login_success").fadeOut(10000);
setInterval(function(){
$('#login_success').addClass('hide');
$('#login_model').hide();
}, 20000);
location.reload();
}
if(response.errormsg)
{
$('#errormsg').show();
$('#errormsg').html(response.errormsg);
}
},
error:function(error)
{
console.log(error);
alert("sorry");
}
});
});
</script>
<script type="text/javascript">
$("#user_register").click(function(e) {
e.preventDefault();
var fname = $('#first_name').val();
var lname = $('#last_name').val();
var email = $('#email').val();
var mobile = $('#mobile').val();
var password = $('#password').val();
//var confpassword = $('#password_confirmation').val();
var token = $("meta[name='csrf-token']").attr("content");
//var token = $(this).data("token");
// var formdata = $('#frmregister').serialize();
$('#first_name-error').html(" ");
$('#last_name-error').html(" ");
$('#email-error').html(" ");
$('#mobile-error').html(" ");
$('#password-error').html(" ");
//$( '#password_confirmation-error' ).html( "" );
$.ajax({
//url:'register_patient',
url:'register',
type: "post",
data:{fname:fname,lname:lname,email:email,mobile:mobile,password:password,_token:token},
success:function(response){
if(response.errors)
{
/*
$('.alert-danger').html('');
$.each(response.errors, function(key, value){
$('.alert-danger').show();
$('.alert-danger').append('<li>'+value+'</li>');
});
*/
if(response.errors.fname){
$( '#first_name-error' ).html( response.errors.fname[0] );
}
if(response.errors.lname){
$( '#last_name-error' ).html( response.errors.lname[0] );
}
if(response.errors.email){
$( '#email-error' ).html( response.errors.email[0] );
}
if(response.errors.mobile){
$( '#mobile-error' ).html( response.errors.mobile[0] );
}
if(response.errors.password){
$( '#password-error' ).html( response.errors.password[0] );
}
/*
if(response.errors.password_confirmation){
$('#password_confirmation-error').html(response.errors.password_confirmation[0]);
}*/
}
if(response.registermsg)
{
e.preventDefault();
$("#register_success").show();
$("#register_success").html(response.registermsg);
// Set the message text.
//$("#register_success").text(response.registermsg);
$("#register_success").fadeOut(10000);
setInterval(function(){
$('#register_success').addClass('hide');
$('#login_model').hide();
}, 20000);
location.reload();
}
},
error:function(error)
{
console.log(error);
alert("sorry");
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#email").blur(function(){
var email = $(this).val();
//var email = $(#email).val();
//alert(email);
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url:'check-email-available',
method:'post',
data:{email:email, _token:token},
dataType:'json',
success:function(result)
{
// $('#availablity').html(result
// if(result != '0')
if(result > 0)
{
$("#availablity").html('<span class="text-danger"> Sorry! Email Already Exists </span>');
//$("#availablity").html("<font color='red'> Sorry! Email Already Exists </font>");
$("#user_register").attr("disabled",true);
}
else
{
$("#availablity").html('<span class="text-success"> Email Availabl </span>');
//$("#availablity").html("<font color='green'> Email Available </font>");
$("#user_register").attr("disabled",false);
}
}
});
});
});
$("#registeruser").click(function(e) {
e.preventDefault();
var fname = $('#firstname').val();
var lname = $('#lastname').val();
var email = $('#emailid').val();
var mobile = $('#mobileno').val();
var password = $('#userpassword').val();
//var confpassword = $('#password_confirmation').val();
var token = $("meta[name='csrf-token']").attr("content");
//var token = $(this).data("token");
// var formdata = $('#frmregister').serialize();
$('#firstname-error').html(" ");
$('#lastname-error').html(" ");
$('#emailid-error').html(" ");
$('#mobileno-error').html(" ");
$('#userpassword-error').html(" ");
//$( '#password_confirmation-error' ).html( "" );
$.ajax({
//url:'register_patient',
url:'register',
type: "post",
data:{fname:fname,lname:lname,email:email,mobile:mobile,password:password,_token:token},
success:function(response){
if(response.errors)
{
/*
$('.alert-danger').html('');
$.each(response.errors, function(key, value){
$('.alert-danger').show();
$('.alert-danger').append('<li>'+value+'</li>');
});
*/
if(response.errors.fname){
$( '#firstname-error' ).html( response.errors.fname[0] );
}
if(response.errors.lname){
$( '#lastname-error' ).html( response.errors.lname[0] );
}
if(response.errors.email){
$( '#emailid-error' ).html( response.errors.email[0] );
}
if(response.errors.mobile){
$( '#mobileno-error' ).html( response.errors.mobile[0] );
}
if(response.errors.password){
$( '#userpassword-error' ).html( response.errors.password[0] );
}
/*
if(response.errors.password_confirmation){
$('#password_confirmation-error').html(response.errors.password_confirmation[0]);
}*/
}
if(response.registermsg)
{
e.preventDefault();
$("#register_successmsg").show();
$("#register_successmsg").html(response.registermsg);
// Set the message text.
//$("#register_success").text(response.registermsg);
$("#register_successmsg").fadeOut(10000);
setInterval(function(){
$('#register_successmsg').addClass('hide');
$('#register_model').hide();
}, 20000);
location.reload();
}
},
error:function(error)
{
console.log(error);
alert("sorry");
}
});
});
</script>
<script>
$("#addtocart_item").click(function(e) {
e.preventDefault();
var productId = $('#productId').val();
var productPrice = $('#productPrice').val();
var productMrp = $('#productMrp').val();
var quantity = $('#quantity').val();
var weight = $('#weight').val();
var productImage = $('#productImage').val();
var token = $("meta[name='csrf-token']").attr("content");
//var token = $(this).data("token");
// var formdata = $('#frmregister').serialize();
$.ajax({
url:'addToCart',
type: "post",
data:{productId:productId,productPrice:productPrice,productMrp:productMrp,quantity:quantity,weight:weight,_token:token},
success:function(response){
if(response.registermsg)
{
e.preventDefault();
$("#register_successmsg").show();
$("#register_successmsg").html(response.registermsg);
// Set the message text.
//$("#register_success").text(response.registermsg);
$("#register_successmsg").fadeOut(10000);
setInterval(function(){
$('#register_successmsg').addClass('hide');
$('#register_model').hide();
}, 20000);
location.reload();
}
},
error:function(error)
{
console.log(error);
alert("sorry");
}
});
});
</script>
<script>
$("#addToCart").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var value;
$('.size.active input:radio').each(function (index) {
value = $(this).attr('value');
});
alert(vlaue);
if(value===undefined)
{
$('.size_valid_msg').html('Please select Size');
}
else
{
$('.size_valid_msg').html('');
$.ajax({
type: "POST",
url: 'addToCart',
data: form.serialize()+'&size='+value, // serializes the form's elements.
success: function(data)
{
if(data.status==1)
{
$(".modal-body p:first").text('Product Added to Cart');
$('#common-modal').modal('show');
setTimeout(function() {
location.reload();
}, 2000);
}
}
});
}
});
$('body').on('click', '.remove-cart', function(e){
console.log('remove cart function called');
var id = $(this).attr('id');
$.ajax({
type: "POST",
url: "{{ url('removeCart') }}",
data:{
"c_p_id": id,"_token": "{{ csrf_token() }}",
},
success: function(data)
{
if(data.status==1)
{
alert('Product Deleted From Cart');
location.reload();
}
}
});
});
$('body').on('click', '.left.dec', function(e){
e.preventDefault();
if($(this).siblings('input[name=p_tot_qty]').val()>1)
{
$(this).siblings('input[name=p_tot_qty]').val(parseInt($(this).siblings('input[name=p_tot_qty]').val())-1);
var id = $('.remove-cart').attr('id');
$.ajax({
type: "POST",
url: "{{ url('update-cart') }}",
data:{
"c_p_id": id,"type":"dec","_token": "{{ csrf_token() }}",
},
success: function(data)
{
if(data.status==1)
{
//alert('Product updated From Cart');
location.reload();
}
}
});
}
});
$('body').on('click', '.right.inc', function(e){
$(this).siblings('input[name=p_tot_qty]').val(parseInt($(this).siblings('input[name=p_tot_qty]').val())+1);
var id = $('.remove-cart').attr('id');
$.ajax({
type: "POST",
url: "{{ url('update-cart') }}",
data:{
"c_p_id": id,"type":"inc","_token": "{{ csrf_token() }}",
},
success: function(data)
{
if(data.status==1)
{
//alert('Product updated From Cart');
e.preventDefault();
location.reload();
}
}
});
});
</script>
<script type="text/javascript">
$("#btn_address_save").click(function(e) {
e.preventDefault();
var user_id = $('#user_id').val();
var first_name = $('#fname').val();
var last_name = $('#lname').val();
var address = $('#address').val();
var pincode = $('#pincode').val();
var mobile = $('#mobileno').val();
var landmark = $('#landmark').val();
var country = $('#country').val();
var state = $('#state').val();
var city = $('#city').val();
var address_type = $('#address_type').val();
var token = $("meta[name='csrf-token']").attr("content");
//var token = $(this).data("token");
// var formdata = $('#frmregister').serialize();
$('#fname-error').html(" ");
$('#lname-error').html(" ");
$('#address-error').html(" ");
$('#pincode-error').html(" ");
$('#mobileno-error').html(" ");
$('#landmark-error').html(" ");
$('#country-error').html(" ");
$('#state-error').html(" ");
$('#city-error').html(" ");
$('#address_type-error').html(" ");
//$( '#password_confirmation-error' ).html( "" );
$.ajax({
//url:'register_patient',
url:'add-address',
type: "post",
data:{user_id:user_id,first_name:first_name,last_name:last_name,address:address,pincode:pincode,mobile:mobile,landmark:landmark,country:country,state:state,city:city,address_type:address_type,_token:token},
success:function(response){
if(response.errors)
{
/*
$('.alert-danger').html('');
$.each(response.errors, function(key, value){
$('.alert-danger').show();
$('.alert-danger').append('<li>'+value+'</li>');
});
*/
if(response.errors.first_name){
$( '#fname-error' ).html( response.errors.first_name[0] );
}
if(response.errors.last_name){
$( '#lname-error' ).html( response.errors.last_name[0] );
}
if(response.errors.address){
$( '#address-error' ).html( response.errors.address[0] );
}
if(response.errors.pincode){
$( '#pincode-error' ).html( response.errors.pincode[0] );
}
if(response.errors.mobile){
$( '#mobileno-error' ).html( response.errors.mobile[0] );
}
if(response.errors.landmark){
$( '#landmark-error' ).html( response.errors.landmark[0] );
}
if(response.errors.country){
$( '#country-error' ).html( response.errors.country[0] );
}
if(response.errors.state){
$( '#state-error' ).html( response.errors.state[0] );
}
if(response.errors.city){
$( '#city-error' ).html( response.errors.city[0] );
}
if(response.errors.address_type){
$( '#address_type-error' ).html( response.errors.address_type[0] );
}
}
if(response.saveaddress)
{
e.preventDefault();
$("#saveaddress").show();
$("#saveaddress").html(response.saveaddress);
// Set the message text.
//$("#register_success").text(response.registermsg);
$("#saveaddress").fadeOut(10000);
setInterval(function(){
$('#saveaddress').addClass('hide');
$('#add-address-modal').hide();
}, 20000);
location.reload();
}
},
error:function(error)
{
console.log(error);
alert("sorry");
}
});
});
</script>
<script>
$('body').on('click', '.wishlist', function(e){
e.preventDefault();
var elem=$(this);
var product_id=$(this).attr('data-wishlist');
var ishome=$(this).attr('data-home');
jQuery.ajax({
url: "{{ url('add-wishlist') }}",
method: 'post',
data: {
"p_id": product_id,"_token": "{{ csrf_token() }}",
},
success: function(result){
if(result.status==0)
{
//$('#login').modal('show');
alert("Please Login First");
}
if(result.status==2)
{
// $('#login').modal('show');
//alert("Please Login First");
alert("Product Already wishlisted");
}
if(result.status==1)
{
if(ishome!=true){
$('.wishlist').addClass('active');
}
else{
$('.wishlist').css('color','red');
}
alert("Product Added to Wishlist");
$(".modal-body p:first").text('Product Added to Wishlist');
$('#common-modal').modal('show');
setTimeout(function() {
location.reload();
}, 2000);
}
else{
if(ishome!=true){
$('.wishlist').removeClass('active');
}
else{
// $('.wishlist').css('color','');
$('.wishlist').css('color','#bbbbbb');
}
$(".modal-body p:first").text('Product Removed from Wishlist');
$('#common-modal').modal('show');
setTimeout(function() {
location.reload();
}, 2000);
}
}});
});
</script>
<script>
$('body').on('click', '.removewishlist', function(e){
e.preventDefault();
var elem=$(this);
var product_id=$(this).attr('data-wishlist');
var ishome=$(this).attr('data-home');
jQuery.ajax({
url: "{{ url('remove-wishlist') }}",
method: 'post',
data: {
"p_id": product_id,"_token": "{{ csrf_token() }}",
},
success: function(result){
if(result.status==0)
{
//$('#login').modal('show');
alert("Please Login First");
}
if(result.status==2)
{
// $('#login').modal('show');
//alert("Please Login First");
alert("Product Already wishlisted");
}
if(result.status==1)
{
if(ishome!=true){
$('.wishlist').addClass('active');
}
else{
$('.wishlist').css('color','red');
}
alert("Product Added to Wishlist");
$(".modal-body p:first").text('Product Added to Wishlist');
$('#common-modal').modal('show');
setTimeout(function() {
location.reload();
}, 2000);
}
else{
if(ishome!=true){
$('.wishlist').removeClass('active');
}
else{
// $('.wishlist').css('color','');
$('.wishlist').css('color','#bbbbbb');
}
$(".modal-body p:first").text('Product Removed from Wishlist');
$('#common-modal').modal('show');
setTimeout(function() {
location.reload();
}, 2000);
}
}});
});
</script>
<script>
$('body').on('click', '#btn_place_order', function(e){
e.preventDefault();
$('#place_order').submit();
});
</script>
<script>
$(function(){
$('.delete_address').click(function(){
//var id = this.id ;
var id = $(this).data("id");
$('#deladdress').val(id);
$("#delete-address-modal").modal('show');
/*
if(confirm('Are you sure to delete this Address ?'))
{
$.ajax({
type:'DELETE',
data:'id='+id,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url : 'address-delete/'+id,
success:function(data){
//alert("Address deleted successfully");
location.reload();
},
error: function(data){
alert("Sorry Try Again");
}
});
}
*/
});
});
</script>
<script>
$(document).on('click','.edit_address',function(){
//var id = this.id ;
var id = $(this).data('id');
//alert(id);
//var id = $(this).attr('id');
$.ajax({
url:'edit-address/'+id+'/edit',
type:'GET',
data:{id:id},
dataType:'json',
success:function(response){
$('#f_name').val(response.data.first_name);
$('#l_name').val(response.data.last_name);
$('#deleveryaddress').val(response.data.address);
$('#deleverycity').val(response.data.city);
$('#deleverypincode').val(response.data.pincode);
$('#deleverymobileno').val(response.data.mobile);
$('#deleverycountry').val(response.data.country);
$('#deleverystate').val(response.data.state);
$('#deleveryaddresstype').val(response.data.address_type);
$('#deleverylandmark').val(response.data.landmark);
$('#hidden_id').val(response.data.id);
$('#edit-address-modal').modal('show');
}
});
});
$(document).on('click','#btn_update_address',function(){
//e.preventDefault();
var id = $("#hidden_id").val();
var firstname = $("#f_name").val();
var lastname = $("#l_name").val();
$.ajax({
url:'update-address_ajax/'+id+'/update',
type: "POST",
data:{id:id,firstname:firstname,lastname:lastname, _token: '{{csrf_token()}}'},
dataType:'json',
//contentType:false,
//cache:false,
//processData:false,
//headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success:function(response){
alert(response.success);
$("#msg").html(response.success);
$("#msg").fadeOut(2000);
$('.alert-danger').hide();
$('#edit-address-modal').modal('hide');
//location.reload();
//document.location.href="{!! url('showgallery'); !!}";
},
error: function(response) {
alert("sorry error");
}
});
});
</script>
<script>
function checkAvailability() {
$("#loaderIcon").show();
var pincode = $('#pincode').val();
if(pincode == "")
{
alert("Please Enter Pinode");
return false;
}
var token = $("meta[name='csrf-token']").attr("content");
jQuery.ajax({
url: "pincode-check",
type: 'GET',
data:{pincode:pincode, _token: '{{csrf_token()}}'},
dataType:'json',
success:function(data){
$(".pin-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
$("#check_pin").click(function(){
var pincode = $('#pincode').val();
if(pincode == "")
{
$("#pin-status").html("Please Enter PinCode");
$("#pin-availability-status").html(" ");
return false;
}
//alert(pincode);
var token = $("meta[name='csrf-token']").attr("content");
//var currenturl = window.location.href;
//alert(currenturl);
$.ajax({
url:'pincode-check',
type:'POST',
dataType:'json',
data:{pincode:pincode, _token:token},
success:function(result){
/* if(result.status == 1)
{
// document.getElementById("pin-status").style.display= 'none';
$("#pin-status").hide();
$("#pin-availability-status").html("Shipping Available");
}
if(result.status == 0)
{
$("#pin-status").html("Shipping Not Available");
//document.getElementById("pin-availability-status").style.display= 'none';
$("#pin-availability-status").hide();
}
*/
if(result > 0)
{
$("#pin-availability-status").html("<font color='green'> Shipping is Available for this pincode </font>");
$("#pin-status").html(" ");
}
else
{
$("#pin-availability-status").html("<font color='red'> Sorry! Shipping is Not Available for this pincode </font>");
$("#pin-status").html(" ");
}
},
error:function(error)
{
alert("sorry");
}
});
});
</script>
<script>
$(document().ready(function(){
});
</script>
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
<script type="text/javascript">
var path = "{{ url('search-products') }}";
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
</script>