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');
}
}
Related
I have come across a bug on my website and I am baffled as to how to fix it.. basically I have a view to create courses, I type a course title and secondly assign an instructor to that course and click save. But when i return to my index page.. the instructor i assigned is completely different. It appears there must be an issue with my select but I am not sure how to go about fixing it.. I am new to laravel so any help is greatly appreciated.
I have added a picture to try to further explain my issue, here i have selected an instructor -
And when i return to my index page, the newly created course 'test' has the admin user assigned... I am very confused -
create.blade.php
#extends('layouts.app')
#section('content')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Course</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.courses.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label class="required" for="name">Course Title</label>
<input class="form-control" type="text" name="title" id="id" value="{{ old('title', '') }}" required>
#if($errors->has('name'))
<div class="invalid-feedback">
{{ $errors->first('name') }}
</div>
#endif
</div>
<div class="form-group {{ $errors->has('instructors') ? 'has-error' : '' }}">
<label class="required" for="name">Instructors</label>
<select class="form-control select2" name="instructors[]" id="instructors" multiple>
#foreach($instructors as $id => $instructors)
<option value="{{ $id }}" {{ in_array($id, old('instructors', [])) ? 'selected' : '' }}>{{ $instructors }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<button class="btn btn-danger" type="submit">
Save
</button>
</div>
</div>
</form>
</div>
</div>
#endsection
index.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-10">
<p>
#can('create_courses')
<button type="button" class="btn btn-success">Create Course</button>
#endcan('create_courses')
</p>
<div class="card">
<div class="card-header">Courses</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Course Title</th>
<th>Instructor</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($course as $course)
<tr>
<th scope="row">{{ $course->id }}</th>
<td>{{ $course->title}}</td>
<td>{{ implode (', ', $course->instructors()->pluck('name')->toArray()) }}</td>
<td>
#can('edit_courses')
<a class="btn btn-xs btn-secondary" href="{{ route('admin.modules.index', $course->id) }}">
Modules
</a>
#endcan
</td>
<td>
#can('edit_courses')
<a class="btn btn-xs btn-primary" href="{{ route('admin.courses.edit', $course->id) }}">
Edit
</a>
#endcan
</td>
<td>
#can('delete_courses')
<form action="{{ route('admin.courses.destroy', $course->id) }}" method="POST" onsubmit="return confirm('Confirm delete?');" style="display: inline-block;">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-xs btn-danger" value="Delete">
</form>
#endcan
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- <div class="col-md-2 col-lg-2">
<div class="list-unstyled">
Courses
Modules
</div>
</div> -->
</div>
</div>
#endsection
CoursesController;
<?php
namespace App\Http\Controllers\Admin;
use Gate;
use App\User;
use App\Course;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
class CoursesController extends Controller
{
public function __construct()
{
//calling auth middleware to check whether user is logged in, if no logged in user they will be redirected to login page
$this->middleware('auth');
}
public function index()
{
if(Gate::denies('manage_courses')){
return redirect(route('home'));
}
$courses = Course::all();
return view('admin.course.index')->with('course', $courses); //pass data down to view
}
public function create()
{
if(Gate::denies('create_courses')){
return redirect(route('home'));
}
$instructors = User::whereHas('role', function ($query) {
$query->where('role_id', 2); })->get()->pluck('name'); //defining instructor variable to call in create.blade.php. Followed by specifying that only users with role_id:2 can be viewed in the select form by looping through the pivot table to check each role_id
return view('admin.course.create', compact('instructors')); //passing instructor to view
}
public function store(Request $request)
{
$course = Course::create($request->all()); //request all the data fields to store in DB
$course->instructors()->sync($request->input('instructors', [])); //input method retrieves all of the input values as an array
if($course->save()){
$request->session()->flash('success', 'The course ' . $course->title . ' has been created successfully.');
}else{
$request->session()->flash('error', 'There was an error creating the course');
}
return redirect()->route ('admin.courses.index');
}
public function destroy(Course $course)
{
if(Gate::denies('delete_courses'))
{
return redirect (route('admin.course.index'));
}
$course->delete();
return redirect()->route('admin.courses.index');
}
public function edit(Course $course)
{
if(Gate::denies('edit_courses'))
{
return redirect (route('admin.courses.index'));
}
$instructors = User::whereHas('role', function ($query) {
$query->where('role_id', 2); })->get()->pluck('name');
//return view('admin.course.edit', compact('instructors'));
return view('admin.course.edit', compact('instructors'))->with([
'course' => $course
]);
}
public function update(Request $request, Course $course)
{
$course->update($request->all());
if ($course->save()){
$request->session()->flash('success', $course->title . ' has been updated successfully.');
}else{
$request->session()->flash('error', 'There was an error updating ' . $course->title);
}
return redirect()->route('admin.courses.index');
}
public function show(Course $course)
{
return view('admin.course.show', compact('course'));
}
}
Referring to latest comment -
you are updating data with key not id
try this
in controller
$instructors = User::whereHas('role', function ($query) {
$query->where('role_id', 2); })->select('id','name')->get();
in blade
you will need instructors->id to update right value
#foreach($instructors as $id => $instructor)
<option value="{{ $instructor->id }}" {{ in_array($id, old('instructors', [])) ? 'selected' : '' }}>{{ $instructor->name }}
</option>
#endforeach
I'm beginner in Laravel. I'm using ajax. I want to display data of students (eleves) in my select option by first name (prénom) last name (nom), but the problem that it displays only the first name (prénom) without the last name (nom). However I need to associate first name and last name. Please help me.
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Note;
use App\Matiere;
use App\Eleve;
use App\Classe;
use DB;
class DropdownlistController extends Controller
{
public function index()
{
$notes = Note::all();
$matieres = Matiere::all();
$eleves = Eleve::all();
$classes = Classe::all();
$classes = DB::table("classes")->pluck("classe","id");
return view('admin.dropdownlists',compact('classes','notes','matieres','eleves'));
}
public function store(Request $request)
{
Note::create($request->all());
return redirect()->back();
}
public function getStateList(Request $request)
{
$eleves = DB::table("eleves")
->where("classe_id",$request->classe_id)
->pluck("nom" ,"prenom","id");
return response()->json($eleves);
}
public function getCityList(Request $request)
{
$matieres = DB::table("matieres")
->where("classe_id",$request->classe_id)
->pluck("nom_matiere","id");
return response()->json($matieres);
}
}
My view there I'm using my function ajax
#extends('layouts.admin')
#section('content')
<section class="wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-6">
<h2> ESpace de Gestion <b></b> des notes </h2>
</div>
<div class="col-sm-6">
<a href="#addEmployeeModal" class=" btn btn-success" data-toggle="modal"><i class="material-icons"></i>
<span>Ajouter un nouvelle note </span></a>
</div>
</div>
</div>
<div class="row mt">
#if(session()->has('success'))
<div class="alert alert-success">
{{session()->get('success')}}
</div>
#endif
<div class="col-lg-12">
<div class="content-panel">
<section id="no-more-tables">
<table class="table table-bordered table-striped table-condensed cf">
<thead class="cf">
<tr>
<th>id-note</th>
<th>Nom</th>
<th>classe</th>
<th>matiére</th>
<th>Note</th>
<th>les actions</th>
</tr>
</thead>
<tbody>
#foreach($notes as $note)
<tr>
<td class="numeric" data-title="id-parent">{{$note->id}}</td>
<td class="numeric"
data-title="id-parent">{{$note->eleve->nom}} {{$note->eleve->prenom}}</td>
<td class="numeric" data-title="id-parent">{{$note->classe->classe}}</td>
<td class="numeric" data-title="id-parent">{{$note->matiere->nom_matiere}}</td>
<td class="numeric" data-title="Login">{{$note->note}}</td>
<td>
<button href="#editEmployeeModal" class="btn btn-theme"
data-target="#editEmployeeModal " data-catid={{$note->id}} class="edit"
data-toggle="modal"><i class="material-icons" data-toggle="tooltip"
title="Edit"></i></button>
<button href="#deleteEmployeeModal" class="btn btn-theme"
data-target="#deleteEmployeeModal" data-catid="{{$note->id}}"
class="delete" data-toggle="modal"><i class="material-icons"
data-toggle="tooltip"
title="Delete"></i>
</button>
</td>
</tr>
</tbody>
#endforeach
</table>
<div class="text-center">
</div>
<div class="clearfix">
<div class="hint-text">Affichage de <b>5</b> sur <b>25</b> entrées</div>
<div id="addEmployeeModal" href="create" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{route('dropdownlists.store')}}" method="post">
{{csrf_field()}}
<div class="modal-header">
<h4 class="modal-title">Ajouter un éléve</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×
</button>
</div>
<div class="modal-body">
<div class="panel-body">
<div class="form-group">
<label for="title">Select classe:</label>
<select id="classe" name="classe" class="form-control"
style="width:350px">
<option value="" selected disabled>Select</option>
#foreach($classes as $key => $classe)
<option value="{{$key}}"> {{$classe}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="title">Select classe:</label>
<select id="eleve" name="eleve" class="form-control"
style="width:350px">
</select>
</div>
<div class="form-group">
<label for="title">Select matiere:</label>
<select id="matiere" name="matiere" class="form-control"
style="width:350px">
<option value="" selected disabled>Select</option>
</select>
</div>
<div class="form-group">
<label>la note </label>
<input type="text" id="note" name="note" class="form-control"
required>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal"
value="Annuler">
<input type="submit" class="btn btn-success" value="Ajouter">
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('js')
<script type="text/javascript">
$('#classe').change(function () {
var classeID = $(this).val();
if (classeID) {
$.ajax({
type: "GET",
url: "{{url('get-state-list')}}?classe_id=" + classeID,
success: function (res) {
if (res) {
$("#eleve").empty();
$("#eleve").append('<option>Select</option>');
$.each(res, function (key, value) {
$("#eleve").append('<option
value = "'+eleve.age+'" > '+value+' < /option>');
});
} else {
$("#eleve").empty();
}
}
});
} else {
$("#classe").empty();
$("#matiere").empty();
}
});
$('#classe').on('change', function () {
var classeID = $(this).val();
if (classeID) {
$.ajax({
type: "GET",
url: "{{url('get-city-list')}}?classe_id=" + classeID,
success: function (res) {
if (res) {
$("#matiere").empty();
$.each(res, function (key, value) {
$("#matiere").append('<option
value = "'+key+'" > '+value+' < /option>');
});
} else {
$("#matiere").empty();
}
}
});
} else {
$("#matiere").empty();
}
});
</script>
#endsection
Routes:
Route::resource('dropdownlists','DropdownlistController');
Route::get('get-state-list','DropdownController#getStateList');
Route::get('get-city-list','DropdownController#getCityList');
Laravel has a very powerful and very useful feature that will make this easy for you, mutators. By adding a 'fullName' mutator, you can do this in the model any time you want. Then, in your controllers, you can call the function as if it was a field.
So, on your Eleve model:
public function getFullNameAttribute(){
return $this->prenom. " " . $this->nom;
}
Then in any controller, like when you want to send these to a dropdown, you can just get your collection, and then transfer it into the array you need.
Get the collection:
$elevesCollection = \App\Eleve::orderBy('nom')->select('prenom', 'nom', 'id')->get();
Then, pull the full name and the id from the collection:
$eleves = $elevesCollection ->pluck('name', 'id')->toArray();
You can send that through to your form dropdown. Please double check my code / spelling, but this should do what you wish.
Basically, I want to solve this error
Missing required parameters for [Route: post.show] [URI: post/show/{id}]. (View: C:\xampp2\htdocs\galaxall\resources\views\index.blade.php)
I am trying to make a system on my site whereby users can post,view post comment on posts and reply.
When a usertypes the details of his post in http://localhost:8000/post/create,it is supposed to accept the values,insert it into the database and redirect to http://localhost:8000/posts/show and show a the list of posts ever 'posted' so that the user can view a post can comment and reply to comments about that post.
BUT
what currently happens is that after typing the details for the to-be post in
http://localhost:8000/post/create,it inserts into the db and then shows this error on laravel 'customised' error page:
Missing required parameters for [Route: post.show] [URI: post/show/{id}]. (View: C:\xampp2\htdocs\galaxall\resources\views\index.blade.php)
I have no clue what I'm doing wrong.
Please help
These are my code:
PostController.php
<?php
// PostController.php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use Auth;
use Stevebauman\Location\Facades\Location;
class PostController extends Controller
{
protected $fillable = [
'Uploader',
];
public function __construct()
{
return $this->middleware('auth');
}
public function create()
{
return view('post');
}
public function store(Request $request)
{
{
$post = new Post;
$post->title = $request->get('title');
$post->type = $request->get('type');
$post->description = $request->get('description');
$post->body = $request->get('body');
$post->UniqueId = str_random(16);
$post->Uploader = Auth::user()->name;
$post->Language = 'en';
$post->Location=Location::get()->countryCode;
$post->views = 0;
$post->Applauds = 0;
$post->Boos = 0;
$post->Tags = "hey";
if ($request->get('agegroup')) {
$post->agegroup = $request->get('agegroup');
} else {
$post->agegroup ='undefined';
}
$post->AllowComments = 'true';
$post->CommentsBg = 'default';
$post->Visibility = 'globally public';
$post->others = 'embeddable';
$post->save();
return redirect('posts');
}
}
public function index()
{
$posts = Post::all();
return view('index', compact('posts'));
}
public function show($id)
{
$post = Post::find($id);
return view('show', compact('post'));
}
}
CommentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Comment;
use App\Post;
class CommentController extends Controller
{
public function store(Request $request)
{
$comment = new Comment;
$comment->body = $request->get('comment_body');
$comment->user()->associate($request->user());
$post = Post::find($request->get('post_id'));
$post->comments()->save($comment);
return back();
}
}
Web.php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('logout', '\App\Http\Controllers\Auth\LoginController#logout');
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin', 'AdminController#index')->name('admin');
Route::get('/upload', 'UploadController#index')->name('upload');
Route::get('/post/create', 'PostController#create')->name('post.create');
Route::post('/post/store', 'PostController#store')->name('post.store');
Route::get('/posts', 'PostController#index')->name('posts');
Route::get('/post/show/{id}', 'PostController#show')->name('post.show');
Route::post('/comment/store', 'CommentController#store')->name('comment.add');
Route::post('/reply/store', 'CommentController#replyStore')->name('reply.add');
Route::match(['get', 'post'], 'imageupload', 'ImageController#Image');
Route::delete('delimage/{filename}', 'ImageController#Image');
post.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Post</div>
<div class="card-body">
<form method="post" action="{{ route('post.store') }}">
<div class="form-group">
#csrf
<label class="label">Post Title: </label>
<input type="text" name="title" class="form-control" required/>
</div>
<label class="label">Post Type </label>
<input type="text" name="type" class="form-control" required/>
<label class="label">Tags </label>
<input type="text" name="tags" class="form-control" required/>
<label class="label">Age-group(optional) </label>
<input type="text" name="agegroup" class="form-control" required/>
<div class="form-group">
<label class="label">Post Description </label>
<textarea name="description" rows="5" cols="20" class="form-control" required></textarea>
</div>
<div class="form-group">
<label class="label">Post Body: </label>
<textarea name="body" rows="10" cols="30" class="form-control" required></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
show.blade.php
<!-- show.blade.php -->
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<p><b>{{ $post->title }}</b></p>
<p>
{{ $post->body }}
</p>
<hr />
<h4>Display Comments</h4>
#foreach($post->comments as $comment)
<div class="display-comment">
<strong>{{ $comment->user->name }}</strong>
<p>{{ $comment->body }}</p>
</div>
#endforeach
<hr />
<h4>Add comment</h4>
<form method="post" action="{{ route('comment.add') }}">
#csrf
<div class="form-group">
<input type="text" name="comment_body" class="form-control" />
<input type="hidden" name="post_id" value="{{ $post->id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-warning" value="Add Comment" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
index.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<table class="table table-striped">
<thead>
<th>ID</th>
<th>Title</th>
<th>Action</th>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>
Show Post
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endsection
The second parameter of the route function should be an array of parameter name to value pairs, eg
<a href="{{ route('post.show', ['id' => $post]) }}" class="btn btn-primary">
Show Post
</a>
See https://laravel.com/docs/5.8/urls#urls-for-named-routes
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 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