Route [student.update] not defined. using laravel 7 - php

i am a beginner of laravel. i ran into the problem with Route [student.update] not defined. using laravel 7. when run the laravel project. what i tried so far i attached below.
i attached the controller and view and route file below i don't what was a problem.
Controller
public function edit(Student $student)
{
return view('edit')->with('student',$student);
}
public function update(Request $request, Student $student)
{
Student::update([
'name' => $request->name,
'phone' => $request->phone,
'address' => $request->address,
'created_at' => now(),
]);
return redirect()->route('student.index')->with('success', 'Student has been Updatedddd');
}
edit.blade.php
<form action="{{ route('student.update',$student->id) }}" method="POST">
#csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $student->name }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Phone:</strong>
<input class="form-control" name="phone" value="{{ $student->phone }}" placeholder="Phone"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Address:</strong>
<input class="form-control" name="address" value="{{ $student->address }}" placeholder="Address"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
index.blade.php
#extends('layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 7 CRUD Example from scratch - ItSolutionStuff.com</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('student.create')}}"> Create New Student</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>Phone</th>
<th>Address</th>
<th width="280px">Action</th>
</tr>
#foreach ($students as $student)
<tr>
<td>{{ $student->id }}</td>
<td>{{ $student->name }}</td>
<td>{{ $student->phone }}</td>
<td>{{ $student->address }}</td>
<td>
<a class="btn btn-primary" href="{{ route('student.edit',$student->id) }}">Edit</a>
<button type="submit" class="btn btn-danger">Delete</button>
</td>
</tr>
#endforeach
</table>
{!! $students->links() !!}
#endsection
Routes
Route::get('/students/{student}', 'StudentController#edit')->name('student.edit');
Route::get('/students/{student}', 'StudentController#update')->name('student.update');

Your update route is defined as a get route while your edit form is trying to submit a post request to the route
You should ideally have the update route defined as a PUT or PATCH route. And if you are using Laravel 8.x, then you should have FQCN for the controllers
//import use statements at the top
//use Illuminate\Support\Facades\Route;
//use App\Http\Controllers\StudentController;
Route::match(['PUT', 'PATCH'], '/students/{student}', [StudentController::class, 'update'])->name('student.update');
And then make a PUT or PATCH submit request from edit.blade.php
<form action="{{ route('student.update',$student->id) }}" method="POST">
#csrf
#method('PUT') //Method spoofing
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $student->name }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Phone:</strong>
<input class="form-control" name="phone" value="{{ $student->phone }}" placeholder="Phone"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Address:</strong>
<input class="form-control" name="address" value="{{ $student->address }}" placeholder="Address"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
And change the controller method
public function update(Request $request, Student $student)
{
$student->update([
'name' => $request->name,
'phone' => $request->phone,
'address' => $request->address,
'created_at' => now(),
]);
return redirect()->route('student.index')->with('success', 'Student has been Updatedddd');
}

Related

Update photo using Laravel

I created a table called "directors" using migrations.Then i created the model, view, controller.
In "DirectorController" i wrote crud operations logic for my table. It works until i try to edit a existing record. To be clear it update all informations except the image, it remains the same. Can someone tell me what is wrong?
*Folder "images" exists in public.
enter image description here
//Migration
public function up()
{
Schema::create('directors', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->datetime('birth');
$table->string('town');
$table->string('country');
$table->string('image');
$table->timestamps();
});
}
//DirectorController
public function update(Request $request, Director $director)
{
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'birth' => 'required',
'town' => 'required',
'country' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'images/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}else{
unset($input['image']);
}
$director->update($input);
return redirect()->route('directors.index')->with('success', 'Director updated successfully.');
}
//DirectorModel
protected $fillable = [
'first_name',
'last_name',
'birth',
'town',
'country',
'image'];
public function movies() {
return $this->hasMany(Movie::class);
}
// edit.blade.php
#extends('directors.layout')
#section('content')
<div class="row">
<div class="col-lg-12 d-flex justify-content-between mt-5 mb-4">
<div class="pull-left">
<h2>Edit Director</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('directors.index') }}"><i class="fa-solid fa-delete-left"></i> Back</a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<div class="first d-flex justify-content-between">
<strong>Whoops!</strong>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
There were some problems with your input. <br><br>
<ul>
#foreach ( $errors->all() as $error )
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('directors.update', $director->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>First Name:</strong>
<input type="text" name="first_name" value="{{ $director->first_name }}" class="form-control" placeholder="First Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Last Name:</strong>
<input type="text" name="last_name" value="{{ $director->last_name }}" class="form-control" placeholder="Last Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Birth:</strong>
<input type="text" name="birth" value="{{ $director->birth }}" class="form-control" placeholder="Birth">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Town:</strong>
<input type="text" name="town" value="{{ $director->town }}" class="form-control" placeholder="Town">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Country:</strong>
<input type="text" name="country" value="{{ $director->country }}" class="form-control" placeholder="Country">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Image:</strong>
<input type="file" name="image" class="form-control" placeholder="image">
<img src="/images/{{ $director->image }}" width="300px">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md12 text-center">
<button type="submit" class="btn btn-primary"><i class="fa-solid fa-square-plus"></i> Submit</button>
</div>
</div>
</form>
#endsection
You need to change your form as:
<form action="{{ route('directors.update', $director->id) }}" method="POST" enctype="multipart/form-data">

Laravel 8 CRUD Edit page cannot display correctly

I am currently making laravel project using internet references and now I'm stuck at CRUD operation.
I use Laravel 8 with jetstream for auth, now ui template assets, bootstrap.
I tried several CRUD codes from different sources and everything worked except for edit page.
Index page:
Edit page:
This is my route:
Route::resource('projects', ProjectController::class);
My controller:
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
public function update(Request $request, Project $project)
{
$request->validate([
'name' => 'required',
'introduction' => 'required',
'location' => 'required',
'cost' => 'required'
]);
$project->update($request->all());
return redirect()->route('projects.index')
->with('success', 'Project updated successfully');
}
The blade file:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Product</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('projects.index') }}" title="Go back"> <i class="fas fa-backward "></i> </a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<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
<form action="{{ route('projects.update', $project->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $project->name }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Introduction:</strong>
<textarea class="form-control" style="height:50px" name="introduction"
placeholder="Introduction">{{ $project->introduction }}</textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Location:</strong>
<input type="text" name="location" class="form-control" placeholder="{{ $project->location }}"
value="{{ $project->location }}">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Cost:</strong>
<input type="number" name="cost" class="form-control" placeholder="{{ $project->cost }}"
value="{{ $project->location }}">
</div>
</div>
<div class="text-center col-xs-12 col-sm-12 col-md-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
#endsection
I tried changing the edit blade file codes to different ones but still same. I tried different method from online for the edit function in controller but nothing change. I also tried completely different coding, different model controllers and all, still the same. Only edit page turns out that way. Anyone have any clue?

dropdown list not shown in laravel

I've got problem with dropdown list.
i want to show a primary key as a dropdown list in view blade , but i can not make the right rout to show it. Have you any ideas how to solve this problem?
this my root
$objects = ['users', 'permissions', 'roles', 'coins','pillars','subtindicators'];
foreach ($objects as $object) {
Route::get("$object", ucfirst(str_singular($object))."Controller#index")->middleware("permission:browse $object")->name("{$object}");
Route::get("$object/datatable", ucfirst(str_singular($object))."Controller#datatable")->middleware("permission:browse $object")->name("{$object}.datatable");
Route::get("$object/add", ucfirst(str_singular($object))."Controller#add")->middleware("permission:add $object")->name("{$object}.add");
Route::post("$object/create", ucfirst(str_singular($object))."Controller#create")->middleware("permission:add $object")->name("{$object}.create");
Route::get("$object/{id}/edit", ucfirst(str_singular($object))."Controller#edit")->middleware("permission:edit $object")->name("{$object}.edit");
Route::post("$object/{id}/update", ucfirst(str_singular($object))."Controller#update")->middleware("permission:edit $object")->name("{$object}.update");
Route::get("$object/{id}/delete", ucfirst(str_singular($object))."Controller#delete")->middleware("permission:delete $object")->name("{$object}.delete");
Route::get("$object/{id}", ucfirst(str_singular($object))."Controller#view")->middleware("permission:view $object")->name("{$object}.view");
Route::get("$object/create", ucfirst(str_singular($object))."Controller#list")->middleware("permission:add $object")->name("{$object}.create");
this my controller
public function add()
{ $strs = DB::table('stargets')->select('*')->get();;
return view('subtindicators.add-edit',compact('strs'));
}
public function update(Request $request, $id)
{
$object = $this->objectModel::find($id);
$object->update([
'skey_name' => $request->skey_name,
'Subtarget_base' => $request->Subtarget_base,
'Subtarget_end' => $request->Subtarget_end,
'subtarget_id' => $request->subtarget_id
]);
if ($request->save == 'browse')
return redirect()->route("{$this->objectName}");
elseif ($request->save == 'edit')
return redirect()->route("{$this->objectName}.edit", ['id' => $object]);
elseif ($request->save == 'add')
return redirect()->route("{$this->objectName}.add");
else
return redirect($request->previous_url);
}
this my blade
#extends('adminlte::page')
#include('bread.title')
#section('main-content')
<div class="container-fluid spark-screen">
<div class="row">
{!! csrf_field() !!}
<form class="form-horizontal" action="{{$actionName=='edit'?route("{$objectName}.update",['id'=>$object->id]):route("{$objectName}.create") }}" method="post">
{!! csrf_field() !!}
<input type="hidden" name="previous_url" value="{{ url()->previous() }}">
<form class="form-horizontal" action="{{ $actionName == 'edit' ? route("{$objectName}.update", ['id' => $object->id]) : route("{$objectName}.create") }}" method="post">
{!! csrf_field() !!}
<input type="hidden" name="previous_url" value="{{ url()->previous() }}">
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">{{ ucfirst($actionName) }} {{ ucfirst($objectName) }} {{ !empty($object) ? "(ID $object->id)" : '' }}</h3>
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">{{ ucfirst($actionName) }} {{ ucfirst($objectName) }} {{ !empty($object) ? "(ID $object->id)" : '' }}</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<div class="box-body">
<div class="form-group">
<label for="" class="col-md-2 control-label">col</label>
<div class="col-md-10">
<input type="text" name="skey_name" class="form-control" maxlength="255" value="{{ !empty($object) ? $object->coin_arname : '' }}" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-md-2 control-label">cl_d</label>
<div class="col-md-10">
<input type="text" name="Subtarget_base" class="form-control" maxlength="255" value="{{ !empty($object) ? $object->coin_enname : '' }}" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-md-2 control-label">cl_e</label>
<div class="col-md-10">
<input type="text" name="Subtarget_end" class="form-control" maxlength="255" value="{{ !empty($object) ? $object->coin_arsymbol : '' }}" required>
</div>
</div>
<div class="form-group">
<label for="" class="form-control">c_i</label>
<div class="col-md-10">
<select class="form-control" name="starget_id">
<option selected disabled value = " ">choos</option>
#foreach($strs as $vis)
<option value="{{$vis->id}}">{{$vis->target_name}}</option>
#endforeach
<!-- <p class="form-control-static">{{ $object->subtarget_id }}</p>-->
</div>
</div>
<div class="form-group has-feedback">
<label for="title">main<span class="text-danger">*</span></label>
<select class="form-control" name="starget_id">
<option selected disabled value = " ">choos</option>
#foreach($strs as $slider2)
<option value="{{$slider2->id}}" {{ $slider2->id== $slider->starget_id ? 'selected' : '' }}>{{$slider2->vname}}</option>
#endforeach
</div>
</div>
</div>
<div class="box-footer">
#include('bread.add-edit-actions')
</div>
</div>
</form> </form>
</div>
</div>
</div>
#endsection
this error what i got
ErrorException (E_ERROR)
Undefined variable: actionName (View: C:\project Last\resources\views\bread\title.blade.php) (View: C:\Ministry Last\resources\views\bread\title.blade.php)
You should forward $actionName variable to your view:
public function add()
{
$strs = DB::table('stargets')->select('*')->get();
$actionName = 'edit';
return view('subtindicators.add-edit',compact('strs', 'actionName'));
}
However this will hardcode the form to being an "edit" form. You must see what you really want with your logic.

"Trying to get property 'name' of non-object

I had a Laravel script installed
Now I want to go to the services list page, but with the "Trying to get the property 'name' of non-object" encountered.
please help me
My error:
Trying to get property 'name' of non-object (View: /mylocalhost/core/resources/views/admin/service.blade.php)
in line 36:
category->name); ?>
service.blade.php code:
#section('page_name', 'Services')
<a class="btn btn-outline-success btn-lg" href="#" data-toggle="modal" data-target="#addService"><i
class="fa fa-plus-circle"></i> Add Service</a>
#endsection
#section('body')
<ul class="orders-ul">
<li class="text-color"><a class="btn btn-outline-secondary" href="{{ route('api.service') }}" target="_blank">API Services List</a></li>
</ul>
<div class="row">
#include('admin.layouts.flash')
<div class="col-md-12">
<div class="tile">
<h3 class="tile-title">Services</h3>
<table class="table table-hover">
<thead>
<tr>
<th>Serial</th>
<th>Name</th>
<th>Category</th>
<th>Price per 1K</th>
<th>Min</th>
<th>Max</th>
<th>Order Response</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($items as $key => $item)
<tr>
<td>{{ $key+1 }}</td>
<td>{{ $item->name }}</td>
<td>{{ $item->category->name }}</td>
<td>{{ $item->price_per_k }}</td>
<td>{{ $item->min }}</td>
<td>{{ $item->max }}</td>
<td>{{ $item->service_id == 0? 'Manual' : 'API' }}</td>
<td>
{!! $item->status == 0 ? '<b style="color:#d35400">Inactive</b>' : '<b style="color:#16a085">Active</b>' !!}
</td>
<td>
<button class="btn btn-outline-info service_edit_btn"
data-toggle="modal"
data-target="#editService"
data-route="{{ route('service.update', $item->id) }}"
data-category="{{ $item->category_id }}"
data-name="{{ $item->name }}"
data-price="{{ $item->price_per_k }}"
data-min="{{ $item->min }}"
data-max="{{ $item->max }}"
data-service_id="{{ $item->service_id }}"
data-details="{{ $item->details }}"
data-status="{{ $item->status }}">
<i class="fa fa-edit`enter code here`"></i></button>
<button class="btn btn-outline-danger service_dlt_btn"
data-toggle="modal"
data-target="#delService"
data-route="{{ route('service.delete', $item->id) }}">
<i class="fa fa-trash"></i></button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
<div class="modal fade" id="addService" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4><b>Add Service</b></h4>
</div>
<div class="modal-body">
<div class="portlet light bordered">
<div class="portlet-body form">
<form role="form" action="{{ route('service.store') }}" method="post">
#csrf
<div class="form-body">
<div class="form-group">
<label for=""><b>Category</b></label>
<select name="category_id" class="form-control form-control-lg">
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for=""><b>Name</b></label>
<input type="text" name="name" class="form-control form-control-lg">
</div>
<div class="form-group">
<label for=""><b>Price per 1k</b></label>
<div class="input-group">
<input type="text" name="price_per_k" class="form-control form-control-lg">
<div class="input-group-append">
<span class="input-group-text">{{ $general->currency_symbol }}</span>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for=""><b>Min</b></label>
<input type="text" name="min" class="form-control form-control-lg">
</div>
<div class="form-group col-md-6">
<label for=""><b>Max</b></label>
<input type="text" name="max" class="form-control form-control-lg">
</div>
</div>
<div class="form-group">
<label for=""><b>Details</b></label>
<textarea class="form-control" name="details" rows="8"></textarea>
</div>
<div class="form-group">
<label for=""><b>service Id (If order process through API)</b></label>
<input type="text" name="service_id" class="form-control form-control-lg">
</div>
<div class="form-group">
<label for=""><b>Status</b></label>
<input data-toggle="toggle" data-onstyle="success" data-offstyle="danger"
data-on="Active" data-off="Inactive" data-width="100%" type="checkbox" name="status" value="1">
</div>
</div>
<div class="tile-footer">
<button class="btn btn-primary btn-block btn-lg" type="submit"><i
class="fa fa-fw fa-lg fa-check-circle"></i>Save
</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<div class="modal fade" id="editService" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4><b>Edit Service</b></h4>
</div>
<div class="modal-body">
<div class="portlet light bordered">
<div class="portlet-body form">
<form role="form" action="" method="post"
id="serviceEditdForm">
#csrf
#method('put')
<div class="form-body">
<div class="form-group">
<label for=""><b>Category</b></label>
<select name="category_id" id="category_id" class="form-control form-control-lg">
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for=""><b>Name</b></label>
<input type="text" name="name" id="name" class="form-control form-control-lg">
</div>
<div class="form-group">
<label for=""><b>Price per 1k</b></label>
<div class="input-group">
<input type="text" name="price_per_k" id="price_per_k" class="form-control form-control-lg">
<div class="input-group-append">
<span class="input-group-text">{{ $general->currency_symbol }}</span>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for=""><b>Min</b></label>
<input type="text" name="min" id="min" class="form-control form-control-lg">
</div>
<div class="form-group col-md-6">
<label for=""><b>Max</b></label>
<input type="text" name="max" id="max" class="form-control form-control-lg">
</div>
</div>
<div class="form-group">
<label for=""><b>Details</b></label>
<textarea class="form-control" name="details" id="details" rows="8"></textarea>
</div>
<div class="form-group">
<label for=""><b>service Id (If order process through API)</b></label>
<input type="text" name="service_id" id="service_id" class="form-control form-control-lg">
</div>
<div class="form-group">
<label for=""><b>Status</b></label>
<input data-toggle="toggle" data-onstyle="success" data-offstyle="danger"
data-on="Active" data-off="Inactive" data-width="100%" type="checkbox" name="status" id="status" value="1">
</div>
</div>
<div class="tile-footer">
<button class="btn btn-primary btn-block btn-lg" type="submit"><i
class="fa fa-fw fa-lg fa-check-circle"></i>Save
</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<div class="modal fade" id="delService">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-body">
<form action="" method="post" id="serviceDelForm">
#csrf
#method('delete')
<h3 class="d-flex justify-content-center">Are you want to delete this Service?</h3>
<div class="tile-footer d-flex justify-content-center">
<button class="btn btn-primary" type="submit"><i class="fa fa-fw fa-lg fa-check-circle"></i>Confirm
</button>
<a class="btn btn-danger" href="#" data-dismiss="modal"><i
class="fa fa-fw fa-lg fa-times-circle"></i>Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.service_edit_btn', function () {
var route = $(this).data('route');
var category = $(this).data('category');
var name = $(this).data('name');
var price = $(this).data('price');
var min = $(this).data('min');
var max = $(this).data('max');
var service_id = $(this).data('service_id');
var details = $(this).data('details');
var status = $(this).data('status');
$('#category_id').val(category).attr('selected', 'selected');
$('#name').val(name);
$('#price_per_k').val(price);
$('#min').val(min);
$('#max').val(max);
$('#service_id').val(service_id);
$('#details').val(details);
$('#serviceEditdForm').attr('action',route);
if(status == 1){
$('#status').bootstrapToggle('on');
}else{
$('#status').bootstrapToggle('off');
}
});
$(document).on('click', '.service_dlt_btn', function () {
var route = $(this).data('route');
$('#serviceDelForm').attr('action', route);
});
});
</script>
#endsection
And service list controller in Admin controller:
public function service(){
$categories = Category::orderBy('name')->get();
$items = Service::orderBy('category_id')->paginate(10);
return view('admin.service', compact('items', 'categories'));
}
public function serviceStore(Request $request){
$this->validate($request, [
'category_id' => 'required',
'name' => 'required|unique:services,name',
'price_per_k' => 'required',
'min' => 'required',
'max' => 'required',
'details' => 'required',
], [
'category_id.required' => 'Category name is required',
'price_per_k.required' => 'price per 1k is required',
]);
$excp = $request->except('_token', 'status', 'service_id');
$status = $request->status == 1? 1:0;
if(isset($request->service_id)){
$service_id = $request->service_id;
}else{
$service_id = 0;
}
$sev = Service::create($excp + ['status' => $status, 'service_id' => $service_id]);
$users = User::all();
foreach ($users as $user){
$servicePrice = new ServicePrice();
$servicePrice->category_id = $sev->category_id;
$servicePrice->service_id = $sev->id;
$servicePrice->user_id = $user->id;
$servicePrice->price = $sev->price_per_k;
$servicePrice->save();
}
session()->flash('success', 'Service Stored successfully');
return back();
}
public function serviceUpdate(Request $request, $id){
$this->validate($request, [
'category_id' => 'required',
'name' => 'required',
'price_per_k' => 'required',
'min' => 'required',
'max' => 'required',
'details' => 'required',
], [
'category_id.required' => 'Category name is required',
'price_per_k.required' => 'price per 1k is required',
]);
$excp = $request->except('_token', 'status', 'service_id');
$status = $request->status == 1? 1:0;
if(isset($request->service_id)){
$service_id = $request->service_id;
}else{
$service_id = 0;
}
Service::findOrFail($id)->update($excp + ['status' => $status, 'service_id' => $service_id]);
session()->flash('success', 'Service Updated successfully');
return back();
}
public function serviceDelete($id){
Service::findOrFail($id)->delete();
session()->flash('success', 'Service deleted successfully');
return back();
}
This means your item don't have category, So you can do something like this.
<td>
#if(!empty($item->category)) {{ $item->category->name }} #endif
</td>
Other way to solve this problem using php7 is to use null coalescing operator which:
It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
<td>{{ $item->category->name ?? '' }}</td>

How to update a database table in laravel 5.2

i created one project in laravel 5.2. In that "myform.blade.php" page , created form for register the user. after registration it will show the current user in table format("index.blade.php"). There i given two dynamic button like the drop inside the table. One for Edit and other for Edit/View. When i click on delete button it will delete the corresponding row from the database by taken Primary key(employeeID) as reference id, it's working properly. if i click on Edit/View button it will redirect to "edit.blade.php". There i created same form as in myform.blade.php. If we want to edit the details we can edit from there. I can able to fetch the data from database to the form that i created in the "edit.blade.php". But i don't know how to update the data from their without inserting the same data again(It is not possible, because it will create Integrity constraint violation by trying to insert duplicate primary key. Can any one please tell me how to do updation. Replies are appreciable.
"myform.blade.php" is
#extends('app')
#section('content')
<div class="templatemo-content-wrapper">
<div class="container">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">Employee Form</li>
</ol>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-success">
<div class="panel-heading">Employee Form</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<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
<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/myform/') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">Employee ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeID" value="{{ old('employeeID') }}" placeholder="Enter employee ID">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E_number</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeNo" value="{{ old('employeeNo') }}" placeholder="Enter employee number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="Cname" value="{{ old('Cname') }}" placeholder="Enter Contact Name">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">DOB</label>
<div class="col-md-6">
<input type="date" class="form-control" name="dob" value="{{ old('dob') }}" placeholder="Enter date of birth">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Contact Phone</label>
<div class="col-md-6">
<input type="text" class="form-control" name="phoneNumber" value="{{ old('phoneNumber') }}" placeholder="Enter Mobile Number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Address</label>
<div class="col-md-6">
<input type="text" class="form-control" name="address" value="{{ old('address') }}" placeholder="Enter Address">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-warning">
Save
</button>
</div>
</div>
view Data
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
"index.blade.php" is
#extends('app')
#section('content')
<div class="templatemo-content-wrapper" xmlns="http://www.w3.org/1999/html">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">user information</li>
</ol>
<div class="templatemo-content">
<h1>View/Edit user information</h1>
<div>
<div>
<div>
<table id="example" class="table table-striped table-hover table-bordered" bgcolor="#fff8dc">
<thead>
<tr>
<th>Employee ID</th>
<th>Employee No</th>
<th>Contact Name</th>
<th>Date of birth</th>
<th>Mobile number</th>
<th>address</th>
</tr>
</thead>
<tbody>
{{--{{ UserController::getIndex() }}--}}
#foreach($employer as $emp)
<tr>
<td>{{ $emp->employeeID }}</td>
<td>{{ $emp->employeeNo }}</td>
<td>{{ $emp->Cname }}</td>
<td>{{ $emp->dob }}</td>
<td>{{ $emp->phoneNumber }}</td>
<td>{{ $emp->address }}</td>
<td>
{{--#if ( in_array($nam->isActive, array('Yes','No')) )--}}
<div class="btn-group">
<button type="button" class="btn btn-info">Action</button>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
{{--#if ($nam->isActive == 'Yes')--}}
<li data-toggle="modal" data-target="#acceptModal" data-bookingid="{{ $emp->employeeID }}">View/ Edit
</li>
{{--#endif--}}
<li>Delete</li>
</ul>
</div>
{{--#endif--}}
</td>
</tr>
#endforeach
</tbody>
</table>
{{$employer->links()}}
</div>
</div>
</div>
</div>
</div>
{{-- <input type="submit" id="add" name="add" value="Edit" class="button">--}}
</br>
<h4>Create a new Employee</h4>
{{--<form class="templatemo-preferences-form" role="form" method="POST" action="{{ action('UserController#save') }}">--}}
{{--<input type="hidden" name="_token" value="{{ csrf_token() }}">--}}
<form role="form" method="POST" action="{{ url('myform/index') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="row">
<div class="col-md-6 margin-bottom-15">
<input type="text" class="form-control" name="employeeID" value="{{ old('employeeID') }}" placeholder="Enter employee ID">
</div>
<div class="row templatemo-form-buttons">
<div class="submit-button">
<button type="submit" class="btn btn-primary">New</button>
</div>
</div>
</div>
</form>
{{--</form>--}}
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
#endsection
"edit.blade.php" is
#extends('app')
#section('content')
<div class="templatemo-content-wrapper">
<div class="container">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">Employee Form</li>
</ol>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-success">
<div class="panel-heading">Employee Form</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<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
<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/myform/') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#foreach($user as $use)
<div class="form-group">
<label class="col-md-4 control-label">Employee ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeID" value="{{ $use->employeeID }}" placeholder="Enter employee ID">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E_number</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeNo" value="{{ $use->employeeNo}}" placeholder="Enter employee number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="Cname" value="{{ $use->Cname }}" placeholder="Enter Contact Name">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">DOB</label>
<div class="col-md-6">
<input type="date" class="form-control" name="dob" value="{{ $use->dob }}" placeholder="Enter date of birth">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Contact Phone</label>
<div class="col-md-6">
<input type="text" class="form-control" name="phoneNumber" value="{{ $use->phoneNumber }}" placeholder="Enter Mobile Number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Address</label>
<div class="col-md-6">
<input type="text" class="form-control" name="address" value="{{ $use->address }}" placeholder="Enter Address">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-warning"><a href="{{ url('myform/update/'.$use->employeeID) }}">
Update</a>
</button>
</div>
</div>
{{-- <input type="button" id="add" name="add" value="View data" class="button">--}}
#endforeach
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
"myformController.php" is
<?php
namespace App\Http\Controllers;
use App\myform;
use Mail;
use Illuminate\Support\Facades\DB;
use Faker\Provider\DateTime;
use App\User;
use App\Http\Requests\createUserRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Symfony\Component\HttpFoundation\Request;
class myformController extends Controller
{
public $type = 'myform';
public function getIndex()
{
// $user = DB::table('user')->get();
$employer = DB::table('employee')->simplePaginate(5);
return view('myform.index')->with('employer',$employer);
}
public function formInsert()
{
$postform = Input::all();
//insert data into mysql table
$data = array('employeeID'=> $postform['employeeID'],
'employeeNo'=> $postform['employeeNo'],
'Cname'=> $postform['Cname'],
'dob'=> $postform['dob'],
'phoneNumber'=> $postform['phoneNumber'],
'address'=> $postform['address'],
);
// echo print_r($data);
$ck = 0;
$ck = DB::table('employee')->Insert($data);
//echo "Record Added Successfully!";
$employer = DB::table('employee')->simplePaginate(10);
return view('myform.index')->with('employer',$employer);
}
public function delete($id)
{
DB::table('employee')->where('employeeID', '=', $id)->delete();
$employer = DB::table('employee')->simplePaginate(10);
return view('myform.index')->with('employer', $employer);
}
public function formIDinsert()
{
$postform = Input::all();
//insert data into mysql table
$data = array('employeeID'=> $postform['employeeID'],
);
// echo print_r($data);
$ck = 0;
$ck = DB::table('employee')->Insert($data);
//echo "Record Added Successfully!";
$employer = DB::table('employee')->simplePaginate(10);
return view('myform.index')->with('employer',$employer);
}
public function edit($id)
{
try {
//Find the user object from model if it exists
$user=DB::table('employee')->where('employeeID', '=', $id)->get();
//$user = User::findOrFail($id);
//Redirect to edit user form with the user info found above.
return view('myform.edit')->with ('user', $user);
//return view('myform.edit')->with('user', myform::find($id));
} catch (ModelNotFoundException $err) {
//redirect to your error page
}
}
// Update user
public function update(Request $request, $id)
{
try{
//Find the user object from model if it exists
$user= myform::findOrFail($id);
DB::table('employee')
->where('employeeID', $id)
->update(['employeeNo' =>$request['employeeNo'],
'Cname'=>$request['Cname'],
'phoneNumber'=>$request['phoneNumber'],
'address'=>$request['address']
]);
//Set user object attributes
//the $request index should match your form field ids!!!!!
//you can exclude any field you want.
// $user->employeeNo = $request['employeeNo'];
// $user->Cname = $request['Cname'];
// $user->phoneNumber = $request['phoneNumber'];
// $user->address = $request['address'];
//Save/update user.
$user->save();
return view('myform.index')->with('user', $user);
//redirect to somewhere
}
catch(ModelNotFoundException $err){
//Show error page
}
}
}
model "myform.php" is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class myform extends Model
{
protected $table = 'employee';
//protected $primaryKey = 'employeeID';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'employeeID',
'employeeNo',
'Cname',
'dob',
'phoneNumber',
'address',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Routes.php is
Route::any('myform', function()
{
return view('myform/myform');
});
Route::any('myform/myform', 'myformController#formInsert');
Route::any('myform/index', 'myformController#getIndex');
//to show edit form and fetch passed user id info from db
Route::get('myform/edit/{id}', 'myformController#edit');
//to get the edited info and save it to db
Route::get('myform/update/{id}', 'UserController#update');
Route::any('myform/index', 'myformController#formIDinsert');
Route::any('myform/delete/{id}', 'myformController#delete');
You wanna change this in your route:
Route::get('myform/update/{id}', 'UserController#update');
to
//Because the data in your form is transferred/submitted by post request
Route::post('myform/update/{id}', 'UserController#update');
then change your update function to this
// Update user
public function update(Request $request, $id)
{
try{
//Find the user object from model if it exists
$user= myform::findOrFail($id);
//$request contain your post data sent from your edit from
//$user is an object which contains the column names of your table
//Set user object attributes
$user->employeeNo = $request['employeeNo'];
$user->Cname = $request['Cname'];
$user->dob = $request['dob'];
$user->phoneNumber = $request['phoneNumber'];
$user->address = $request['address'];
// Save/update user.
// This will will update your the row in ur db.
$user->save();
return view('myform.index')->with('user', $user);
}
catch(ModelNotFoundException $err){
//Show error page
}
}
If you have any question or need clarification you are most welcome to ask :)
Update in your edit view
change this
<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/myform/') }}">
to
<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/update/').$user->employeeID}}">
change $user->employeeID to whatever is your primary key.
Also change this
<button type="submit" class="btn btn-warning"><a href="{{ url('myform/update/'.$use->employeeID) }}">
Update</a>
</button>
to this
<button type="submit" class="btn btn-warning">Update</button>
Aso you didn't fix your route as I mentioned earlier in this answer.

Categories