I am doing a project. In this project I want to update name, websit and image field. I want that if a user choose new one then the field upadted otherwise it retains the past value. this works perfectly okay for my name and website_link. But I cant do the image field looking like this. Please help me guys.
My Controller is
public function edit($id)
{
if (Auth::check()) {
if (Auth::user()->user_role->role_id == 1) {
$sponsor = Sponsor::where('id', $id)->first();
if (!empty($sponsor)) {
$data = array(
'menu' => 'sponsor',
'sub_menu' => 'all',
'sponsor' => $sponsor
);
return view('backends.sponsors.edit', $data);
} else {
Session::flash('error', 'Try again.');
return redirect();
}
} else {
return redirect('');
}
} else {
return redirect('');
}
}
public function update(Request $request, $id)
{
if (Auth::check()) {
if (Auth::user()->user_role->role_id == 1) {
$sponsor = Sponsor::where('id', $id)->first();
if (!empty($sponsor)) {
$rules = array(
'name' => '',
'website_link' => '',
'logo' => ''
);
$valid = Validator::make($request->input(), $rules);
if ($valid->fails()) {
return redirect('sponsors/edit/' . $sponsor->id)->withErrors($valid)->withInput();
} else {
$sponsor->name = $request->input('name');
$sponsor->website_link = $request->input('website_link');
// $sponsor->logo = $request->input('logo');
$photo = $request->file('logo');
if($photo)
{
$ext = $photo->getClientOriginalExtension();
$fileName = rand(100, 5000000) . '.' .$ext;
$sponsor->logo = 'public/assets/uploads/sponsors/'.$fileName;
$photo->move(base_path().'/public/assets/uploads/sponsors/',$fileName);
} else {
}
if ($sponsor->save()) {
Session::flash('success', 'Area of experience updated successful.');
return redirect('sponsors/all');
} else {
Session::flash('error', 'Try again.');
return redirect('sponsors/edit//' . $sponsor->id);
}
}
} else {
Session::flash('error', 'Try again.');
return redirect('sponsors/all');
}
} else {
return redirect('');
}
} else {
return redirect('');
}
}
My view page is
#extends ('backends.layouts.app')
#section('main')
<main id="main-container">
<div class="content bg-gray-lighter">
<div class="row items-push">
<div class="col-sm-7">
<h1 class="page-heading">
Sponsors <small>That feeling of delight when you start your awesome new project!</small>
</h1>
</div>
<div class="col-sm-5 text-right hidden-xs">
<ol class="breadcrumb push-10-t">
<li><a class="link-effect" href="{{ URL::to('admin/dashboard') }}">Home</a></li>
<li>Sponsor</li>
</ol>
</div>
</div>
</div>
<div class="content">
<div class="block">
<div class="block-header">
<h3 class="block-title">Sponsor</h3>
</div>
<div class="col-md-12">
#if(Session::has('success'))
<div class="alert alert-success">
<strong> {{ Session::get('success') }}</strong>
</div>
#endif
#if(Session::has('error'))
<div class="alert alert-danger">
<strong> {{ Session::get('error') }}</strong>
</div>
#endif
</div>
<div class="clearfix"></div>
<div class="block-content">
<form method="POST" action="{{ (!empty($sponsor->id)) ? URL::to('sponsors/edit/'.$sponsor->id) : '' }}" class="push-10-t" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<div class="form-material floating">
<input type="text" name="name" value="{{ (!empty($sponsor->name)) ? $sponsor->name : old('name') }}" id="name" class="form-control" required >
<label for="name">Company Name</label>
</div>
</div>
<div class="form-group">
<div class="form-material floating">
<input type="text" name="website_link" value="{{ (!empty($sponsor->website_link)) ? $sponsor->website_link : old('name') }}" id="website_link" class="form-control" >
<label for="website_link">Website Link</label>
</div>
</div>
<div class="form-group">
<label for="logo">Logo</label><br/>
<div id="prev" style="display: none" class="col-md-3 thumbnail">
<img id="blah" class="img-responsive">
</div>
<div class="clearfix"></div>
<div class="form-group">
<label for="logo"> <span class="btn btn-primary" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="fileName0">Browse</span></label>
<input type="file" name="logo" style="visibility: hidden; position: absolute;" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="logo" class="form-control" required>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
</main>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#logo").change(function(){
$('#prev').show();
readURL(this);
});
</script>
#endsection
Please help me solving this
The answer will be
public function update(Request $request, $id)
{
if (Auth::check()) {
if (Auth::user()->user_role->role_id == 1) {
$sponsor = Sponsor::where('id', $id)->first();
if (!empty($sponsor)) {
$rules = array(
'name' => 'required',
'website_link' => 'required',
'logo' => ''
);
$valid = Validator::make($request->input(), $rules);
if ($valid->fails()) {
return redirect('sponsors/edit/' . $sponsor->id)->withErrors($valid)->withInput();
} else {
$sponsor->name = $request->input('name');
$sponsor->website_link = $request->input('website_link');
$hdLogo = $request->input('hdLogo');
$photo = $request->file('logo');
if(!empty($photo) && !empty($hdLogo)){
$ext = $photo->getClientOriginalExtension();
$fileName = rand(100, 5000000) . '.' .$ext;
$sponsor->logo = 'public/assets/uploads/sponsors/'.$fileName;
$photo->move(base_path().'/public/assets/uploads/sponsors/',$fileName);
}else if(!empty($photo) && empty($hdLogo)){
$ext = $photo->getClientOriginalExtension();
$fileName = rand(100, 5000000) . '.' .$ext;
$sponsor->logo = 'public/assets/uploads/sponsors/'.$fileName;
$photo->move(base_path().'/public/assets/uploads/sponsors/',$fileName);
}else if(empty($photo) && !empty($hdLogo)){
$sponsor->logo = $sponsor->logo;
}
else if(empty($photo) && empty($hdLogo)){
Session::flash('error','Logo is required.');
return redirect()->back();
}
if ($sponsor->save()) {
Session::flash('success', 'Sponsor updated successful.');
return redirect('sponsors/all');
} else {
Session::flash('error', 'Try again.');
return redirect()->back();
}
}
} else {
Session::flash('error', 'Try again.');
return redirect('sponsors/all');
}
} else {
return redirect('');
}
} else {
return redirect('');
}
}
And the view file will be
#extends ('backends.layouts.app')
#section('main')
<main id="main-container">
<div class="content bg-gray-lighter">
<div class="row items-push">
<div class="col-sm-7">
<h1 class="page-heading">
Sponsors <small>That feeling of delight when you start your awesome new project!</small>
</h1>
</div>
<div class="col-sm-5 text-right hidden-xs">
<ol class="breadcrumb push-10-t">
<li><a class="link-effect" href="{{ URL::to('admin/dashboard') }}">Home</a></li>
<li>Sponsor</li>
</ol>
</div>
</div>
</div>
<div class="content">
<div class="block">
<div class="block-header">
<h3 class="block-title">Sponsor</h3>
</div>
<div class="col-md-12">
#if(Session::has('success'))
<div class="alert alert-success">
<strong> {{ Session::get('success') }}</strong>
</div>
#endif
#if(Session::has('error'))
<div class="alert alert-danger">
<strong> {{ Session::get('error') }}</strong>
</div>
#endif
</div>
<div class="clearfix"></div>
<div class="block-content">
<form method="POST" action="{{ (!empty($sponsor->id)) ? URL::to('sponsors/edit/'.$sponsor->id) : '' }}" class="push-10-t" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<div class="form-material floating">
<input type="text" name="name" value="{{ (!empty($sponsor->name)) ? $sponsor->name : old('name') }}" id="name" class="form-control" required >
<label for="name">Company Name</label>
</div>
</div>
<div class="form-group">
<div class="form-material floating">
<input type="text" name="website_link" value="{{ (!empty($sponsor->website_link)) ? $sponsor->website_link : old('name') }}" id="website_link" class="form-control" >
<label for="website_link">Website Link</label>
</div>
</div>
<div class="form-group">
<label for="logo">Logo</label><br/>
<input type="hidden" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : ''}}" name="hdLogo">
#if(!empty($sponsor->logo))
<div id="prev" class="col-md-3 thumbnail">
<img id="blah" src="{{ url($sponsor->logo)}}" class="img-responsive">
</div>
#else
<div id="prev" style="display: none" class="col-md-3 thumbnail">
<img id="blah" src="{{ (!empty($sponsor->logo)) ? $sponsor->logo : '' }}" class="img-responsive">
</div>
#endif
<div class="clearfix"></div>
<div class="form-group">
#if(!empty($sponsor->logo))
<label for="logo"> <span class="btn btn-primary" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="fileName0">Browse</span></label>
<input type="file" name="logo" style="visibility: hidden; position: absolute;" id="logo" class="form-control">
#else
<label for="logo"> <span class="btn btn-primary" value="{{ (!empty($sponsor->logo)) ? $sponsor->logo : old('logo') }}" id="fileName0">Browse</span></label>
<input type="file" name="logo" style="visibility: hidden; position: absolute;" id="logo" class="form-control" required>
#endif
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
</main>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#logo").change(function(){
$('#prev').show();
readURL(this);
});
</script>
#endsection
Related
I have a form with 3 fields - start date, end date and pattern. I want to pick the values from the input and check if those are empty. if not then compare the dates and perform action. By when I tried passing the value `$request->input('from')` in $status, it returned null.
my form:
<div class="modal-body">
<form action="App\Http\Controllers\HolidayController#addSchedule" method="POST" autocomplete="off" id="scheduleForm">
#include('partials.holidayFormModal')
</form>
</div>
holidayFormModal:
<link rel="stylesheet" href="{{ url('assets/custom/css/schedule/scheduleForm.css') }}">
<div class="form-group row col-md-12 date-picker">
<label class="col-sm-2 date-picker-label" for="from">
{{ __('messages.schedule_period') }}
</label>
<div class="input-group col-sm-4">
<input class="form-control" id="start_datepicker" type="text" name="from" autocomplete="off" readonly>
<span class="input-group-addon">
<i class="fas fa-calendar-alt"></i>
</span>
</div>
<div class="col-sm-2"></div>
<div class="input-group col-sm-4">
<input class="form-control" id="end_datepicker" type="text" name="to" autocomplete="off" readonly>
<span class="input-group-addon">
<i class="fas fa-calendar-alt"></i>
</span>
</div>
</div>
<div class="form-group row col-md-12 motif-picker">
<label class="col-sm-2 motif-label" for="meotif">
{{ __('messages.schedule_motif') }}
</label>
<input class="form-control col-sm-10" type="text" id="motif" name="motif" max="60">
</div>
<div class="col-md-11"></div>
<div class="col-md-1" id="schedule-submit">
<button class="btn" type="button" id="schedule_form_submit_button">
<i class="fas fa-check-circle fa-3x"></i>
</button>
</div>
web.php :
Route::get('/holidays', ['uses' => $controllerNamespace . 'HolidayController#index', 'as' => 'holidays']);
Route::post('/holidayAdd',['uses' => $controllerNamespace . 'HolidayController#addSchedule', 'as' => 'holidayAdd']);
HolidayController:
public function addSchedule(Request $request) {
$scheduleModelObj = new ScheduleModel;
$scheduleModelObj->from = $request->from;
$scheduleModelObj->to = $request->to;
$scheduleModelObj->motif = $request->motif;
$fromDate = str_replace('/', '-', $request->from);
$toDate = str_replace('/', '-', $request->to);
$f = date('Y-m-d', strtotime($fromDate));
$t = date('Y-m-d', strtotime($toDate));
if ($f == '' || $t == '' || $scheduleModelObj->motif == '') {
$returnMessage['date'] = __('messages.schedule_end_date_error');
$returnMessage['motif'] = __('messages.schedule_motif_error');
$status = 'error';
} else {
if ($f < $t) {
$scheduleModelObj->searchSchedule($scheduleModelObj->from, $scheduleModelObj->to);
$status = 'success';
}
$returnMessage['date'] = __('messages.schedule_end_date_error');
$returnMessage['motif'] = __('messages.schedule_motif_error');
$status = 'error';
}
return ['status' => $status, 'message' => $returnMessage];
}
Try this:
<div class="modal-body">
<form action="{{route('holidayAdd')}}" method="POST" autocomplete="off" id="scheduleForm">
#include('partials.holidayFormModal')
</form>
</div>
im trying to edit an image on laravel 6, but but it does not advance to next view, stays on the form view.
I have seen many tutorials of laravel 5.8 and 6. I can't make it work in any way
This is de controller:
public function update(Request $request, $id)
{
$validator = $request->validate([
'titulo' => 'required | max:50', //campo obligatorio y máximo 50 caracteres
'contenido' => 'required | max:150',
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$image_name = time().'.'.$request->imagen->getClientOriginalExtension();
$request->image->move(public_path('images'), $image_name);
$datos = array(
'titulo' => $request->titulo,
'contenido' => $request->contenido,
'imagen' => $image_name,
);
Noticia::whereId($id)->update($datos);
return redirect('/mostrar');
}
THis is Web.php file:
Route::get('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
Route::get('/editar/{id}', 'crearNoticiaController#edit')->name('editar');
this is form file:
<div class="subir-imagen">
<form method="get" action="{{ route('actualizar', $noticia->id) }}" enctype="multipart/form-data">
#csrf
<div class="crear-titulo">
<input class="titulo" type="text" name="titulo" placeholder="Escriba el titulo" value="{{$noticia->titulo}}">
</div>
<div class="crear-contenido">
<textarea class="ckeditor" name="contenido" placeholder="Escriba el contenido" >
{{$noticia->contenido}}
</textarea>
</div>
<table border="2">
<tr>
<td><img src="{{URL::to('/')}}/images/{{$noticia->imagen}}" alt="imagen" width="250" align="left"/></td>
</tr>
</table>
<div class="form-group">
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" />
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<input type="submit" class="btn btn-primary" value="Enviar" id="btn-enviar" />
</div>
</div>
</form>
</div>
Thnaks for help
I faced same issue, but luckily i solved this problem.I added my solution below, i think this will help you to solve this problem
public function updatePost(Request $request, $id)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:25|min:4',
'image' => 'mimes:jpeg,jpg,png,JPEG,JPG,PNG | max:100000',
]);
$data = array();
$data['category_id'] = $request->category_id;
$data['title'] = $request->title;
$data['details'] = $request->details;
$image = $request->file('image');
if($image)
{
$image_name = hexdec(uniqid());
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/assets/img/';
$image_url = $upload_path.$image_full_name;
$success = $image->move($upload_path,$image_full_name);
$data['image'] = $image_url;
unlink($request->old_photo);
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
else
{
$data['image'] = $request->old_photo;
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
}
edit_post.blade.php
#extends('welcome')
#section('content')
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<p>
List Posts
</p>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ url('posts.update_posts/'.$posts->id) }}" method="post" enctype="multipart/form-data">
#csrf
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<div>Category Name</div>
<label>Category ID</label>
<select class="form-control" name="category_id">
#foreach($category as $categories)
<option value="{{ $categories->id }}" <?php if ($categories->id == $posts->category_id)
echo "selected"; ?> > {{ $categories->name }} </option>
#endforeach
</select>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Title</label>
<input type="text" name="title" class="form-control" value="{{ $posts->title }}" id="title" required data-validation-required-message="Please product name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Details</label>
<textarea name="details" rows="5" class="form-control" value="{{ $posts->details }}" id="details"></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Image</label>
<input type="file" name="image" class="form-control" id="image"><br/>
Old Image : <img src="{{ URL::to($posts->image) }}" style="hight: 40px; width: 100px">
<input type="hidden" name="old_photo" value="{{ $posts->image }}">
</div>
</div>
<br>
<div id="success"></div>
<div class="form-group">
<button type="submit" class="btn btn-success" id="sendMessageButton">Update</button>
</div>
</form>
</div>
</div>
</div>
#endsection
First run on your project console command:
php artisan storage:link
Then try this code and if return any error message tell me khow:
$imagen = $request->file("imagen");
$extension = $imagen->extension();
$filename = time().".".$extension;
$request->file('imagen')->storeAs("public/images", $filename);
Finally check your public/images folder for image file exists.
Also you can read about storing uploaded files in laravel 6.x official documentation
I've solved with this way:
In web.php I put patch instead get
Route::patch('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
In the edit blade I put: #method('PATCH')
And this is the update in the controller:
public function update(Request $request, $id)
{
$noticia = Noticia::findOrFail($id);
$noticia->titulo = $request->get('titulo');
$noticia->contenido = $request->get('contenido');
$noticia->imagen = $request->file('imagen');
$validator = $request->validate([
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$imageName = time().'.'.request()->imagen->getClientOriginalExtension();
request()->imagen->move(public_path('images'), $imageName);
$noticia->imagen = $imageName;
$noticia->update();
return redirect('/mostrar'); //Redirigimos a la la vista para mostrar las noticias
}
I wish to be able to edit my users through the admin panel but this returns the following error to me:
Trying to get property 'id' of non-object
it will be an error in my view with the call of the variable ID if I change it I have the same thing with my variable name.
I use the users table and in no other place in my code do I have problems
help me please
URI : /role-edit/{id}
View :
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4>Edit register roles</h4>
</div>
<div class="card-body">
<form action="/role-register-update/{{ $users->id }}" method="POST">
{{ csrf_field() }}
{{ method_field('PUT') }}
<div class="form-group">
<label>Name</label>
<input type="text" name="name" value="{{ $users->name }}" class="form-control">
</div>
<div class="form-group">
<label>Give role</label>
<select name="type" class="form-control">
<option value="admin">Admin</option>
<option value="vendor">Vendor</option>
<option value="">None</option>
</select>
<button type="submit" class="btn btn-success">Update</button>
Cancel
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Controller :
class DashboardController extends Controller
{
public function registered()
{
$users = User::all();
return view('admin.registeradmin')->with('users', $users);
}
public function edit(Request $request,$id)
{
$users = User::findOrFail($id);
return view('admin.edit-register')->with('users',$users);
}
public function update(Request $request, $id)
{
$users = User::findOrFail($id);
$users->name = $request->input('name');
$users->usertype = $request->input('type');
$users->update();
return redirect('/role-register')->with('status', 'You data is update');
}
public function destroy($id)
{
$users = User::where('id', $id);
if ($users != null)
{
$users->delete();
return redirect('/role-register')->with('status', 'User is correctly deleted !');
}
return redirect('/role-register')->with('status', 'User is not correctly deleted !');
}
}
Routes :
Route::get('/', function () {
return view('pages.home');
});
Route::get('/aboutus', function () {
return view('pages.aboutus');
})->name('aboutus');
Auth::routes();
Route::get('profile', 'UserProfileController#show')->middleware('auth')->name('profile.show');
Route::post('profile', 'UserProfileController#update')->middleware('auth')->name('profile.update');
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth', 'admin']], function () {
Route::get('/dashboard', function () {
return view('admin.dashboard');
});
Route::get('/role-register', 'Admin\DashboardController#registered');
Route::get('/role-edit/{id}', 'Admin\DashboardController#edit');
Route::put('/role-register-update/{id}', 'Admin\DashboardController#update');
Route::delete('/role-delete/{id}', 'Admin\DashboardController#destroy');
});
Add dd($users) in the edit function of your controller. If you get the data, add the following to the form action form action:
{{route('routename',['id'=>$users->id])}}
// Controller
public function Updateprofile(Request $request)
{
if (Auth::check() && Auth::user()->role->id == 2) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email'
]);
$image = $request->file('image');
$slug = str_slug($request->name);
if (isset($image))
{
$currentDate = Carbon::now()->toDateString();
$imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(600,500);
if (!file_exists('storage/uploads/profile'))
{
mkdir('storage/uploads/profile',0777,true);
}
unlink('storage/uploads/profile/'.Auth::user()->image);
$image_resize->save('storage/uploads/profile/'.$imagename);
}else{
$imagename = Auth::user()->image;
}
$user = User::find(Auth::id());
$user->name = $request->name;
$user->email = $request->email;
$user->image = $imagename;
$user->save();
Toastr::success('Profile Successfully Updated :)', 'Success');
return redirect()->back();
}
}
// blade file
<form method="POST" action="{{route('user.profile.update')}}" class="form-horizontal" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="row clearfix">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
<label for="name">Name : </label>
</div>
<div class="col-lg-10 col-md-10 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
<input type="text" id="name" class="form-control" placeholder="Enter your name" name="name" value="{{Auth::user()->name}} {{old('name')}}">
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
<label for="image">{{__('Image')}} : </label>
</div>
<div class="col-lg-10 col-md-10 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
<input type="file" name="image" >
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
<label for="email_address_2">Email Address</label>
</div>
<div class="col-lg-10 col-md-10 col-sm-8 col-xs-7">
<div class="form-group">
<div class="form-line">
<input type="text" id="email_address_2" class="form-control" value="{{Auth::user()->email}} {{old('email')}}" placeholder="Enter your email address" name="email" ">
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-offset-2 col-md-offset-2 col-sm-offset-4 col-xs-offset-5">
<button type="submit" class="btn btn-primary m-t-15 waves-effect">UPDATE</button>
</div>
</div>
</form>
I am using the Croppie script to edit images before uploading to my server.
https://foliotek.github.io/Croppie/
The problem is Croppie encodes the cropped image in a base64 format. I have created a hidden input and attached the base64 string. I need to know how to grab the string so i can decode it and post it with my form.
I have tried so many methods but i am stuck. Any help will be appreciated
Controller
$post = new Post;
$post->post_category_id = $request->post_category_id;
$post->title = $request->title;
$post->body = $request->body;
$post->meta_description = $request->meta_description;
$post->slug = $request->slug;
$post->user_id = auth()->id();
$image = $request->input('featimage'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'image_' . time() . '.' . $image_extension[1]; //generating unique file name;
\Storage::disk('public')->put($imageName,base64_decode($image)
$post->save();
}
View
<form class="form-horizontal" action="{{route('posts.store')}}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<fieldset>
<div class="form-group row"><label class="col-md-2 col-form-label">Title</label>
<div class="col-md-10"><input class="form-control" name="title" type="text"><span class="form-text">Please insert a title <small>eg. Exciting new event coming to London</small>
</span></div>
</div>
</fieldset>
<fieldset class="">
<div class="form-group row"><label class="col-md-2 col-form-label">Category</label>
<div class="col-md-10"><select name="post_category_id" class="custom-select custom-select-sm">
#foreach($postCategories as $postCategory)
<option value="{{ $postCategory->id }}">{{ $postCategory->name }}</option>
#endforeach
</select></div>
</div>
</fieldset>
<fieldset>
<div class="form-group row"><label class="col-md-2 col-form-label">Post Body</label>
<div class="col-md-10">
<textarea type="textarea" class="form-control" rows="10" name="body"></textarea>
</div>
</div>
</fieldset>
<fieldset>
<div class="form-group row"><label class="col-md-2 col-form-label">Meta Description</label>
<div class="col-md-10">
<textarea type="textarea" class="form-control" rows="4" name="meta_description"></textarea>
</div>
</div>
</fieldset>
<fieldset>
<select name="tags[]" multiple="multiple" class="form-control select2-multi">
#foreach($tags as $tag)
<option value="{{ $tag->id }}">{{ $tag->name }}</option>
#endforeach
</select>
</fieldset>
</div>
</div><!-- END card-->
</div>
<div class="col-md-4">
<div class="card card-default">
<div class="card-header">Featured Image</div>
<div class="card-body">
<fieldset>
<figure>
<img src="" class="gambar img-responsive img-thumbnail" id="item-img-output" /></figure>
<input type="hidden" id="featimage" name="featimage">
</fieldset>
<input type="file" class="item-img file center-block" name="upload"/>
</label>
</div>
<div>
</div>
<!-- START card-->
<div class="card card-default">
<div class="card-header">Slug</div>
<div class="card-body">
<div class="input-group mb-3">
<div class="input-group-prepend"><span class="input-group-text" id="basic-addon1">www.sixmedia.co.uk/</span></div><input class="form-control" name="slug" type="text" placeholder="slug" aria-label="Username" aria-describedby="basic-addon1">
</div>
</div>
</div><!-- END card-->
<!-- START card-->
<div class="card card-default">
<div class="card-header">Featured</div>
<div class="card-body">
<div class="col-md-12">
<fieldset>
<div class="form-group row">
#foreach($featured as $feat)
<div class="checkbox c-checkbox"><label><input name="featured[]" type="checkbox" value="{{$feat->id}}"><span class="fa fa-check"></span>{{ $feat->name }} </label></div>
#endforeach
</div>
</fieldset>
</div>
</div>
</div><!-- END card-->
<button class="btn btn-primary btn-block" name="submit">Save</button>
<button class="btn btn-danger btn-block" name="submit">Cancel</button>
</form>
JS
<script type="text/javascript">
$(".gambar").attr("src", "http://www.pngall.com/wp-content/uploads/2/Upload-PNG-Image-File.png");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 500,
height: 281,
},
enforceBoundary: false,
enableExif: true
});
$('#cropImagePop').on('shown.bs.modal', function(){
// alert('Shown pop');
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
console.log('jQuery bind complete');
});
});
$('.item-img').on('change', function () { imageId = $(this).data('id'); tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId); readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'base64',
format: 'png',
size: {width: 350, height: 200}
}).then(function (resp) {
$('#item-img-output').attr('src', resp);
$('#featimage').attr('src', resp);
$('#cropImagePop').modal('hide');
});
});
// End upload preview image
</script>
The problem seems to be in your jquery script, you are setting the base64 string as the source of <input type="hidden" id="featimage">
change this:
$('#featimage').attr('src', resp);
to this
`$('#featimage').val(resp);`
I am new to Laravel. I want to use MongoDB with laravel so I have installed mongodb and configured php extension also(copied mongo dll file) and it works fine.
Now I want to use CRUD operation in laravel using mongoDB. How can I use. How to create model. What I need to modify in model.
Note: show me model code. In model what I have to write.
Thank You
It seems that there's a package that enables you to use MongoDB with Eloquent. I'm not a fan of linking external sources without quoting information here, but copying their readme sounds counterproductive as well. The instructions seem easy enough, so I hope this can help you: Laravel MongoDB.
Example code MongoDb + Php:
Insert:
$mongo = new MongoClient();
$db = $mongo->mydb1;
$data = array('emp_id' => '1', 'first_name' => 'Tiger' , 'last_name' => 'Nixon', 'position' => 'System Architect', 'email' => 't.nixon#datatables.net', 'office' => 'Edinburgh', 'start_date' => '2011-04-25 00:00:00', 'age' => '61', 'salary' => '320800', 'projects' => array('Project1', 'Project2', 'Project3'));
$collection = $db->createCollection("emp_details");
if($collection->insert($data))
{
echo '<p style="color:green;">Record inserted successfully</p>';
}
Update:
$mongo = new MongoClient();
$db = $mongo->mydb1;
/* Note: Here we are using the update() method. The update() method update values in the existing document */
$collection = $db->createCollection("emp_details");
$newdata = array('$set' => array("age" => "55", "salary" => "320000"));
// specify the column name whose value is to be updated. If no such column than a new column is created with the same name.
$condition = array("emp_id" => "1");
// specify the condition with column name. If no such column exist than no record will update
if($collection->update($condition, $newdata))
{
echo '<p style="color:green;">Record updated successfully</p>';
}
else
{
echo '<p style="color:red;">Error in update</p>';
}
Delete:
$mongo = new MongoClient();
// name of database which is to be created
$db_name = 'local';
// get the list of database and check if DB exist, if not than create it.
$dblists = $mongo->listDBs();
if(count($dblists) > 0)
{
$count = 0;
$exist = false;
foreach($dblists['databases'] as $databases)
{
if($databases['name'] == $db_name)
{
$exist = true;
break;
}
}
}
if($exist)
{
$db = $mongo->db_name; // select the db which is to be deleted
if($db)
{
if($db->drop())
{
echo '<p style="color:green;">Database deleted successfully</p>';
}
}
}
else
{
echo '<p style="color:red;">No such database exist</p>';
}
In case of Laravel, you have to study the basic CRUD operation then you will use this very well.
Create Customer Controller
<?php
namespace App\Http\Controllers;
use App\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Hash;
class CustomerController extends Controller
{
public function index(Request $request)
{
$search = $request->get('search');
$field = $request->get('field') != '' ? $request->get('field') : 'firstname';
$sort = $request->get('sort') != '' ? $request->get('sort') : 'asc';
$customers = new Customer();
$customers = $customers->where('firstname', 'like', '%' . $search . '%')
->orderBy($field, $sort)
->paginate(5)
->withPath('?search=' . $search . '&field=' . $field . '&sort=' . $sort);
return view('theme.customers_list', compact('customers'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
public function add()
{
return view('theme.customer_form');
}
public function add_record(Request $request)
{
$this->validate($request,
[
'firstname' =>'required|max:20',
'lastname' =>'required|max:20',
'email' =>'required|email|unique:users',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password',
'phone' =>'required|numeric|phone',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
], [
'firstname.required' => ' The first name field is required.',
//'firstname.min' => ' The first name must be at least 5 characters.',
'firstname.max' => ' The first name may not be greater than 20 characters.',
'lastname.required' => ' The last name field is required.',
//'lastname.min' => ' The last name must be at least 5 characters.',
'lastname.max' => ' The last name may not be greater than 20 characters.',
]);
$customers = new Customer;
$customers->firstname = $request->input('firstname');
$customers->lastname = $request->input('lastname');
$customers->email = $request->input('email');
$customers->phone = $request->input('phone');
$customers->password = Hash::make($request->input('password'));
$customers->confirm_password = $request->input('confirm_password');
if($request->hasFile('image'))
{
$filename = $request->image->getClientOriginalName();
$request->image->storeAs('public/uploads',$filename);
}
$customers->image = $filename;
$customers->save();
return redirect()->action('CustomerController#index');
}
public function edit($id)
{
$customers = Customer::find($id);
return view('theme.customer_edit',compact('customers'));
}
public function update(Request $request, $id)
{
$this->validate($request,
[
'firstname' =>'required|max:20',
'lastname' =>'required|max:20',
'email' =>'required|email|unique:users',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password',
'phone' =>'required|numeric|phone',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
], [
'firstname.required' => ' The first name field is required.',
//'firstname.min' => ' The first name must be at least 5 characters.',
'firstname.max' => ' The first name may not be greater than 20 characters.',
'lastname.required' => ' The last name field is required.',
//'lastname.min' => ' The last name must be at least 5 characters.',
'lastname.max' => ' The last name may not be greater than 20 characters.',
]);
$customers = Customer::find($id);
$customers->firstname = $request->input('firstname');
$customers->lastname = $request->input('lastname');
$customers->email = $request->input('email');
$customers->phone = $request->input('phone');
$customers->password = $request->input('password');
$customers->confirm_password = $request->input('confirm_password');
if($request->hasFile('image'))
{
$filename = $request->image->getClientOriginalName();
$request->image->storeAs('public/uploads',$filename);
}
$customers->image = $filename;
$customers->save();
return redirect()->action('CustomerController#index');
}
public function delete($id)
{
Customer::find($id)->delete();
return redirect()->action('CustomerController#index');
}
public function search()
{
$name = Input::get('search');
if ($name != "")
{
$customers = Customer::where('firstname','Like','%' . $name . '%')
->orWhere('email','Like','%' . $name . '%')
->get();
return view('theme.customers_list',compact('customers'));
}
else
{
dd('no data found');
}
}
public function login()
{
return view('theme.login');
}
public function do_login(Request $request)
{
$email=$request->input('email');
$password = Hash::check($request->input('password'));
dd($password);exit();
$data=with(new Customer)->SignIn($email,$password);
$row=count($data);
if($row > 0){
echo "Login success";
}else{
echo "usename and password Mismatch!";
}
}
}
Now create customer_form.blade.php
#extends('theme.default')
#section('content')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Customer</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<!-- #if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif -->
<form role="form" action="<?php echo url('customer/add_record')?>" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="Firstname">
<span class="text-danger">{{ $errors->first('firstname') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('lastname') ? 'has-error' : '' }}">
<label for="lastname">Lastname</label>
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Lastname">
<span class="text-danger">{{ $errors->first('lastname') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control" placeholder="Email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}">
<label for="phone">Contact Number</label>
<input type="text" name="phone" id="phone" class="form-control" placeholder="Contact Number">
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('confirm_password') ? 'has-error' : '' }}">
<label for="confirm_password">Confirm Password</label>
<input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password">
<span class="text-danger">{{ $errors->first('confirm_password') }}</span>
</div>
</div>
</div>
<div class="row">
<div class= "col-lg-6">
<div class="form-group">
<label>Image</label>
<input type="file" name="image" id="image">
</div>
</div>
<!-- <div class= "col-lg-6">
<div class="form-group">
<label>Text area</label>
<textarea class="form-control" rows="3"></textarea>
</div>
</div> -->
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
<!-- /.col-lg-6 (nested) -->
<!-- /.col-lg-6 (nested) -->
<!-- /.row (nested) -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#add_customer').validate({
rule: {
firstname: {
required: true,
}
},
messages: {
firstname: {
required:"firstname name cannot be blank."
}
},
});
});
</script>
#endsection
create list view customer_list.blade.php
#extends('theme.default')
#section('content')
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Users
<a class="pull-right btn btn-primary" href="<?php echo url('customer/add') ?>">Add Customer</a></h1>
</div>
<!-- /.col-lg-12 -->
</div>
<form action="<?php echo url('customer/index')?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="pull-right btn btn-primary" href="<?php echo url('customer/index') ?>">view all</button>
<div class="pull-right col-lg-3 input-group custom-search-form">
<input class="form-control" name="search" placeholder="Search..." type="text" value="{{ request('search') }}">
<span class="input-group-btn ">
<button class="btn btn-default" type="submit">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<input type="hidden" value="{{request('field')}}" name="field"/>
<input type="hidden" value="{{request('sort')}}" name="sort"/>
<!-- <button type="button" class="pull-right btn btn-primary">Add Customer</button> -->
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>Iamge</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=firstname&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
FirstName
</a>
{{request('field','firstname')=='firstname'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=lastname&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
LastName
</a>
{{request('field','lastname')=='lastname'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=email&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Email
</a>
{{request('field','email')=='email'?(request('sort','asc')=='asc'?'▴':'▾'):''}}</th>
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=phone&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Phone Number
</a>
{{request('field','phone')=='phone'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
#php
$i=1;
#endphp
<?php foreach ($customers as $customer)
{
?>
<tr>
<td><?php echo $i++;?></td>
<td> <img height="50px" width="50px" class="user-pic" src="<?php echo asset("/storage/uploads/$customer->image")?>"></td>
<td><?php echo $customer->firstname;?></td>
<td><?php echo $customer->lastname;?></td>
<td><?php echo $customer->email;?></td>
<td><?php echo $customer->phone;?></td>
<td><a href ='edit/<?php echo $customer->id?>'>Edit</a></td>
<td><a href ='delete/<?php echo $customer->id?>'>Delete</a></td>
</tr>
<?php
}
?>
</tbody>
</table>
<nav>
<ul class="pagination justify-content-end pull-right">
{{$customers->links('vendor.pagination.bootstrap-4')}}
</ul>
</nav>
</form>
#endsection
create edit form customer_edit.blade.php
#extends('theme.default')
#section('content')
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script> -->
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Customer</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<!-- #if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif -->
<form role="form" action="{{ url('customer/update', $customers->id)}}" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $customers->firstname;?>" class="form-control" placeholder="Firstname">
<span class="text-danger">{{ $errors->first('firstname') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('lastname') ? 'has-error' : '' }}">
<label for="lastname">Lastname</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $customers->lastname;?>" class="form-control" placeholder="Lastname">
<span class="text-danger">{{ $errors->first('lastname') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
<label for="email">Email</label>
<input type="text" name="email" id="email" value="<?php echo $customers->email;?>" class="form-control" placeholder="Email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}">
<label for="phone">Contact Number</label>
<input type="text" name="phone" id="phone" value="<?php echo $customers->phone;?>" class="form-control" placeholder="Contact Number">
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class= "col-lg-6">
<div class="form-group">
<label>Image</label>
<div class="fileinput-preview thumbnail" id="profile" data-trigger="fileinput" style="width: 60px; height: 60px;">
<img height="90px" width="70px" class="user-pic" src="<?php echo asset("/storage/uploads/$customers->image")?>">
</div>
<input type="file" name="image" id="image">
</div>
</div>
<!-- <div class= "col-lg-6">
<div class="form-group">
<label>Text area</label>
<textarea class="form-control" rows="3"></textarea>
</div>
</div> -->
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
<!-- /.col-lg-6 (nested) -->
<!-- /.col-lg-6 (nested) -->
<!-- /.row (nested) -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection
create Model Customer.php
<?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function SignIn($email,$password)
{
$sql=DB::table('customers')->where('email',$email)->where('password',$password)->get();
return $sql;
}
}
create routing in web.php
Route::get('home/my-home', 'HomeController#myHome');
Route::get('customer/index', 'CustomerController#index');
Route::get('customer/add', 'CustomerController#add');
Route::post('customer/add_record', 'CustomerController#add_record');
Route::get('customer/edit/{id}', 'CustomerController#edit');
Route::post('customer/update/{id}', 'CustomerController#update');
Route::get('customer/delete/{id}','CustomerController#delete');
Route::post('customer/index','CustomerController#index');
Route::get('customer/login','CustomerController#login');
Route::post('customer/do_login','CustomerController#do_login');
for validation create function in AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
return substr($value, 0, 3) == '+91';
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
Create Routes
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/role', 'RoleController#index')->name('role');
Route::get('/create', 'RoleController#create')->name('role.create');
Route::post('/store', 'RoleController#store')->name('role.store');
Route::get('/edit/{id}', 'RoleController#edit')->name('role.edit');
Route::post('/update/{id}', 'RoleController#update')->name('role.update');
Route::any('/destroy/{id}', 'RoleController#destroy')->name('role.destroy');
Create Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Role;
use Validate;
use Collective\Html\FormFacade;
class RoleController extends Controller
{
public function index(){
$roles = Role::all();
return view('role.index',compact('roles'));
}
public function create(){
return view('role.create');
}
public function store(Request $request)
{
request()->validate([
'name' => 'required',
]);
Role::create($request->all());
return redirect()->route('role')
->with('success','Role created successfully');
}
public function edit($id){
$roles = Role::find($id);
return view('role.edit',compact('roles'));
}
public function update(Request $request, $id){
request()->validate([
'name' => 'required',
]);
Role::find($id)->update($request->all());
return redirect()->route('role')
->with('success','Role updated successfully');
}
public function destroy($id)
{
Role::find($id)->delete($id);
return redirect()->route('role')
->with('success','Role updated successfully');
}
}
Create Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $fillable = [ 'name' ];
}
create layoyt file in layouts folder
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.5 CRUD Application</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
#yield('content')
</div>
</body>
</html>
create index.blade.php
#extends('layouts.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Role</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('role.create') }}"> Create New role</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th width="280">Action</th>
</tr>
#foreach ($roles as $role)
<tr>
<td>{{ $role->id }}</td>
<td>{{ $role->name}}</td>
<td>
<a class="btn btn-primary" href="{{ route('role.edit',$role->id) }}">Edit</a>
<form action="{{ route('role.destroy', $role->id) }}" method="DELETE">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
<!-- <button class="deleteRecord" data-id="{{ $role->id }}" >Delete Record</button> -->
</td>
</tr>
#endforeach
</table>
#endsection
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$(".deleteRecord").click(function(){
var id = $(this).data("id");
//var token = $("meta[name='csrf-token']").attr("content");
$.ajax(
{
url: "destroy/"+id,
type: 'Post',
data: { "id": id, "_token": "{{ csrf_token() }}",},
dataType: "JSON",
success: function (){
console.log("it Works");
}
});
});
});
</script>
Create create.blade.php
#extends('layouts.layout')
#section('content')
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Role</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form role="form" action="{{ route('role.store') }}" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Name">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
</div>
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection
Create edit.blade.php
#extends('layouts.layout')
#section('content')
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Role</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form role="form" action="{{ route('role.update',$roles->id) }}" id="update_role" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" value="<?php echo $roles->name ?>" placeholder="Name">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
</div>
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection