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/
Related
i hope you are doing good.
i'am new to laravel and i searched a lot but no chance.
So i hava a form it contain fields to submit a comment here is the code :
<!-- comment -->
<div class="clearfix"></div>
<div class="margin-top-35"></div>
<div class="utf-inner-blog-section-title">
<h4><i class="icon-line-awesome-comments-o"></i> Laisse votre commentaire</h4>
</div>
<div class="margin-top-15"></div>
<input type="hidden" name="prop_id" id="prop_id" value="{{ $proprety->id }}">
<div id="add-comment">
<form class="add-comment" action="/commentannonce" method="POST">
#csrf
<input type="hidden" name="prop_id" value="{{ $proprety->id }}">
<fieldset>
<div class="row">
<div class="col-md-6">
<input type="text" placeholder="Nom Complet*" value="" name="nom"
required />
</div>
<div class="col-md-6">
<input type="email" placeholder="Adresse Email *" value="" name="email"
required />
</div>
<div class="col-md-6">
<input type="tel" placeholder="Numéro de téléphone *" value=""
name="telephone" required />
</div>
<div class="col-md-6">
<input type="text" placeholder="Sujet" value="" name="sujet"
required />
</div>
<div class="col-md-12">
<textarea cols="30" placeholder="Commentaire..." rows="2" name="commentaire" required></textarea>
</div>
</div>
</fieldset>
<div class="utf-centered-button">
<button type="submit" class="button">Submit Comment</button>
</div>
<div class="clearfix"></div>
</form>
</div>
<!-- comment -->
when i submit this form it store in the database normally.
here is my model for the comment
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Annoncecomment extends Model
{
use HasFactory;
protected $fillable = [
'prop_id',
'nom',
'telephone',
'email',
'sujet',
'commentaire',
];
}
and this is my controller for the comment :
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request){
$form_data = array(
'prop_id' => $request->prop_id,
'nom' =>$request->nom,
'telephone' => $request->telephone,
'sujet'=>$request->sujet,
'email' =>$request->email,
'commentaire'=>$request->commentaire,
);
$commentaire = Annoncecomment::create($form_data);
$user = User::first();
$commentaire = Annoncecomment::where('prop_id',$request->prop_id)->count();
$commentaires = Annoncecomment::where('prop_id',$request->prop_id)->orderBy('id','desc')->get();
$user = User::first();
return redirect('/proprety/'.$request->prop_id)->with([ 'commentaire'=>$commentaire, 'commentaires'=>$commentaires]);
}
So now i need to display these comments on a property page so i added code to property controller and i made it like this where $commentaires and commentaire are my variables one who get count and seconde to display.
$commentaire = Annoncecomment::where('prop_id',$proprety)->count();
$commentaires = Annoncecomment::where('prop_id',$proprety)->orderBy('id','desc')->get();
$rate = DB::table('clients')
->join('ratings', 'ratings.client', '=', 'clients.id')
->where('ratings.client',$proprety->client)->sum('star_rating');
$rateC = DB::table('clients')
->join('ratings', 'ratings.client', '=', 'clients.id')
->where('ratings.client',$proprety->client)->count();
if($rateC == 0){
$rate = 0;
}else{
$rate = $rate/$rateC;
}
return view('client.propretry.showProprety')->with(["commentaire"=>$commentaire, "commentaires"=>$commentaires,"rate"=>$rate,'cat'=>$cat,'area'=>$area,'price'=>$price,'type'=>$type,'client'=>$client,'similair'=>$similar,'image'=>$image,"states"=>$state,"proprety"=>$proprety]);
Back to the view of the property page i made a foreach but it dont display data and there is NO error or something in the console i made my for each like this :
section class="comments">
<div class="utf-inner-blog-section-title">
<h4><i class="icon-line-awesome-commenting-o"></i> Commentaires ({{ $commentaire->count() }})</h4>
</div>
<ul>
#foreach ($commentaires as $i)
<li>
<div class="avatar"><img src="/assets/media/avatars/blank.png" alt="" /></div>
<div class="comment-content">
<div class="arrow-comment"></div>
<div class="comment-by">{{ $i->nom }}
<span class="date">{{ date('F j, Y', strtotime($i->created_at)) }}</span>
#if (Auth::user())
<a href="#" data-id="{{ $i->id }}" id="replay"
class="reply"><i class="fa fa-reply"></i> Répondre</a>
#endif
</div>
<p>{{ $i->commentaire }}</p>
</div>
<ul>
What i did wrong ?
I know this is a little bit long but i'am struggling for 5 hours now.
Thank you very much
UPDATE UPDATE :
when i change this, from property controller it display all the comment but not the specifique comment for the prop :
this :$commentaires = Annoncecomment::where('prop_id',$proprety)->get();
to this : $commentaires = Annoncecomment::all();
Please pass the data in view method as second parameter not in with;
return view('client.propretry.showProprety', ["commentaire"=>$commentaire, "commentaires"=>$commentaires,"rate"=>$rate,'cat'=>$cat,'area'=>$area,'price'=>$price,'type'=>$type,'client'=>$client,'similair'=>$similar,'image'=>$image,"states"=>$state,"proprety"=>$proprety]);
i have a problem where the value isn't calculated.
I have function where the user able to update Weight/size and quantity(if the input isn't in readonly). When the user enter a new weight/size it will be auto-calculated in the Order Total. Apparently, there is a value already in the Order Total (since it is an update) so i want it to auto update the value in the order total when the user update the new input in weight/size or quantity.
pls click this picture
here is my updates.blade.php
<div class="col-sm-12 col-md-6" >
<div class="card">
<div class="card-body">
<div class="form-actions">
<div class="container" style="padding: 0;margin: 0;">
<div class="row">
<div class="col-sm-6" >
<span class="float-sm-left">
<h3 class="card-title">Update Order</h3>
</span>
</div>
</div>
</div>
</div>
</br>
<form action="" method="POST" >
#csrf
#method('PUT')
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationTooltip01">Order ID</label>
<input type="text" class="form-control" wire:model="orderID" value="" readonly>
</div>
<div class="col-md-4 mb-3">
<label for="validationTooltip02">Order Date</label>
<input type="text" class="form-control" wire:model="orderDate" value="" readonly>
</div>
<div class="col-md-4 mb-3">
<label for="validationTooltipUsername">Order Status</label>
<input type="text" class="form-control" wire:model="orderStatus" value="" readonly>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label class="form-control-label" >Customer Phone Number</label>
<input type="text" name="" value="" class="form-control" maxlength="11" wire:model="custPhone" readonly>
</div>
<div class="col-md-6 mb-3">
<label class="form-control-label" >Customer Name</label>
<input type="text" name="" value="" class="form-control" maxlength="11" wire:model="custName" readonly>
</div>
</div>
<div class="form-row">
#foreach($serviceOrder as $o)
<div class="col-md-5 mb-3">
<label class="form-control-label" >Service {{ $loop->iteration }} </label>
<input type="text" wire:model="serviceOrder.{{ $loop->index }}.serv.serviceName" class="form-control " readonly>
</div>
<input type="hidden" wire:model="serviceOrder.{{ $loop->index }}.serv.servicePrice" class="form-control col-sm-1 mb-3" readonly>
<div class="col-md-3 mb-3">
<label class="form-control-label" >Weight/Size</label>
<input type="text" name="" value="" wire:model="serviceOrder.{{ $loop->index }}.weightsize" class="form-control">
</div>
<div class="col-md-3 mb-3">
<label class="form-control-label" >Quantity*opt</label>
<input type="text" name="" value="" wire:model="serviceOrder.{{ $loop->index }}.quantity" class="form-control" #if(!$serviceOrder[$loop->index]['quantity']) readonly #endif >
</div>
#endforeach
</div>
<label class="form-control-label" >Order Total RM</label>
<input type="number" wire:model="orderTotal" value="" class="form-control" readonly>
</br>
<div class="form-actions">
<div class="container" style="padding: 0;margin: 0;">
<div class="row">
<div class="col-sm-6" >
<span class="float-sm-left">
<a class="btn btn-primary" href="{{ route('orders.indexInProcess') }}"> Back</a>
</span>
</div>
<div class="col-sm-6">
<span class="float-sm-right">
<div class="text-right">
<button type="submit" class="btn btn-info mr-2">Update</button>
<button type="reset" class="btn btn-dark float-right">Reset</button>
</div>
</span>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
here is the livewire updates.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Customer;
use App\Service;
use App\Order;
use App\ServiceOrder;
class Updates extends Component
{
public $orders;
public $orderID;
public $orderDate;
public $orderStatus;
public $orderTotal;
public $custName;
public $custPhone;
public $serviceName;
public $servicePrice;
public $weightsize;
public $quantity;
public $serviceOrder;
public function mount($order,$so)
{
//$orders = Order::with('customer')->get();
//ServiceOrder::with('serv')->where('order_id', $order->id)->get();
$this->orderID = $order->id;
$this->orderDate = $order->orderDate;
$this->orderStatus = $order->orderStatus;
$this->orderTotal = $order->orderTotal;
$this->custPhone = $order->customer->custPhone;
$this->custName = $order->customer->custName;
$this->serviceOrder = $so->toArray();
//dd($this->serviceOrder);
//$so->serviceName,
//$so->weightsize,
//$so->quantity
}
public function render()
{
//$so = ServiceOrder::with('serv')->where('order_id', $order->id)->get();
return view('livewire.updates');
}
public function updatedInputs($name)
{
$array = explode('.', $name);
if ($array[1] == 'serviceName') {
$this->inputs[$array[0]]['servicePrice'] = $this->services->find($value)->servicePrice;
}
try {
$this->calculateTotal();
} catch (\Exception $e) {
}
}
// perform calculation here.
public function calculateTotal(){
$this->orderTotal = $this->orderTotal;
foreach ($this->serviceOrder as $item) {
if($item['quantity'] == ''){
$item['optQuantity']= 1;
$this->orderTotal += ($item['servicePrice'] * $item['weightsize']) * ($item['quantity']);
}else{
$this->orderTotal += $item['servicePrice'] * ($item['weightsize']) * ($item['quantity']);
}
//$this->total *= $item['optQuantity']; // * price;
}
}
}
please help me out here T.T
You can fire event from component (for example) and then register listener in class and call a method for updating total. Check documentation for that.
"Apparently, there is a value already in the Order Total (since it is an update) so i want it to auto update the value in the order total when the user update the new input in weight/size or quantity."
So, the problem is $orderTotal only update once? it doesn't update when user update new input?. Livewire should render everytime there is action or any input.
First of all, i advice u to check what happen when to your function when user update the new input with dd function.
public function calculateTotal(){
dd('is this func work?');
$this->orderTotal = $this->orderTotal;
foreach ($this->serviceOrder as $item) {
if($item['quantity'] == ''){
$item['optQuantity']= 1;
$this->orderTotal += ($item['servicePrice'] * $item['weightsize']) * ($item['quantity']);
}else{
$this->orderTotal += $item['servicePrice'] * ($item['weightsize']) * ($item['quantity']);
}
//$this->total *= $item['optQuantity']; // * price;
}
}
After you debug your function, maybe you already found the answer you looking for or you can come back and ask me anything. ^^
im trying to edit an image on laravel 6, but but it does not advance to next view, stays on the form view.
I have seen many tutorials of laravel 5.8 and 6. I can't make it work in any way
This is de controller:
public function update(Request $request, $id)
{
$validator = $request->validate([
'titulo' => 'required | max:50', //campo obligatorio y máximo 50 caracteres
'contenido' => 'required | max:150',
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$image_name = time().'.'.$request->imagen->getClientOriginalExtension();
$request->image->move(public_path('images'), $image_name);
$datos = array(
'titulo' => $request->titulo,
'contenido' => $request->contenido,
'imagen' => $image_name,
);
Noticia::whereId($id)->update($datos);
return redirect('/mostrar');
}
THis is Web.php file:
Route::get('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
Route::get('/editar/{id}', 'crearNoticiaController#edit')->name('editar');
this is form file:
<div class="subir-imagen">
<form method="get" action="{{ route('actualizar', $noticia->id) }}" enctype="multipart/form-data">
#csrf
<div class="crear-titulo">
<input class="titulo" type="text" name="titulo" placeholder="Escriba el titulo" value="{{$noticia->titulo}}">
</div>
<div class="crear-contenido">
<textarea class="ckeditor" name="contenido" placeholder="Escriba el contenido" >
{{$noticia->contenido}}
</textarea>
</div>
<table border="2">
<tr>
<td><img src="{{URL::to('/')}}/images/{{$noticia->imagen}}" alt="imagen" width="250" align="left"/></td>
</tr>
</table>
<div class="form-group">
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" />
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<input type="submit" class="btn btn-primary" value="Enviar" id="btn-enviar" />
</div>
</div>
</form>
</div>
Thnaks for help
I faced same issue, but luckily i solved this problem.I added my solution below, i think this will help you to solve this problem
public function updatePost(Request $request, $id)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:25|min:4',
'image' => 'mimes:jpeg,jpg,png,JPEG,JPG,PNG | max:100000',
]);
$data = array();
$data['category_id'] = $request->category_id;
$data['title'] = $request->title;
$data['details'] = $request->details;
$image = $request->file('image');
if($image)
{
$image_name = hexdec(uniqid());
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/assets/img/';
$image_url = $upload_path.$image_full_name;
$success = $image->move($upload_path,$image_full_name);
$data['image'] = $image_url;
unlink($request->old_photo);
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
else
{
$data['image'] = $request->old_photo;
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
}
edit_post.blade.php
#extends('welcome')
#section('content')
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<p>
List Posts
</p>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ url('posts.update_posts/'.$posts->id) }}" method="post" enctype="multipart/form-data">
#csrf
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<div>Category Name</div>
<label>Category ID</label>
<select class="form-control" name="category_id">
#foreach($category as $categories)
<option value="{{ $categories->id }}" <?php if ($categories->id == $posts->category_id)
echo "selected"; ?> > {{ $categories->name }} </option>
#endforeach
</select>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Title</label>
<input type="text" name="title" class="form-control" value="{{ $posts->title }}" id="title" required data-validation-required-message="Please product name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Details</label>
<textarea name="details" rows="5" class="form-control" value="{{ $posts->details }}" id="details"></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Image</label>
<input type="file" name="image" class="form-control" id="image"><br/>
Old Image : <img src="{{ URL::to($posts->image) }}" style="hight: 40px; width: 100px">
<input type="hidden" name="old_photo" value="{{ $posts->image }}">
</div>
</div>
<br>
<div id="success"></div>
<div class="form-group">
<button type="submit" class="btn btn-success" id="sendMessageButton">Update</button>
</div>
</form>
</div>
</div>
</div>
#endsection
First run on your project console command:
php artisan storage:link
Then try this code and if return any error message tell me khow:
$imagen = $request->file("imagen");
$extension = $imagen->extension();
$filename = time().".".$extension;
$request->file('imagen')->storeAs("public/images", $filename);
Finally check your public/images folder for image file exists.
Also you can read about storing uploaded files in laravel 6.x official documentation
I've solved with this way:
In web.php I put patch instead get
Route::patch('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
In the edit blade I put: #method('PATCH')
And this is the update in the controller:
public function update(Request $request, $id)
{
$noticia = Noticia::findOrFail($id);
$noticia->titulo = $request->get('titulo');
$noticia->contenido = $request->get('contenido');
$noticia->imagen = $request->file('imagen');
$validator = $request->validate([
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$imageName = time().'.'.request()->imagen->getClientOriginalExtension();
request()->imagen->move(public_path('images'), $imageName);
$noticia->imagen = $imageName;
$noticia->update();
return redirect('/mostrar'); //Redirigimos a la la vista para mostrar las noticias
}
I 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
I am trying to first validate the inputs and then add the values to database but neither I am able to see the validation error message nor I am able to insert records to database. I have a table in database named 'news' where I have
this is my boxed.blade.php
<form class="form-horizontal" role="form" method="post" action="/addNews" novalidate>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 col-sm-2 control-label">Title</label>
<div class="col-lg-10">
<input type="text" name="title" class="form-control" id="inputEmail1" placeholder="News Title" value="{{ Input::old('title') }}">
</div>
</div>
<div class="form-group">
<label for="inputPassword1" class="col-lg-2 col-sm-2 control-label">Description</label>
<div class="col-lg-10">
<textarea name="description" class="form-control" rows="6">{{ Input::old('description') }}</textarea>
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 col-sm-2 control-label">Reporter</label>
<div class="col-lg-10">
<input type="text" name="reported_by" class="form-control" id="inputEmail1" placeholder="Reporter Name" value="{{ Input::old('reported_by') }}">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<div class="checkbox">
<label>
<input type="checkbox" name="status"> Status
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-danger"><i class="fa fa-comments"></i> Add To List</button>
</div>
</div>
</form>
And routes.php
Route::get('addNews', function()
{
return View::make('pages.boxed');
}
);
Route::post('addNews', function()
{
//processing the form
$rules = array(
'title' => 'required',
'description' => 'required|min:50',
'reported_by' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
$message = $validator->message();
return Redirect::to('addNews')->withErrors($validator)->withInput(Input::all());
}
else{
$news = new News;
$news->title = Input::get('title');
$news->description = Input::get('description');
$news->reported_by = Input::get('reported_by');
$news->status = Input::get('status');
$news->save();
return Redirect::to('addNews');
}
}
This is my model News.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class News extends Model
{
protected $fillable = array('title', 'description', 'reported_by', 'status');
}
If you want to see the error, place the following code above your form:
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
UPDATE 1: Instead of defining the methods in routes.php file, define it in a Controller called NewsController
So, to do this, update your routes.php file to this:
Route::get('/addNews', 'getNewsForm');
Route::post('/addNews', 'postNewsForm');
NewsController.php
/**
* Display the add news form to the user.
*
* #return view
*/
public function getNewsForm()
{
return View::make('pages.boxed');
}
/**
* Store the input in the database after validation
*
* #param $request Illuminate\Http\Facade\Request
*/
public function postNewsForm(Request $request)
{
$this->validate($request, [
'title' => 'required',
'description' => 'required|min:50',
'reported_by' => 'required'
]);
News::create($request->all());
return redirect('/addNews');
}