Route not going where it's supposed to - laravel

I'm getting this error. This error comes in when I hit the delete button
MethodNotAllowedHttpException in RouteCollection.php line 251:
the problem is as far as I know my routes is correct.
My cart.blade.php
#foreach($cartItems as $cartItem)
<tr>
<td>
<img src="{!! asset("product_images/$cartItem->img") !!}" alt="..." class="img-responsive">
</td>
<td>{!! $cartItem->name !!}</td>
<td>{!! $cartItem->qty !!}</td>
<td>R {!! $cartItem->qty * $cartItem->price !!}</td>
<td>
{!! Form::open(array('method' => 'Delete', 'route' => array('deleting', $cartItem->rowId))) !!}
<button class="btn btn-warning">Delete 2</button>
{!! Form::close() !!}
</td>
</tr>
#endforeach
My routes
Route::put('/product/deleting/{id}', [
'uses' => 'OpenController#deleting',
'as' => 'deleting'
]);
my controller
public function deleting($id)
{
echo "string";
}

You are using method DELETE on your form:
Form::open(array('method' => 'Delete',
but defined the method PUT in your route:
Route::put('/product/deleting/{id}', [
Try to change the route to
Route::delete('/product/deleting/{id}', [

Try using 'delete' instead of 'put' in your routes file.

Related

Trying to get property of non-object - laravel 5.4

I am using Laravel eloquent relationship, when i use
{{$subject->cat}}
i receive a json response like below
{"id":13,"name":"Fsc","created_at":"2017-10-23 00:00:00","updated_at":"2017-10-23 00:00:00"}
as i have 2nd object "name" here i tried
{{$subject->cat->name}}
but got error
Trying to get property of non-object
while i am using same approach for other table and copied same method here but getting error.
See my Blade file code, i am calling object inside foreach loop
#foreach ($subjects as $subject)
<tr>
<td width="8%">{{$subject->id}}</td>
<td width="22%">{{$subject->subject}} </td>
<td width="22%">{{$subject->cat->name}}</td>
<!-- <a class="btn btn-success btn-sm" href="{{route('subjects.show', $subject->id)}}"><i class="fa fa-eye"></i></a> | -->
<i class="fa fa-pencil"></i> |
{!! Form::open(['route' => ['subjects.destroy', $subject->id], 'method' => 'DELETE', 'class' => 'delete-form']) !!}
{{ Form::button('<i class="fa fa-times" aria-hidden="true"></i>', ['class' => 'btn btn-danger btn-sm pull-left', 'type' => 'submit']) }}
{!! Form::close() !!}
</td>
</tr>
#endforeach
First Use json_decode($json);
Takes a JSON encoded string and converts it into a PHP variable.
Then
Use {{$subject->cat}}
Just use json_decode like:
$var = json_decode($subject, true);
Then you can use:
{{$subject->cat->name}}
See more here!
Hope this helps you!
You need to decode your json and then use like this:
$result = json_decode ($subject->cat);
echo $result->name;
Use your variable name in place of $result
For insight here is pastebin demo
Try this
$cat = json_decode($subject->cat); // returns object
{{ $cat['name'] }}
or
$cat = json_decode($subject->cat, true); // returns array
{{ $cat['name'] }}

Laravel a form isn't reset after successful submit

This is my controller:
class GuestbookController extends Controller
{
public function viewAll(Request $request)
{
if ($request->method() === 'POST') {
$this->validate($request, [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
$message = new Message();
$message->username = $request->get('username');
$message->email = $request->get('email');
$message->homepage = $request->get('homepage');
$message->text = strip_tags($request->get('text'));
$message->ip = $request->ip();
$message->browser = get_browser($request->header('User-Agent'))->browser;
$message->save();
}
$messages = Message::sortable(['created_at' => 'desc'])->paginate(25);
return view('Guestbook.viewAll', [
'newMessage' => new Message(),
'messages' => $messages
]);
}
}
I am using this plugin. viewAll handles both GET and POST requests, but the problem is that the form isn't reset when I successfully submit data keeping all the previous input values.
I've checked what the server sends and it seems like it sends inputs with last values in them. I've no idea what to do, please help!
View:
#extends('base')
#section('title', 'Guestbook')
#section('baseContent')
{!! BootForm::open(['model' => $newMessage]) !!}
{!! BootForm::text('username') !!}
{!! BootForm::email('email') !!}
{!! BootForm::text('homepage') !!}
{!! BootForm::textarea('text') !!}
{!! captcha_img() !!}
{!! BootForm::text('captcha') !!}
{!! BootForm::submit('Send') !!}
{!! BootForm::close() !!}
#if (count($messages) > 0)
<table class="table table-bordered">
<tr>
<td>#sortablelink('username', 'Username')</td>
<td>#sortablelink('email', 'Email')</td>
<td>Homepage</td>
<td>#sortablelink('created_at', 'Data added')</td>
<td>Message</td>
</tr>
#foreach ($messages as $message)
<tr>
<td>{{ $message->username }}</td>
<td>{{ $message->email }}</td>
<td>{{ $message->homepage }}</td>
<td>{{ $message->created_at }}</td>
<td>{{ $message->message }}</td>
</tr>
#endforeach
</table>
#else
There is nothing to display here.
#endif
{!! $messages->appends(\Request::except('page'))->render() !!}
#endsection
See all code here.
BootForm is compiled like this
<div class="form-group">
<label for="username" class="control-label col-md-2">Username</label>
<div class="col-md-10">
<input type="text" value={{old('username')}} name="username" class="form-control">
</div>
The old('params') is a helper method which keeps the previous inputs in session. And secondly, you have model associated with it.
I hope this helps

Laravel: Route [users.edit] not defined

I have created a demo application in Laravel 4, for some learning experience. The routes.php is as follows:
Route::get('/', function()
{
return View::make('hello');
});
Route::group(['prefix' => 'users', 'before' => 'auth'], function () {
Route::get('dashboard', function () {
$layout = View::make('users.dashboard');
$layout->title = "Dashboard";
$layout->content = View::make('users.dashboard');
return $layout;
});
Route::get('/all/', [ 'as' => 'users.index', 'uses' => 'UserController#all']);
Route::get('/create/', [ 'as' => 'users.create', 'uses' => 'UserController#create']);
Route::get('users/login', [ 'as' => 'users.login', 'uses' => 'UserController#getLogin']);
Route::post('users/login', [ 'as' => 'users.login', 'uses' => 'UserController#postSignin']);
Route::get('users/logout', [ 'as' => 'users.logout', 'uses' => 'UserController#getLogout']);
Route::resource('/','UserController');
});
Route::controller('users', 'UserController');
Here, I prefixed the "users". However, Trying logging in with/out correct login details, it shows only the login page instead of showing up the error message on the login page or dashboard.
Any suggestion? FYI,
The index.blade.php in app\views\users is below:
#extends('users.user')
#section('title', 'User Listing Page')
#section('description', 'This is the user listing page')
#section('main')
<h1>All Users</h1>
<p>{{ link_to_route('users.create', 'Add new user') }}</p>
<h1>Login</h1>
<p>{{ link_to_route('users.login', 'Login') }}</p>
<table>
<tr>
<td>{{ $users->links() }}</td>
</tr>
</table>
#if ($users->count())
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Username</th>
<th>Email</th>
<th>Phone</th>
<th>Name</th>
</tr>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td>{{ $user->username }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->phone }}</td>
<td>{{ $user->name }}</td>
<td>{{ link_to_route('users.edit', 'Edit', array($user->id), array('class' => 'btn btn-info')) }}</td>
<td>{{ Form::open(array('method' => 'DELETE', 'route' => array('users.destroy', $user->id))) }}
{{ Form::submit('Delete', array('class' => 'btn btn-danger')) }}
{{ Form::close() }}
</td>
</tr>
#endforeach
</tbody>
</table>
<table>
<tr>
<td>{{ $users->links() }}</td>
</tr>
</table>
#else
There are no users
#endif
#stop
The script login.blade.php (on the same location as above) as follows:
#extends('users.user')
#section('main')
<h1>Login</h1>
{{ Form::open(array('route' => 'users.login')) }}
<ul>
<li>
{{ Form::label('username', 'Username:') }}
{{ Form::text('username') }}
</li>
<li>
{{ Form::label('password', 'Password:') }}
{{ Form::password('password') }}
</li>
<li>
{{ Form::submit('Submit', array('class' => 'btn')) }}
</li>
</ul>
{{ Form::close() }}
#if ($errors->any())
<ul>
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</ul>
#endif
#stop
There is no users.edit route defined in your routes file. Hence, you are bound to receive that error. There's no users.edit route in your code.
Route::group(['prefix' => 'users', 'before' => 'auth'], function () {
Route::get('dashboard', function () {
$layout = View::make('users.dashboard');
$layout->title = "Dashboard";
$layout->content = View::make('users.dashboard');
return $layout;
});
Route::get('/all/', [ 'as' => 'users.index', 'uses' => 'UserController#all']);
Route::get('/create/', [ 'as' => 'users.create', 'uses' => 'UserController#create']);
Route::get('users/login', [ 'as' => 'users.login', 'uses' => 'UserController#getLogin']);
Route::post('users/login', [ 'as' => 'users.login', 'uses' => 'UserController#postSignin']);
Route::get('users/logout', [ 'as' => 'users.logout', 'uses' => 'UserController#getLogout']);
Route::resource('/','UserController');
});
Add the following route somewhere in your routes file and the error should disappear:
Route::get('/edit/', [ 'as' => 'users.edit', 'uses' => 'UserController#edit']);
Note: You need to replace the controller method name edit to whatever you have defined.
UPDATE 1
That is because, you have 'before' => 'auth' parameter passed in your Route::group() method. Just remove users from edit route and I hope that should do the job for you.
Just A Side note
I presume that you are new in laravel and have less amount of experience with the framework. I would recommend you to go with this only in order to get your hands dirty with the basics. Then once you start gaining the experience and know how things work behind the scenes, you can jump off to the next level.
If I were at your place, I wouldn't have gone with the code that you have provided, instead I would have kept it way too simple for now. My routes.php file would be like this:
/* Routes for users not logged in. */
Route::get('/all', 'UserController#all');
Route::get('/create', 'UserController#create');
Route::get('users/login', 'UserController#getLogin');
Route::post('users/login', 'UserController#postSignin');
Route::get('users/logout', 'UserController#getLogout');
/* Routes for logged in users */
Route::get('/users/dashboard', 'UserSessionsController#dashboard');
Route::get('/users/edit/{id}', 'UserSessionsController#edit');
And then in your view file:
EDIT
Then I would have used the middleware only inside the UserSessionsController file like this:
/**
* Check if the user is authenticated.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth'); // or any other middleware you have.
}
UPDATE 2:
Learn more about the middleware from the following links:
For version: 5
Official Docs
Matt Stauffer On Middleware
For version: 5.1
Official Docs
Youtube Video
For version: 5.2
Official Docs
Hope this helps you out. Happy Coding. Cheers.
in Laravel 8 it's a bit different
Route::get('/users/edit',[UserController::class, 'edit']);

laravel 5 not deleting user record

All i want to do is simply delete a user form the database.
My Route is a resource as seen below:
Route::resource('users', 'UserController');
So this should mean that the destroy action in my UserController should be the place for my code.
So my controller action is below:
public function destroy($id)
{
$user = User::find($id);
$user->delete();
return Redirect::back();
}
Now when i click the delete button, which links to /users/destroy/4
it should find the user with id 4 and then delete it.
Instead i get the error
NotFoundHttpException in RouteCollection.php line 145:
EDIT:
#foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->username }}</td>
<td>{{$user->HWID}}</td>
<td>{{$user->name}}</td>
<td class="tools">
<i class="fa fa-pencil-square-o fa-lg"></i>
<i class="fa fa-trash fa-lg"></i>
</td>
</tr>
#endforeach
I dont know if it's possible to directly delete a user from your database via a link as you specified in your table.
My work around for this is to first point the user to the show function in your controller. And giving the user an overview of the information of the user itself.
This page contains a form with the DELETE method. Below the information of the user I put a delete button which will submit the form with the DELETE method to the URL: /users/4
Cause the link: /users/destroy/4 is not a valid resource link.
See this link for extra information about the resource controller links: Resource Controller
Example delete/show page of my own application:
{!! Form::model($ManagementUser, array('method' => 'DELETE', 'url' => 'admin/management/' . $ManagementUser->id, 'role' => 'form')) !!}
<div class="box-body">
<div class="form-group">
<label>Name</label>
{!! Form::text('name', Input::old('name'), array('class' => 'form-control', 'placeholder' => 'Name', 'name' => 'name', 'disabled')) !!}
</div>
<div class="form-group">
<label>E-mailaddress</label>
{!! Form::text('email', Input::old('email'), array('class' => 'form-control', 'placeholder' => 'E-Mail', 'name' => 'email', 'disabled')) !!}
</div>
{!! Form::submit('Delete', array('class' => 'btn btn-block btn-default')) !!}
</div>
{!! Form::close() !!}
In Resource Controller, destroy action is handled by DELETE method. Not GET method. Currently you are accessing a route with GET method that is not registered. The following command will help you to understand Resource Routes that you registered.
php artisan route:list
GET
<i class="fa fa-trash fa-lg"></i>
DELETE (You can delete the record by using form and DELETE method as follows)
<form action="{{ route('users.destroy', $user->id) }}" method="POST">
<input type="hidden" name="_method" value="DELETE" />
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" />
<button><i class="fa fa-trash fa-lg"></i></button>
</form>
Reference
Resource Controller
Method Spoofing

Wildcards in Laravel

With the following code, I'm trying to pass a wildcard to my controller but I'm not sure how I can pass the URL dynamically and I'm not sure how to do this without creating a route for each url, which would take forever. Currently, I'm attempting to do it like so:
<a href="{{ route('purchase-get') }}/$item->name">
Here is the rest of the code
<tbody class="text-center">
#foreach (array_chunk($items->all(), 3) as $item_each)
<tr>
#foreach($item_each as $item)
<td>
<a href="{{ route('purchase-get') }}/$item->name">
{{ HTML::image($item->image_url, 'item-image', array('class' => 'item-image-row')) }}
<h4>{{ $item->item }}</h4>
<span class="text-muted">{{ $item->cost }}</span>
</a>
</td>
#endforeach
</tr>
#endforeach
</tbody>
You can link to a wildcard with named routes:
Route::get('/', array('as' => 'index', function()
{
$slug = 'product-1';
return 'link to product';
}));
Then catch the names route with the wildcard slug:
Route::get('products/{slug}', array('as' => 'products', function($slug)
{
$product = Product::where('slug','=',$slug)->first();
return $product;
}));

Resources