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
Related
I have been having a 404 error message on my livewire Laravel project anytime I type an input. It was working perfectly fine on localhost but was giving this error of GET https://chat.mhminternationaltv.com/livewire/livewire.js?id=83b555bb3e243bc25f35 net::ERR_ABORTED 404 on the console.
My asset_url in Livewire.php in my config folder points to my subdomain folder
`'asset_url' => "https://chat.mhminternationaltv.com",
If I modify it to
'asset_url' => "https://chat.mhminternationaltv.com/vendor", I get a 404 error on any of the livewire powered inputs. With this error on the console
POST https://chat.mhminternationaltv.com/vendor/livewire/message/customer 404
With details of
value # index.js:32
sendMessage # index.js:221
value # index.js:231
later # debounce.js:8
setTimeout (async)
(anonymous) # debounce.js:12
value # index.js:204
callback # node_initializer.js:87
(anonymous) # index.js:532
setTimeout (async)
(anonymous) # index.js:531
My Http/Livewire/Sale.php is
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Cart;
use App\Models\Product;
use App\Models\User;
use Auth;
class Sale extends Component
{
public $order, $products = [], $product_code, $message = '', $productIncart;
public $pay_money = '', $balance = '';
public function mount() {
$this->products = Product::all();
$this->productIncart = Cart::all();
}
public function InsertoCart() {
$countProduct = Product::where('id', $this->product_code)->first();
if (!$countProduct) {
return $this->message = 'Product Not Found';
}
$countCartProduct = Cart::where('product_id', $this->product_code)->count();
if ($countCartProduct > 0) {
return $this->message = 'Product '.$countProduct->name. ' already exists in cart!';
}
$add_to_cart = new Cart;
$add_to_cart->product_id = $countProduct->id;
$add_to_cart->product_qty = 1;
$add_to_cart->product_price = $countProduct->price;
$add_to_cart->user_id = Auth::user()->id;
// $add_to_cart->user_id = 0;
$add_to_cart->save();
$this->productIncart->prepend( $add_to_cart);
$this->product_code = ' ';
return $this->message = "Product Added Successfully!";
// dd($countProduct);
}
public function IncrementQty($cartId)
{
$carts = Cart::find($cartId);
$carts->increment('product_qty', 1);
$updatePrice = $carts->product_qty * $carts->product->price;
$carts->update(['product_price' => $updatePrice]);
$this->mount();
}
public function DecrementQty($cartId)
{
$carts = Cart::find($cartId);
if ($carts->product_qty == 1) {
return session()->flash('info', $carts->product->name. ' Quantity cannot be less than 1, add quantity or remove product from cart!!!');
}
$carts->decrement('product_qty', 1);
$updatePrice = $carts->product_qty * $carts->product->price;
$carts->update(['product_price' => $updatePrice]);
$this->mount();
}
public function removeProduct($cartId) {
$deleteCart = Cart::find($cartId);
$deleteCart->delete();
$this->message = "Product removed from cart!";
$this->productIncart = $this->productIncart->except($cartId);
}
public function render()
{
if ( $this->pay_money != '') {
$totalAmount = $this->pay_money - $this->productIncart->sum('product_price');
$this->balance = $totalAmount;
}
return view('livewire.sale');
}
}
My views/livewire/sale.php is
<div class="content">
<div class="animated fadeIn">
<!-- Sales Table -->
<div class="row justify-content-center">
<div class="col-lg-10">
<div class="card">
<div class="card-header">
<h5>Sales</h5>
</div>
<!-- <form action="{{ url('/new-sale') }}" method="post">{{ csrf_field() }} -->
<div class="card-body card-block">
<div class="my-2">
<form wire:submit.prevent="InsertoCart">
<input wire:model="product_code" type="text" id="" name="" placeholder="Scan Product Barcode here" class="form-control">
</form>
</div>
#if (session()->has('success'))
<div class="alert alert-success alert-block">{{ session('success') }}</div>
#elseif (session()->has('info'))
<div class="alert alert-success alert-block">{{ session('info') }}</div>
#elseif (session()->has('error'))
<div class="alert alert-danger alert-block">{{ session('error') }}</div>
#endif
<!-- {{ $productIncart }} -->
<table class="table table-striped table-bordered">
<thead>
<tr>
<th></th>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
<th colspan="6">Total</th>
<!-- <th>
<a class="btn btn-sm btn-success add_more"><i class="fa fa-plus"></i></a>
</th> -->
</tr>
</thead>
<tbody class="addMoreProduct">
#foreach($productIncart as $key=> $cart)
<tr>
<td class="no">{{ $key + 1}}</td>
<td width="30%">
<input type="text" value="{{ $cart->product->name }}" class="form-control">
</td>
<td>
<input type="number" value="{{ $cart->product->price }}" class="form-control">
</td>
<td width="15%">
<div class="row">
<div class="col-md-2">
<button wire:click.prevent="IncrementQty({{ $cart->id }})" class="btn btn-sm btn-success"> + </button>
</div>
<div class="col-md-1">
<label for="">{{ $cart->product_qty }}</label>
</div>
<div class="col-md-2">
<button wire:click.prevent="DecrementQty({{ $cart->id }})" class="btn btn-sm btn-danger"> - </button>
</div>
</div>
</td>
<td>
<input type="number" value="{{ $cart->product_qty * $cart->product->price }}" class="form-control total_amount">
</td>
<td>
<i class="fa fa-times"></i>
</td>
</tr>
#endforeach
</tbody>
</table><br>
<form action="{{ url('/sales-cashier') }}" method="post">{{ csrf_field() }}
#foreach($productIncart as $key=> $cart)
<input type="number" hidden value="{{ $cart->product->id }}" name="product_id[]" class="form-control">
<input type="number" hidden value="{{ $cart->product->price }}" name="price[]" class="form-control price">
<input type="number" hidden value="{{ $cart->product_qty }}" name="quantity[]">
<input type="number" hidden value="{{ $cart->product_qty * $cart->product->price }}" name="total_amount[]" class="form-control total_amount">
#endforeach
<div>
<div class="form-group">
<div class="input-group">
<h3>TOTAL: <b>{{ $productIncart->sum('product_price') }}</b></h3>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="number" wire:model="pay_money" class="form-control" id="paid_amount" name="paid_amount" placeholder="Amount Paid">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="number" wire:model="balance" class="form-control" id="balance" name="balance" placeholder="Change" readonly>
</div>
</div>
<div class="row">
<div class="col-auto d-flex justify-content-around">
<div class="p-2 flex-fill">
<button type="submit" class="btn btn-lg btn-info btn-block">
SELL
</button>
</div>
<div class="p-2 flex-fill">
<button type="button" onClick="PrintReceiptContent('print')" class="btn btn-lg btn-dark btn-block"><i class="fa fa-print"></i>
Print Receipt
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<!-- </form> -->
</div>
</div>
<!-- Sales Table -->
</div>
</div>
My routes.php is
Route::group(['middleware' => ['frontlogin']], function () {
Route::match(['post', 'get'], '/', 'frontController#index');
Route::match(['post', 'get'], '/sales', 'frontController#addSale');
Route::post('/sales-cashier', 'frontController#store');
Route::match(['get', 'post'], '/settings', 'UsersController#updatePassword');
});
My Controller
class frontController extends Controller
{
public function index(){
return view('index');
}
public function addSale() {
$products = Product::all();
$sales = Sale::all();
//lastorder
$lastID = Transaction::max('customer_id');
$receipts = Sale::where('customer_id', $lastID)->get();
return view('sales.new_sale')->with(compact('products', 'sales', 'receipts'));
}
public function store(Request $request) {
//return $request->all();
DB::transaction(function () use ($request){
$customers = new Customer;
$customers->name = "customer";
$customers->save();
$customer_id = $customers->id;
for ($product_id = 0; $product_id < count($request->product_id); $product_id++) {
$sales = new Sale;
$sales->customer_id = $customer_id;
$sales->product_id = $request->product_id[$product_id];
$sales->quantity = $request->quantity[$product_id];
$sales->price = $request->total_amount[$product_id];
$sales->save();
}
$transactions = new Transaction;
$transactions->customer_id = $customer_id;
$transactions->user_id = Auth::user()->id;
// $transactions->user_id = 0;
$transactions->total = $request->paid_amount;
$transactions->save();
Cart::truncate();
$products = Product::all();
$sales = Sale::where('customer_id', $customer_id)->get();
$orderedBy = Customer::where('id', $customer_id)->get();
});
return back()->with('success', 'Sale successfull. Please print your receipt!');
}
public function receipt(){
return view('sales.receipt');
}
}
Hello friends
I'm a new in laravel framework am trying to build a crud app so got this issue When i click Edit btn in the index page which calls data in specific ID to edit it well it shows "error 404 page not found" i still can't find where the problem is so please help
Product controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\product;
use Illuminate\Support\Facades\DB;
/*call product by specific id to update */
public function edit($id){
$product = DB::table('products')->where('id',$id)->first();
return view('product.edit',compact('product'));
}
/* product update */
public function update(request $request ,$id){
$oldlogo = $request->old_logo;
$data = array();
$data['product_name'] = $request->product_name;
$data['product_code'] = $request->product_code;
$data['product_details'] = $request->product_details;
$image = $request->file('product_logo');
if ($image){
unlink($oldlogo);
$image_name = date('dmy_H_s_i');
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/media/';
$image_url = $upload_path.$image_full_name;
$data['product_logo'] = $image_url;
$success =$image->move($upload_path,$image_full_name);
$data['product_logo'] =$image_url;
$product = DB::table('products')->where('id'.$id) -> update($data);
}
return redirect()->route('product.index')
->with('success','Product updated successfully');
}
edit btn`
<a class="btn btn-primary" href="{{ URL :: to ('edit/product'.$pro->id) }}">Edits</a>
edit page
#extends('product.layout')
#section('content')
<br><br><br>
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Product</h2>
</div>
</div>
<br><br><br>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('product.index') }}">Back</a>
</div>
<form action="" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-row">
<div class="col-xs-12 col-xm-12 col-md-12">
<div class="form-group">
<strong>Product name</strong>
<input type="text" name="product_name" calss="form-control" value="{{ $product ->product_name }}">
</div>
</div>
<div class="col-xs-12 col-xm-12 col-md-12">
<div class="form-group">
<strong>Product Code</strong>
<input type="text" name="product_code" calss="form-control" value="{{ $product ->product_code }}">
</div>
</div>
<div class="col-xs-12 col-xm-12 col-md-12">
<div class="form-group">
<strong> Detials </strong>
<textarea class="form-control" name="Details" style="height:150px" >
{{ $product ->product_details" }}</textarea>
</div>
<div class="col">
<div class="form-group">
<strong>Product image</strong>
<input type="file" name="logo">
</div>
</div>
<div class="col">
<div class="form-group">
<strong>Product old image</strong>
<img src ="{{ URL::to($product->product_logo) }}" height="70px" width="80px" alt="logo">
<input type="hidden" name=" old_logo" value="{{ $product->product_logo }}">
</div>
</div>
<button type="button" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
#endsection
** edit Route **
Route::get('edit/product/{id}','ProductController#edit');
Route::post('update/product/{id}','ProductController#update');
laravel Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class product extends Model
{
protected $fillable = [
'product_name', 'product_details', 'product_code','product_logo'
];
}
I think your problem is right here: {{ URL :: to ('edit/product'.$pro->id) }} because its going to print for example this: /edit.product23. What you want is /edit/product/23, so change your URL to {{ URL::to('edit/product/'.$pro->id) }} or {{ url('edit/product/'.$pro->id) }}. Also make sure you set the route like this Route::get('/edit/product/{id}, 'ControllerName#edit'); in your web.php route file.
iam new in laravel i have problem to add data in data base using laravel , i get only validation response in form but after i submit data i don't get any response only just page refresh . without any message appear in view
ac any on help me ?
this is man categories request for validation
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MaincategoryRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'id' => 'integer|required',
'name' => 'min:2|required|max:50|unique:category_translations',
'slug' => 'required|unique:categories,slug,'.$this->id,
'url' => 'required|url',
'status' => 'integer'
];
}
// validation messages
public function messages()
{
return [
'id.required'=>trans('dashboard\validate.required'),
'id.integer'=>trans('dashboard\validate.integer'),
'id.exists'=>trans('dashboard\validate.exists'),
'name.required'=>trans('dashboard\validate.required'),
'name.min'=>trans('dashboard\validate.min'),
'name.max'=>trans('dashboard\validate.max'),
'name.unique'=>trans('dashboard\validate.unique'),
'slug.required'=>trans('dashboard\validate.required'),
'slug.min'=>trans('dashboard\validate.min'),
'slug.max'=>trans('dashboard\validate.max'),
'slug.unique'=>trans('dashboard\validate.unique'),
'url.active_url'=>trans('dashboard\validate.url'),
'url.required'=>trans('dashboard\validate.required'),
'status.integer'=>trans('dashboard\validate.integer'),
];
}
}
this is my route in details
Route::get('create','MainCategoriesController#create') -> name('maincategories.create');
Route::post('store','MainCategoriesController#store') -> name('maincategories.store');
this is my controller in details
public function store(MaincategoryRequest $request )
{
try{
DB::beginTransaction();
// prepare data
$validatedData = array(
'name' =>$request->name,
'url' =>$request->url,
'slug' =>$request->slug,
'last_updated_by' =>auth('admin')->user()->id,
'created_by' =>auth('admin')->user()->id,
'created' =>time(),
);
//check if status is sent
$request->has('status') ? $validatedData['status'] = 1: $validatedData['status'] = 2;
// check if category is exist
$add = Category::create($validatedData);
if (!$add){
return redirect()->route('maincategories.create')->with(['error'=> trans('dashboard\messages.addfailed')]);
}
// start add translated data
$add->name=$request->name;
$add->save();
return redirect()->back()->with('success',trans('dashboard\messages.save'));
DB::commit();
}catch (\Exception $ex){
return redirect()->back()->with('error',trans('dashboard\messages.addfailed'));
DB::rollBack();
}
}
this is my view in details
#extends('layouts.admin')
#section("title",trans('dashboard\category.title-add'))
#section('content')
<div class="app-content content">
<div class="content-wrapper">
<div class="content-header row">
<div class="content-header-left col-md-6 col-12 mb-2">
<div class="row breadcrumbs-top">
<div class="breadcrumb-wrapper col-12">
<ol class="breadcrumb">
<li class="breadcrumb-item"> {{trans('dashboard\messages.home')}}
</li>
<li class="breadcrumb-item active">{{trans('dashboard\category.title-add')}}
</li>
</ol>
</div>
</div>
</div>
</div>
<div class="content-body">
<!-- Basic form layout section start -->
<section id="basic-form-layouts">
<div class="row match-height">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4 class="card-title" id="basic-layout-form"> {{trans('dashboard\category.title-add')}} </h4>
<a class="heading-elements-toggle"><i
class="la la-ellipsis-v font-medium-3"></i></a>
<div class="heading-elements">
<ul class="list-inline mb-0">
<li><a data-action="collapse"><i class="ft-minus"></i></a></li>
<li><a data-action="reload"><i class="ft-rotate-cw"></i></a></li>
<li><a data-action="expand"><i class="ft-maximize"></i></a></li>
<li><a data-action="close"><i class="ft-x"></i></a></li>
</ul>
</div>
</div>
#include('dashboard.includes.alerts.success')
#include('dashboard.includes.alerts.errors')
<div class="card-content collapse show">
<div class="card-body">
<form class="form"
action="{{route('maincategories.store')}}"
method="post"
enctype="multipart/form-data">
#csrf
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="projectinput1"> {{trans('dashboard\category.name')}} </label>
<input type="text" value="{{old('name')}}"
id="name"
class="form-control"
placeholder=" "
name="name">
#error("name")
<span class="text-danger">{{$message}}</span>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="projectinput1"> {{trans('dashboard\category.slug')}} </label>
<input type="text"
value="{{old('slug')}}"
id="email"
class="form-control"
placeholder=" "
name="slug">
#error("slug")
<span class="text-danger">{{$message}}</span>
#enderror
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="projectinput1"> {{trans('dashboard\category.url')}} </label>
<input type="text"
value="{{old('url')}}"
id="plain_value"
class="form-control"
placeholder=" "
name="url">
#error("url")
<span class="text-danger">{{$message}}</span>
#enderror
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label> {{trans('dashboard\category.image')}} </label>
<label id="projectinput7" class="file center-block">
<input type="file" id="file" name="image">
<span class="file-custom"></span>
</label>
#error('image')
<span class="text-danger">{{$message}}</span>
#enderror
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group mt-1">
<input type="checkbox" value="1"
name="status"
id="switcheryColor4"
class="switchery" data-color="success"
checked />
<label for="switcheryColor4"
class="card-title ml-1">{{trans('dashboard\messages.status')}} </label>
#error("status")
<span class="text-danger"> </span>
#enderror
</div>
</div>
</div>
<div class="form-actions">
<button type="button" class="btn btn-warning mr-1"
onclick="history.back();">
<i class="ft-x"></i> {{trans('dashboard\messages.back')}}
</button>
<button type="submit" class="btn btn-primary">
<i class="la la-check-square-o"></i> {{trans('dashboard\messages.save')}}
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- // Basic form layout section end -->
</div>
</div>
</div>
#stop
#section('script')
<script >
$(document).ready(function() {
//start update password
$("#EditPassword").submit(function(){
var formData = $(this).serialize();
var allData = formData + "&action=editPass";
$('#repassword_error').text('');
$('#password_error').text('');
$.ajax({
url: "{{url("admin/category/update_password/{id}")}}",
type:"PUT",
data: allData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
beforeSend:function(){
//alert(allData)
},
statusCode: {
404: function() {
alert( "page not found" );
},
},
success:function(valdata) {
//alert(valdata);
//alert("")
if(valdata.status == "success")
{
$("#updatePasswordResult").html(valdata.message);
setTimeout(function(){$('#changepassword').modal('hide');}, 2000);
}else{
$("#updatePasswordResult").html(valdata.message);
}
},
error: function (reject) {
var response = $.parseJSON(reject.responseText);
$.each(response.errors, function (key, val) {
$("#" + key + "_error").text(val[0]);
});
}
});
return false;
});
});
</script>
#stop
You don't need to use transaction here, However, move DB::commit before return .
besides, check $guarded and $fillable in your model.
also you can dd($ex->getMessage()) to track the error.
I am new to Laravel 5.5 and I am trying to create a CRUD. Right now I am experiencing a views error. I am not sure where I went wrong. If someone point me in the right direction it would be greatly appreciated.
I have tried a few different attempts at resolving this issue such as changing my routes to Uppercase L instead of lower case l for leads to have it follow the directory casing but no avail.
My error
Route [leads.create] not defined. (View: .../resources/views/leads/index.blade.php)
Error's source coming from my index.blade.php file
<div class="pull-right">
<div class="btn-group"> <a href="{{ route('leads.create') }}" class="btn btn-info" >Add New</a> </div>
</div>
My Tree
views
|-- leads
| |-- create.blade.php
| |-- edit.blade.php
| |-- index.blade.php
| `-- show.blade.php
My Web.php
// Leads
Route::resource('Leads','LeadsController');
Route::get('leads/index', function () { return view('Leads.index'); });
Route::get('leads/create', function () { return view('Leads.create'); });
My Controller
namespace App\Http\Controllers;
use App\Leads;
use Illuminate\Http\Request;
class LeadsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$videos = Leads::orderBy('id','DESC')->paginate(5);
return view('leads.index',compact('leads'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('leads.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'first_name' => 'required',
'primary_phone' => 'required',
]);
Leads::create($request->all());
return redirect()->route('leads.index')
->with('success','Lead created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$leads = Leads::find($id);
return view('leads.show',compact('leads'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$leads = Leads::find($id);
return view('leads.edit',compact('leads'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'first_name' => 'required',
'primary_phone' => 'required',
]);
Leads::find($id)->update($request->all());
return redirect()->route('leads.index')
->with('success','Lead updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
Leads::find($id)->delete();
return redirect()->route('leads.index')
->with('success','Lead deleted successfully');
}
}
You could use url() to go to a url link.
<div class="pull-right">
<div class="btn-group"> <a href="{{ url('leads/create') }}" class="btn btn-info" >Add New</a> </div>
</div>
Or you could use named route
Route::get('leads/create', function () {
return view('Leads.create');
})->name('leads.create');
Create Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Contact;
use Hash;
class ContactController extends Controller
{
public function index(Request $request)
{
$search = $request->get('search');
$field = $request->get('field') != '' ? $request->get('field') : 'first_name';
$sort = $request->get('sort') != '' ? $request->get('sort') : 'asc';
$contacts = new Contact();
$contacts = $contacts->where('first_name', 'like', '%' . $search . '%')
->orderBy($field, $sort)
->paginate(10)
->withPath('?search=' . $search . '&field=' . $field . '&sort=' . $sort);
return view('contacts.index', compact('contacts'))
->with('i', ($request->input('page', 1) - 1) * 10);
}
public function create()
{
return view('contacts.create');
}
public function store(Request $request)
{
$request->validate([
'first_name'=>'required|min:3|max:50',
'last_name'=>'required|min:3|max:50',
'email'=>'required|email|unique:contacts',
'phone' => 'required|numeric|phone',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password'
]);
$contact = new Contact([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'job_title' => $request->get('job_title'),
'city' => $request->get('city'),
'country' => $request->get('country'),
'phone' => $request->get('phone'),
'password' => $request->get('password')
]);
$contact->save();
return redirect('/contacts/index')->with('success', 'Contact saved!');
}
public function edit($id)
{
$contact = Contact::find($id);
//print_r($contact);exit;
return view('contacts.edit', compact('contact'));
}
public function update(Request $request, $id)
{
$request->validate([
'first_name'=>'required|min:3|max:50',
'last_name'=>'required|min:3|max:50',
'email'=>'required|email',
'city' => 'required'
]);
$contact = Contact::find($id);
$contact->first_name = $request->get('first_name');
$contact->last_name = $request->get('last_name');
$contact->email = $request->get('email');
$contact->job_title = $request->get('job_title');
$contact->city = $request->get('city');
$contact->country = $request->get('country');
$contact->phone = $request->get('phone');
$contact->password = $request->get('password');
$contact->save();
return redirect('/contacts/index')->with('success', 'Contact updated!');
}
public function delete($id)
{
$contact = Contact::find($id);
$contact->delete();
return redirect('/contacts/index')->with('success', 'Contact deleted!');
}
}
Create Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'city',
'country',
'job_title',
'phone',
'password'
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
}
Create routes in web.php
Route::get('contacts/index', 'ContactController#index');
Route::get('contacts/create', 'ContactController#create');
Route::post('contacts/store', 'ContactController#store');
Route::get('contacts/edit/{id}', 'ContactController#edit');
Route::post('contacts/update/{id}', 'ContactController#update');
Route::post('contacts/delete/{id}','ContactController#delete');
Route::post('contacts/index', 'ContactController#index');
create base.blade.php in resources/views folder
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 5.8 & MySQL CRUD Tutorial</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
#yield('main')
</div>
<script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>
Create index.blade.php in contacts folder
#extends('base')
#section('main')
<div class="col-sm-12">
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
#endif
</div>
<div class="row">
<div class="col-sm-12">
<h1 class="display-3">Contacts</h1>
<a class="pull-right btn btn-primary" href="<?php echo url('contacts/create') ?>">Add Contacts</a>
</div>
</div>
<div class="row">
<form action="<?php echo url('contacts/index')?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="pull-right btn btn-primary" href="<?php echo url('contacts/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"/>
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=first_name&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Name
</a>
{{request('field','first_name')=='first_name'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=email&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Email
</a>
{{request('field','email')=='email'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=job_title&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Job Title
</a>
{{request('field','job_title')=='job_title'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=city&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
City
</a>
{{request('field','city')=='city'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td>
<a href="{{url('contacts/index')}}?search={{request('search')}}&field=country&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Country
</a>
{{request('field','country')=='country'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</td>
<td colspan = 2>Actions</td>
</tr>
</thead>
<tbody>
#foreach($contacts as $contact)
<tr>
<td>{{$contact->id}}</td>
<td>{{$contact->first_name}} {{$contact->last_name}}</td>
<td>{{$contact->email}}</td>
<td>{{$contact->job_title}}</td>
<td>{{$contact->city}}</td>
<td>{{$contact->country}}</td>
<td>
Edit
</td>
<td>
<form action="delete/<?php echo $contact->id?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</form>
</div>
#endsection
Create form create.blade.php
#extends('base')
#section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Add a contact</h1>
<div>
<form method="post" action="{{ url('contacts/store') }}">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" name="first_name"/>
<span class="text-danger">{{ $errors->first('first_name') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" name="last_name"/>
<span class="text-danger">{{ $errors->first('last_name') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email"/>
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="phone">Phone:</label>
<input type="text" class="form-control" name="phone"/>
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="city">City:</label>
<input type="text" class="form-control" name="city"/>
<span class="text-danger">{{ $errors->first('city') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="country">Country:</label>
<input type="text" class="form-control" name="country"/>
<span class="text-danger">{{ $errors->first('country') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password"/>
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="confirm_password">Confrim Password:</label>
<input type="password" class="form-control" name="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 for="job_title">Job Title:</label>
<input type="text" class="form-control" name="job_title"/>
<span class="text-danger">{{ $errors->first('job_title') }}</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Add contact</button>
</form>
</div>
</div>
</div>
#endsection
Create edit.blade.php
#extends('base')
#section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Update a contact</h1>
<form method="post" action="{{ url('contacts/update', $contact->id) }}">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" name="first_name" value="<?php echo $contact->first_name ?>" />
<span class="text-danger">{{ $errors->first('first_name') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" name="last_name" value="<?php echo $contact->last_name ?>" />
<span class="text-danger">{{ $errors->first('last_name') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email" value="<?php echo $contact->email ?>" />
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="phone">Phone:</label>
<input type="text" class="form-control" name="phone" value="<?php echo $contact->phone ?>" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="city">City:</label>
<input type="text" class="form-control" name="city" value="<?php echo $contact->city ?>" />
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="country">Country:</label>
<input type="text" class="form-control" name="country" value="<?php echo $contact->country ?>" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="job_title">Job Title:</label>
<input type="text" class="form-control" name="job_title" value='<?php echo $contact->job_title;?>' />
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
#endsection
Phone number validation put this code in AppServiceProvider.php in boot function
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
return substr($value, 0, 3) == '+91';
});
Link for Crud Operation - https://www.techiediaries.com/php-laravel-crud-mysql-tutorial/
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