I am trying to delete data from my table employes by getting the id of the data and transferring it by using get route but i get the following error
ModelNotFoundException in Builder.php line 125: No query results for
model [App\employe].
her is my route
Route::get('/delete/{employe}', 'EmployeController#delete');
Route::post('/delete', 'EmployeController#handleDelete');
and i have model called employe to access my table
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class employe extends Model {
protected $fillable = array('fname','lname','age','sex','phone','email','houseno','city','kebele','state','username','password','workposition','salary','bankaccount','bankname','contactid','employedate');
}
part of my controller for deleting
public function delete(employe $employe)
{
// Show delete confirmation page.
return View('deleteemploye', compact('employe'));
}
public function handleDelete()
{
$employe = employe::findOrFail(Input::get('employe'));
$employe->delete();
return Redirect::action('EmployeController#index');
}
her is my view for deleting file
#extends('app')
#section('content')
<div class="page-header">
<h2>Delete {{$employe->fname}} Are you sure?</h2>
</div>
<form action="{{ action('EmployeController#handleDelete') }}" method="post" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="employe" id="employe" value="{{ $employe->id }}" />
<input type="submit" class="btn btn-default" value="Yes" />
No
</form>
#stop
Looks like laravel cant find the model with the primary key you are passing. Check the database and see if its there. If it is check the deleted_at field. If it has a date in it, it means it is already deleted. You can still find it by using withTrashed()
$employe = employe::withTrashed()->findOrFail(Input::get('employe'));
and if you have soft deleting enabled for this model, you can completely remove the given row by running
$employe = employe::withTrashed()->findOrFail(Input::get('employe'))->forceDelete();
Related
Hello i'm new in laravel. My application has a search bar component in almost every view.
The user types there the ID of the client, makes a query to db and compares the user's typed ID with the DB client ID.
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class SearchController extends Controller
{
function get_kcli(Request $request) {
$id = $request->input('kcli');
$current_page = $request->input('currentPage') . '.index';
$data = DB::connection('oracle')->table('CLIENTS')->where('KCLI', $id)->get();
return view($current_page, compact('data'));
}
}
Web.php
Route::post('/search', [App\Http\Controllers\SearchController::class, 'get_kcli'])->name('search');
Form search component view:
<nav class="navbar navbar-light">
<form method="POST" class="form-inline position-relative" action="{{ route('/search') }}">
#csrf
#method('POST')
<input class="form-control shadow-none" name="kcli" id="kcli" type="number" placeholder="Codice..." aria-label="Search">
<input type="text" name="currentPage" value="{{ Route::currentRouteName() }}" hidden>
<button type="submit" class="btn btn-light search-btn"><i class="fas fa-search"></i></button>
</form>
Anyone knows the best practice to store that data request globally an mantain it for every view that need to exctract it?
Example : I search for the client ID '5', the search controller makes a db query with the passed ID, then compacts data. That data has to be stored globally for get the results and post it in other views, without searching again on every view switch(the typed ID '5' has to remain in the search field on every view switch).
To print client_id you can store that "id" in session and print from the session by this way your search value keep remains and to get data in all views there is the concept View::share you can register that in AppServiceProvider please go through this link
https://laravel.com/docs/9.x/views#sharing-data-with-all-views
i'm having trouble to get data from an input.
I try to be more specific
My application has many views, and each of these has an #include component that works as a search field.
For example the user types in the input the ID of the store, the controller compares the ID that user inserted with the DB store's ID and then compacts data and fill the views with infos of that specific store.
Im just testing how to get that data from the input but i'm getting this error:
Route [search.get_kcli] not defined.
Actually i'm trying to use that function only for get data by using a controller only for that input field.
What's wrong in it?
Thanks for help!
My code looks like this:
inside of app.blade.php
#auth
#include('partials.search')
#endauth
inside search.blade.php
<form method="POST" class="form-inline position-relative"
action="{{ route('search.get_kcli') }}">
#csrf
#method('POST')
<input class="form-control shadow-none" name="kcli" id="kcli" type="number"
placeholder="Codice..." aria-label="Search">
<button type="submit" class="btn btn-light search-btn"><i class="fas fa-search"></i></button>
</form>
Inside the SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class SearchController extends Controller
{
function get_kcli(Request $request) {
$kcli = $request->input('kcli');
dd($kcli);
}
}
Inside web.php
Route::post('/search', [App\Http\Controllers\SearchController::class, 'get_kcli'])->name('search');
Change
<form method="POST" class="form-inline position-relative"
action="{{ route('search.get_kcli') }}">
to
<form method="POST" class="form-inline position-relative"
action="{{ route('search') }}">
I'm trying to update my database using a form on my
edit.blade.php page as shown below. The edit part works correctly as the fields are filled in in the form as expected, however when i try to save, an error message of
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
is displayed. I have tried so many ways on how to fix it and I'm not sure where I'm going wrong. Hopefully it's something simple to fix?
edit.blade.php
#extends('layouts.app')
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<form method="post" action="{{ action('PostsController#update', $id) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH" />
<h1>Edit Item</h1>
<div class="form-group">
<label for="item">Item:</label>
<input type="text" id="item" name="item" value="{{$post->item}}" class="form-control" required>
</div>
<div class="form-group">
<label for="weight">Weight (g):</label>
<input type="number" id="weight" value="{{$post->weight}}" name="weight" class="form-control">
</div>
<div class="form-group">
<label for="noofservings">No of Servings:</label>
<input type="number" id="noofservings" value="{{$post->noofservings}}" name="noofservings" class="form-control">
</div>
<div class="form-group">
<label for="calories">Calories (kcal):</label>
<input type="number" id="calories" name="calories" value="{{$post->calories}}" class="form-control">
</div>
<div class="form-group">
<label for="fat">Fat (g):</label>
<input type="number" id="fat" name="fat" value="{{$post->fat}}" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
#endsection
PostsController.php
<?php
public function update(Request $request, $id)
{
$this->validate('$request', [
'item' => 'required'
]);
$post = Post::find($id);
$post->item = $request->input('item');
$post->weight = $request->input('weight');
$post->noofservings = $request->input('noofservings');
$post->calories = $request->input('calories');
$post->fat = $request->input('fat');
$post->save();
return redirect('/foodlog');
}
web.php
<?php
Route::get('edit/{id}', 'PostsController#edit');
Route::put('/edit', 'PostsController#update');
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'id',
'user_id',
'item',
'weight',
'noofservings',
'calories',
'fat',
'created_at'
];
}
My website is a food log application and this function is so that they can edit their log.
Any help is greatly appreciated!
Based on Michael Czechowski I edited my answer to make this answer better, The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second problem is , the form method field is 'patch' and your route method is 'put'.
The difference between 'patch' and 'put' is:
put: gets the data and update the row and makes a new row in the database from the data that you want to update.
patch: just updates the row and it does not make a new row.
so if you want to just update the old row change the route method to patch.
or if you really want to put the data, just change the put method field in your form.
simply by : {{method_field('PUT')}}
Remember, the form's and the route's methods must be same. If the form's method is put, the route method must be put; and vice-versa.
The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second one is inside your HTML template:
<input type="hidden" name="_method" value="PUT" />
To hit the right route you have to add the corresponding method to your route Route::put('/edit/{id}', 'PostsController#update');.
A possible last problem
<form method="post" action="{{ action('PostsController#update', $post->id) }}">
I am not sure how your template works, but $id is possible not set inside your template. Maybe try to specify the ID depending on your post. Just to make it sure the ID comes from the shown post.
Further suggestions
Best practice is to use the symfony built-in FormBuilder. This would make it easier to target those special requests like PUT, PATCH, OPTIONS, DELETE etc.
I have a project that is going to have 8 different forms all updating the same 'user' table in my database. I have the user authentication working and it makes a user in the table on my localhost mysql database. However when I start updating the table I keep getting errors such as email is not unique or http errors or ReflectionException in RouteDependencyResolverTrait.php line 57: Internal error: Failed to retrieve the default value.
I have tried everything, my create works but it makes a new row and doesn't update the existing row which the user is signed in on.
I'm only new to Laravel 5.4 and finished going through all the Laracasts, so I'm absolutely stumped at what to do.
Does anyone have any thoughts or know how to fix it or restructure it better? Please let me know if I have missed anything out. I have been trying to get this working for 2 days.
Basics.php
<?php
namespace App;
class Basics extends Model
{
public $table = "users";
protected $fillable = [
'family_name',
'given_names'
];
}
BasicsController.php
class BasicsController extends Controller
{
public function index()
{
$user = \Auth::user();
return view('/details/basics', compact('user'));
}
public function update(Request $request, $id)
{
$basics = Basics::find($id);
$basics->family_name = $request->input('family_name');
$basics->given_names = $request->input('given_names');
$basics->save();
return redirect("/details/basics");
}
}
basics.blade.php
#extends ('layouts/app')
#section ('content')
{{--Do #includes for all form components with the components file--}}
#include ('layouts/header')
<main class="main">
<form action="/details/basics" method="POST">
<input type="hidden" name="_method" value="PATCH">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<fieldset>
<label>Family name</label>
<input type="text" name="family_name" placeholder="Family name" value="{{ old('family_name') }}" />
</fieldset>
<fieldset>
<label>Given names</label>
<input type="text" name="given_names" placeholder="Given names" value="{{ old('given_names') }}" />
</fieldset>
<button type="submit" value="Save" name="save" class="button button-primary button-wide">Save</button>
</form>
</main>
#endsection
web.php
Route::get('/', function () {
return view('welcome');
});
// Authentication Routes
Auth::routes();
Route::get('/logout', 'Auth\LogoutController#destroy');
Route::get('/home', 'DashboardController#index');
Route::get('/dashboard', function () {
$user = Auth::user();
return view('dashboard', compact('user'));
});
// Eligibility Assessments
Route::get('/assessment/student', 'AssessmentController#index');
Route::post('/assessment/results', 'AssessmentController#store');
// Details
Route::get('/details/basics', 'BasicsController#index');
Route::patch('/details/basics', 'BasicsController#update');
You need to add a rule in your post request which will exclude the email field when updating the model. This is why you're getting the email is not unique error. Although you're not posting the email field but still the save method is doing that. Try using post instead of patch. Just for debugging purposes in your Route.php
I'm trying to delete a single record by id. Instead, it deletes all records in that table.
Here's my code:
View
<form role="form" action="{{ route('status.delete', ['statusId' => $status->id]) }}" method="post">
<button type="submit" class="btn btn-default"><i class="fa fa-times"></i> Delete</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
Routes
Route::post('/status/{statusId}/delete', [
'uses' => '\Dashboard\Http\Controllers\StatusController#deleteStatus',
'as' => 'status.delete',
'middleware' => ['auth'],
]);
Controller
public function deleteStatus(Request $request, $statusId)
{
Auth::user()->statuses()->delete($statusId);
return redirect()->route('home')->with('success', 'Post deleted.');
}
Note: When I dd($statusId) it does provide the right ID for the status I'm deleting. So that part does work.
This is possible in Laravel 5.6 using the destroy method:
From the docs:
However, if you know the primary key of the model, you may delete the
model without retrieving it. To do so, call the destroy method
App\Model::destroy(1);
or to delete an array of ids:
App\Model::destroy([1, 2, 3]);
or by query:
App\Model::where('active', 0)->delete();
Unfortunately, the Eloquent builder does not support passing the id to delete.
Instead, you have to first find to model, then call delete on it:
$request->user()->statuses()->findOrFail($statusId)->delete();
you can delete the model by using another approach like
App\Models\ModelName::find(id)->delete()
but it throws nullPointerException that you have to handle
**Step 1 create route inside web.php**
Route::delete('/answers_delete/{id}', [App\Http\Controllers\AnswerController::class, 'delete'])->name('answers.delete');
**Step 2 Create method in your controller**
use App\Models\Answer; // use in top of this file
public function delete($id)
{
$ans = Answer::find($id);
$ans->delete();
session()->flash('success', 'Answer Deleted Successfully!!!');
return view('admin.anser.index');
}
**Step 3 define your route name inside form action(Note my case view file name index.blade.php and inside admin/answer/index.blade.php)*
<form action="{{ route('answers.delete', $answer->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger" style="display: inline;">Delete</button>
</form>