multiple variables in routes. A route isn't leading to the controller defined blade - laravel

I have "show" and "edit" two routes. It's showing two different url. But "edit" route is using the 'show' blade, which is the SAME as the "show" route. How to lead the "edit" route to the 'edit' blade?
here is the web.php:
Route::get('/{user}/{course}', 'CoursesController#show')->name('course.show');
Route::get('/{user}/edit_{course}', 'CoursesController#edit')->name('course.edit');
here is the controller:
public function edit(Course $course) {
return view('courses.edit', compact('course'));
}
public function show(Course $course) {
return view('courses.show', compact('course'));
}
here is the index blade:
<a class="btn btn-xs btn-primary" href="{{ route("course.show", [auth()->user()->username, $course->title. $course->id] ) }}"> VIEW </a>
<a class="btn btn-xs btn-info" href="{{ route("course.edit", [auth()->user()->username, $course->title. $course->id]) }}"> EDIT </a>

Change the order or your routes in your routes files web.php
Route::get('/{user}/edit_{course}', 'CoursesController#edit')->name('course.edit'); //This one goes first.
Route::get('/{user}/{course}', 'CoursesController#show')->name('course.show');
Your show route is working as a wildcard if you invert the order as shown the edit route will catch it first when the second variable begins with edit_.

Related

Edit button not working perfectly on Laraver resource controller

I am using Laravel resource routing, all coding are ok, but when I am trying to press on the edit button from index page, its getting the url: localhost/8000/categories/id/edit but not uploading my edit.blade.php file. The loaded page is showing 404, not found.
index.blade.php
<div class = "span2">
<a href="{{url('/categories/'.$category->id.'/edit')}}">
<i class="halflings-icon white edit"></i>
</a>
</div>
CategoryController.php
public function edit(Category $category)
{
return view('admin.category.edit',compact('category'));
}
web.php
Route::resource('/categories/',CategoryController::class);

How to set up a beautiful url in laravel 8?

Now my url looks like this
localhost/3
But I want the path to look like this
localhost/some-text
To do this, I have a special url field in the Ad model, where the desired address is located. But going through it, I get 404
I have a route
Route::get('/{url}', [App\Http\Controllers\IndexController::class, 'show'])->name('show');
Method
public function show($url) {
$ad = Ad::where('url', $url)->first();
return view('ad', compact('ad'));
}
And btn
<a href="{{ route('show', ['url' => $ad->url]) }}">
<button type="button" class="btn btn-sm btn-outline-secondary">View</button>
</a>
To create better links just use slug
I use laravel slugable

Laravel 2 submit buttons in the same form

I am building a CRUD with Laravel. Each category hasMany attachments and each attachment belongsTo a category.
In the category.edit view I want to give the user the possibility of deleting the attachments (singularly) from the Category. I tried this method but it did not work:
Registering route for the attachment:
Route::group(['middleware' => ['auth']], function () {
Route::delete('attachment/{id}', 'AttachmentController#delete')->name('attachment');
});
Handling the delete building the AttachmentController#delete method:
class AttachmentController extends Controller
{
public function delete($id) {
$toDelete = Attachment::findOrFail($id);
$toDelete->delete();
return redirect()->back();
}
}
In the CategoryController (edit method), I fetch the attachments linked to each category to be rendered inside the view:
public function edit($category)
{
$wildcard = $category;
$category = Category::findOrFail($wildcard);
$attachments = App\Category::findOrFail($wildcard)->attachments()->get()->toArray();
return view('category.edit', [
'category' => $category,
'attachments' => $attachments
]);
}
In the view, I render the attachment and the button to delete. I am fully aware of the error of having a form inside another form, nevertheless I do not know antoher approach to submit this delete request.
// update Category form
#foreach ($attachments as $attachment)
<div class="row">
<div class="col-4">
<img style="width: 100%;" src={{ $attachment['url'] }} alt="">
</div>
<div class="col-4">
<div>
<p class="general_par general_url">{{ $attachment['url'] }}</p>
</div>
</div>
<div class="col-4">
<form action="{{ route('attachment', $attachment['id']) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete Image</button>
</form>
</div>
</div>
<hr>
#endforeach
// end of update Category form
Should I build a deleteAttachment method inside the CategoryController? If so, how can I still submit the Delete request? Also, if any other Model in the future will have attachments, should I build a deleteAttachment method inside each controller? That is cumbersome. Thanks in advance
if you don't like to use form, then use tag:
<a class="btn btn-danger" href="{{ route('attachment', $attachment['id']) }}">Delete Image</a>
And redefine the route to Route::get(...)
(or maybe use ajax for POST method if that is required)

Laravel NotFoundHttpException although route exits

I added a new route as:
Route::post('friendSend/{uid}','FriendController#sendFriendRequest')->name('friends.add');
and called it as a hyperlink to submit form:
<a href="{{route('friends.add',$user->uid)}}"
onclick="event.preventDefault();
document.getElementById('addfriend-form).submit();">
<i class="glyphicon glyphicon-facetime-video" style="color:#F44336;"></i> Add Friend
</a>
<form action="{{route('friends.add',$user->uid)}}" method="post" id="addfriend-form">
{{ csrf_field() }}
</form>
However when I click on the said link, I get redirected to /friendSend with the said error.
the route is visible in:
php artisan route:list
which makes sense since I called it via it's name 'friends.add'. It doesn't even go the controller.
I've already tried the following:
Laravel NotFoundHttpException although route exists
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Friend;
use Auth;
class FriendController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return redirect()->route('home');
}
public function sendFriendRequest($id)
{
echo "hello world";
}
}
Update:
Manually entering the url as /friendSend/2 (or any number for that matter) works.
You are missing a ' in the onclick javascript.
<a href="{{route('friends.add',$user->uid)}}"
onclick="event.preventDefault();
document.getElementById('addfriend-form').submit();">
<i class="glyphicon glyphicon-facetime-video" style="color:#F44336;"></i> Add Friend
</a>
<form action="{{route('friends.add',$user->uid)}}" method="post" id="addfriend-form">
{{ csrf_field() }}
</form>
If this doesn't work, what is the href on the generated page? Do you have multiple of these forms on a single page?
I thing you are doing wrong on set the url in form submit.You are adding route like
href="{{route('friends.add',$user->uid)}}"
Just modified it as
href="{{route('friends.add',['uid' => $user->uid])}}"
You can refer Laravel Named Routes

My function is deleting a different row to the one I intended, Laravel 5.4?

When I press remove, it removes the last charity in the database that belongs to the current user.
View (Button that deletes):
<a href="#"> <button class="btn btn-danger pull-right btnPopover" data-
toggle="popover" data-placement="top"> Remove </button> </a>
View (JS that is called):
function ConfirmDelete()
{
true;
}
$(document).ready(function()
{
$('.btnPopover').popover(
{
html: 'true',
title: '<strong> Are you sure you want to Remove? </strong>',
content: '<form style="display: inline;" action="{{
URL::to('remove', array($favourite->id)) }} "> <button class = "btn
btn-success glyphicon glyphicon-ok" onclick="return
ConfirmDelete()"> Yes </button> </form> <button class = "btn btn-
danger glyphicon glyphicon-remove"> No </button> '
});
$('.btnPopover').on('click', function (e)
{
$('.btnPopover').not(this).popover('hide');
});
Route:
Route::get('remove/{id}', 'HomeController#removeFavourite');
Controller (removeFavourite function):
public function removeFavourite($id)
{
Favourites::where('id', $id)->delete();
Session::flash('flash_message', 'Removed successfully!');
return back();
}
The strange thing is, is that I am using the exact same function and JS call in another part of the application and it is working fine!
The problem is, that it deletes the last record belonging to that user in the database.
Thanks
I don't know exactly what your code looks like, but the problem is that your JS is only valid for the last iteration of the loop, which sounds like what you're experiencing.
To fix it, you can move the form inside the popover button so that you can get the correct form link:
Example (moving the form):
<button class="btn btn-danger pull-right btnPopover" data-toggle="popover" data-placement="top" data-content='<form style="display: inline;" action="{{ URL::to('remove', array($favourite->id)) }} "> <button class = "btn btn-success glyphicon glyphicon-ok" onclick="return ConfirmDelete()"> Yes </button> </form> <button class = "btn btn-danger glyphicon glyphicon-remove"> No </button> '> Remove </button>
JS:
$(document).ready(function()
{
$('.btnPopover').popover(
{
html: 'true',
title: '<strong> Are you sure you want to Remove? </strong>',
});
$('.btnPopover').on('click', function (e)
{
$('.btnPopover').not(this).popover('hide');
});
....
This could be a little cleaner if you could access the parent button from the popover, but I couldn't find a way to do that in the API.
Check whether the $id you retrieve in your program(I assume there is some code missing in the question which finds the $id) is the one you want to delete.
Level official documentation says to use following code for deleting models:
$flight = App\Flight::find(1);
$flight->delete();
Find retrieves single model, and where returns a collection, so that might be the issue.
Also make sure that you pass the specific $id of the favourite that needs to be deleted, if not you'll always be deleting the last $id in your loop.
Official Docs

Resources