I'm using Laravel 5.2 and trying to do an add and delete a data that I already Inputted but when i clicked "Delete" button it gave me NotFoundHttpException.
Here's example of my delete function code in controller:
<?php
namespace App\Http\Controllers\Track;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
//use Illuminate\Support\Facades\Input;
use Validator;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Track as Track;
class TrackController extends Controller
{
/*Display track registry*/
public function index()
{
$data = array('track' => Track::all());
return view('admin.dashboard.tracks.track',$data);
}
/*Display create track form*/
public function create()
{
return view('admin.dashboard.tracks.createtrack');
}
/*Save data form*/
public function saveTrack(Request $request)
{
$input = $request->all();
$messages = array(
'trackCode.required'=>'Track code required.',
'trackCode.unique'=>'Track code already exist.',
'trackName.required'=>'Track name required.',
);
$rule = array(
'trackCode' => 'required|unique:track',
'trackName' => 'required|max:60',
);
$validator = Validator::make($input, $rule, $messages);
if($validator->fails()) {
#Directed to the same page with error message
return Redirect::back()->withErrors($validator)->withInput();
#Validate Success
}
$track = new Track;
$track->trackCode = $request['trackCode'];
$track->trackName = $request['trackName'];
if (! $track->save())
App::abort(500);
return Redirect::action('Track\TrackController#index')->with('successMessage','Track data "'.$input['trackName'].'" has been inserted.');
}
/*Delete data*/
public function delete($id)
{
echo $id;
/*$trackCode = Track::where('trackCode','=',$id)->first();
if($trackCode==null)
App::abort(404);
$trackCode->delete();
return Redirect::action('track');*/
}
}
and here's the part of my delete option code:
<div class="box-body">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 150px; text-align: center;">Track Code</th>
<th>Track Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($track as $itemTrack)
<tr id="track-list" name="track-list">
<td style="text-align: center;">{{ $itemTrack->trackCode }}</td>
<td>{{ $itemTrack->trackName }}</td>
<td><a href="{{{ action('Track\TrackController#delete',[$itemTrack->trackCode]) }}}" title="Delete" onclick="return confirm('Are you sure you want to delete this track : {{{$itemTrack->trackCode.' - '.$itemTrack->trackName }}}?')">
<span class="label label-danger"><i class="fa fa-trash"> Delete </i></span>
</a>
</td>
</tr>
#endforeach
</tbody>
</table>
<br/>
<button class="btn btn-success pull-right" type="submit">Add Data</button>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
whenever it appears the data and i try to delete it, it went to a page and there's NotFoundHttpException error instead of showing me the $id of the data.
Can someone help and explain? thanks
-Edited part-
Routes:
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => 'web'], function()
{
Route::auth();
});
//Route as admin
Route::group(['middleware' => ['web','role:admin']], function()
{
Route::get('/users/dashboard', 'UserController#index');
/*-----------------------------------------------Track Part---------------------------------------------------------*/
/*Track index*/
Route::get('/users/programs/track', array('as'=>'track', 'uses'=>'Track\TrackController#index'));
/*Create track form*/
Route::get('/users/programs/track/create', array('as'=>'track.create', 'uses'=>'Track\TrackController#create'));
/*Route to save track*/
Route::post('/users/programs/track/save', array('as'=>'track.save', 'uses'=>'Track\TrackController#saveTrack'));
/*Delete track*/
Route::get('/users/programs/track/{$id}/delete', array('as'=>'track.delete', 'uses'=>'Track\TrackController#delete'));
/*-----------------------------------------------Course Part---------------------------------------------------------*/
//Display course menu
Route::get('/users/programs/course', array('as'=>'course', 'uses'=>'Course\CourseController#index'));
//Delete course data
Route::get('/users/programs/course/{$id}/delete', array('as'=>'course.delete', 'uses'=>'Course\CourseController#delete'));
//Create course data
Route::post('/users/programs/course/create', array('as'=>'course.create', 'uses'=>'Course\CourseController#createCourse'));
//Edit course data
Route::get('/users/programs/course/{$id}/edit', array('as'=>'course.edit', 'uses'=>'Course\CourseController#editCourse'));
//Save editted course data
Route::put('/users/programs/course/{$id}/saveEdit', array('as'=>'course.saveEdit', 'uses'=>'Course\CourseController#saveEdit'));
});
I'm guessing that you are using DELETE in your route, which wouldn't work with an a link. You'd need to create a form and spoof the DELETE. You can find more about doing it here.
Alternatively, you can change Route::delete() to Route::get(), but this isn't recommended.
I think this could be do to with your triple braces. Try {{ action('Track\TrackController#create') }} instead.
More information read this link
Try this:
{!! action('track.delete',[$itemTrack->trackCode]) !!}
From documentation:
"If the method accepts route parameters, you may pass them as the second argument to the method:
$url = action('UserController#profile', ['id' => 1]);"
I guess 'id' wasn`t defined properly. Try this:
action('Track\TrackController#delete',['id' => $itemTrack->trackCode])
Replace delete Anchor tag with this:-
<a href="{{ url('users/programs/track/'.$itemTrack->trackCode.'/delete') }}" title="Delete" onclick="return confirm('Are you sure you want to delete this track : {{{$itemTrack->trackCode.' - '.$itemTrack->trackName }}}?')">
And change the delete Route:-
Route::match(['get', 'post'], '/users/programs/track/{id?}/delete', 'Track\#TrackController#delete');
Hope it Helps!
Related
sorry if the question is kind of newbie. I am new to php and laravel, still trying to learn through tutorial.
I am trying to pass the 'No' in my database to the url, so that the url when I clicked on Daftar, it will show
http://127.0.0.1:8000/search/{No}
Webpage designed
I did try to put it this way in my href tag but did not manage to get the result I want
here is my code
search.blade.php
#if(isset($namelist))
<table class="table table-hover">
<thread>
<tr>
<th>No</th>
<th>Nama</th>
<th>ID</th>
<th>Tindakan</th>
</tr>
</thread>
<tbody>
#if(count($namelist) > 0)
#foreach($namelist as $nama)
<tr>
<td>{{ $nama->No }}</td>
<td>{{ $nama->Name }}</td>
<td>{{ $nama->ID }}</td>
<td>
<a href="search/".$nama[No]>DAFTAR</a>
</td>
</tr>
#endforeach
#else
<tr><td>Tiada rekod ditemui, sila daftar secara manual di kaunter pendaftaran</td></tr>
#endif
</tbody>
</table>
#endif
</div>
</div>
</div>
</body>
</html>
searchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class searchController extends Controller
{
function search(request $request){
if(isset($_GET['query'])){
$search_text = $_GET['query'];
$namelist = DB::table('namelist')-> where ('ID','LIKE','%'.$search_text.'%')->paginate(100);
return view('search',['namelist'=>$namelist]);
}
elseif(isset($_GET['query'])){
$search_text1 = $_GET['query'];
$namelist = DB::table('namelist')-> where ('No','LIKE','%'.$search_text1.'%')->paginate(100);
return view('search',['namelist'=>$namelist1]);
}
else{
return view('search');
}
}
}
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\searchController;
use App\Http\Controllers\daftar;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
route::get('/search',[searchController::class, 'search'])->name('web.search');
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Thank you
You have multiple ways to do that. In my opinion, the simplest way would be
DAFTAR.
Actually, what you have already done. Only with the Bladesyntax. And there is a small mistake in your example. Namely, your double quotes. <a href="search/".$nama[No]>DAFTAR</a> should be:
DAFTAR or better DAFTAR.
For the sake of completeness. the most elegant way would be to work with components.
Try this
<td>
DAFTAR
</td>
Enter the variable at given_variable_here above.
Also, you did not prepare the route to accept the passed variable in your web.php. This can be corrected like this:
Route::get('/search/{No}',[searchController::class, 'search'])->name('web.search');
Lastly, I'm not too sure about capitalizing the 'N' in the No you want to use. Should you have problems, start by placing these in lowercase. And if you're using VS Code make sure to add the extensions Laravel Extra Intellisense, Laravel Blade Snippets and Laravel Snippets. They are a great help. Let me know if this helps.
I have a view that show some data and have edit feature, but when clicked edit button, user will be redirected to http://localhost:8000/posts/2/edit, I dont want post id appear in the URL, what should I do?
<table class="table table-bordered">
<tr>
<th width="20px" class="text-center">No</th>
<th>Title</th>
<th>Content</th>
<th width="280px" class="text-center">Action</th>
</tr>
#foreach ($posts as $post)
<tr>
<td class="text-center">{{ ++$i }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->content }}</td>
<td class="text-center">
<form action="{{ route('posts.destroy',$post->id) }}" method="POST">
<a class="btn btn-info btn-sm" href="{{ route('posts.show',$post->id) }}">Show</a>
<a class="btn btn-primary btn-sm" href="{{ route('posts.edit',$post->id) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Delete?')">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
here is the controller
public function edit(Post $post)
{
return view('posts.edit', compact('post'));
}
here is the route
Route::get('/', function () {
return view('welcome');
});
Route::resource('posts', App\Http\Controllers\PostController::class);
Auth::routes();
Thanks in advance
If you want to prevent users to edit posts that they did not create:
public function edit(Post $post)
{
if(Auth::user()->id != $post->user_id) {
throw new \Exception("Access denied", 403);
}
return view('posts.edit', compact('post'));
}
you need to use the Auth class offcourse:
use Illuminate\Support\Facades\Auth;
You need to do the same for the delete function
why you don't the id to appear in url. i can not see the reason to do that because there should be some unique key to edit the post. the only way i see is to add in the database a slug column and put it as unique. when adding a post put the title replacing space with '_' as a slug. make sure it is unique in validation. and in your edit and show code send the slug instead of the id.
route('posts.edit',$post->slug)
don't use dependency injection in controller
public function edit( $slug)
{
$post = Post::where('slug','=',$slug)->first();
return view('posts.edit', compact('post'));
}
hi
I think it will help you
your route will be like this:
Route::resource('posts', App\Http\Controllers\PostController::class)->except([
'edit'
]);
or
Route::resource('posts', App\Http\Controllers\PostController::class, ['only' => ['index', 'destroy', 'update' , 'create' , 'store']]);
or even you can write each route separately...
and write your edit route, separate :
Route::post('/post/edit', [App\Http\Controllers\PostController::class, "edit"])->name('post.edit');
delete #method('DELETE') from your blade and add this input to your blade :
<input type="hidden" name="post_id" value="{{$post->id}}" />
and change this :
public function edit(Post $post)
{
return view('posts.edit', compact('post'));
}
to this :
public function edit(Request $request)
{
$post_id = $request->post_id;
//write your code here
return view('posts.edit', compact('post'));
}
I wont to fetch data from database and show them in a view page as a table. I tried so many ways and didn't work. Also I have used member adding form as a model in my home.blade.php and it works fine.
here is my home.blade.php
<!-- show tasks -->
<div class="container-fluid">
<div class="container mt-4">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Task</th>
<th scope="col">Assigned Date</th>
<th socpe="col">Sign-off Date</th>
<th socpe="col">Edit/Delete</th>
</tr>
</thead>
#foreach($tasks as $task)
<tr>
<td>{{$task->id}}</td>
<td>{{$task->task}}</td>
<td>{{$task->assigned_date}}</td>
<td>{{$task->end_date}}</td>
<td>
Delete
Edite
</td>
</tr>
#endforeach
</table>
</div>
</div>
<!-- end Show tasks -->
here is my taskController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\task;
class taskController extends Controller
{
public function store(Request $request){
$this->validate($request,[
'task'=>['required', 'max:100', 'min:5'],
'assignedDate' => ['required', 'date'],
'endDate' => ['required', 'date'],
]);
$task = new task;
$task->task = $request->task;
$task->assigned_date = $request->assignedDate;
$task->end_date = $request->endDate;
$task->save();
return redirect()->back()->with('message', 'Task added successfuly');
}
public function getdata()
{
$data=task::all();
return view('home')->with('tasks', $data);
}
}
and here is my web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::post('/saveTask', 'taskcontroller#store');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
So, What am I doing wrong here? Can somebody please explain me?
Change your Last Route to
Route::get('/home', 'HomeController#getdata')->name('home');
Please look into my code,
this is my web.php
Route::get('test', function (Request $request) {
$data = MyTableResource::collection(MyTable::paginate(10));
$headers = ['col1', 'col2', 'col3'];
return view('test.index', compact('data', 'headers'));
});
Here is my blade file,
<table md-table>
<thead>
<tr>
#foreach($headers as $header)
<th><span>{{$header}}</span></th>
#endforeach
</tr>
</thead>
<tbody>
#foreach($data as $d)
<tr>
<td>{{$d->id}}</td>
<td>{{$d->primary_identifier}}</td>
<td>{{$d->order_date}}</td>
</tr>
#endforeach
</tbody>
</table>
<div class = "table-paginate">
{{ $orders->links() }}
</div>
My problem is that,
when I refresh my page, the URL is
http://localhost/test?page=1
And when I click on any link, the URL is just replacing with its number (http://localhost/test?page=2), not redirecting.
I inspect the pagination link, it seems like
<li class="page-item" aria-current="page">
<a class="page-link" href="http://amzmarketplace.localhost.tom/test?page=2">2</a>
</li>
It is working when I added and attribute to <a> tag, that target="_self".
But how can I add this attribute in Laravel pagination URL or is there any other way to solve this issue?
In Laravel 7.x you can customize URL in route file or controller like:
Route::get('test', function (Request $request) {
$data = MyTableResource::collection(MyTable::paginate(10));
$data->withPath('custom/url');
...
});
OR
Also append sort=votes to each pagination link, you should make the following call to appends in view, like:
{{ $data->appends(['sort' => 'votes'])->links() }}
Check this out the laravel.com/docs/7.x/pagination#displaying-pagination-results documentation link
so, the view page already display all data. but there is an error "not found exception" when the delete button will be pressed. URL that showed in my browser when i press delete button is "http://localhost:8000/admin/hapusdataruang/69"
This is the view page
<table id="datatable-buttons" class="table table-striped table-bordered">
<thead>
<tr>
<th>ID Ruang</th>
<th>Nama Ruangan</th>
<th>Keterangan</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
#foreach($showruang as $rooms)
<tr>
<td>{{$rooms->id_ruang}}</td>
<td>{{$rooms->nm_ruang}}</td>
<td>{{$rooms->keterangan}}</td>
<td>
<form action="{{ url('/admin/hapusdataruang', $rooms->id_ruang) }}" method="post">
{{ csrf_field() }}
{{ method_field('DELETE') }}
Edit
<button class="btn btn-sm btn-danger" type="submit" onclick="return confirm('Yakin ingin menghapus data?')">Delete</button>
</form>
</td>
</tr>
#endforeach
</tbody>
This is the AdminController
public function destroyruang($id_ruang)
{
$ruang = Ruang::where('id_ruang',$id_ruang)->first();
$ruang->delete();
return redirect(url('/admin/dataruang'));
}
This is the admin route
Route::post('/hapusdataruang', 'AdminController#destroyruang', function () {
$users[] = Auth::user();
$users[] = Auth::guard()->user();
$users[] = Auth::guard('admin')->user();
//dd($users);
})->name('destroydataruang');
This is Ruang Model
use Illuminate\Database\Eloquent\Model;
namespace App;
class Ruang extends Model
{
protected $table = 'tr_ruang';
protected $primaryKey = 'id_ruang';
protected $dates = ['deleted_at'];
protected $fillable = ['keterangan','nm_ruang'];
}
The problem is in your routes file. You are submitting the form via a POST request to this url /admin/hapusdataruang, but you have {{ method_field('DELETE') }} in your form, so your route needs to be able to accept DELETE requests.
Your code:
Route::post('/hapusdataruang', 'AdminController#destroyruang', function () {
is for POST requests, not DELETE requests, so change it to:
Route::delete('/hapusdataruang', 'AdminController#destroyruang', function () {
change this code
Route::post('/hapusdataruang', 'AdminController#destroyruang', function () {
to
Route::delete('/hapusdataruang', 'AdminController#destroyruang', function () {
If You want to use the POST Request for deleting an entry from your database then you don't have to specify {{ method_field('DELETE') }} in your form, if you remove this from your form declaration then your existing route will work, but if you want to use the DELETE Request then you have to specify the Route as Route::delete('/yourpath','ControllerName#methodname');