How to update exsiting row in database in laravel5 - php

I am new in laravel and I want to update an existing row in database,but when I click on send button in view (for example 127.0.0.1/laravel/public/Article/update/3 ) I encounter the following error:
MethodNotAllowedHttpException in RouteCollection.php line 201:
Here is my code
Route
Route::get('Article/edit/{id}','ArticleController#edit');
Route::get('Article/update/{id}','ArticleController#update');
ArticleController
public function edit($id)
{
$change = Article::find($id);
return view('edit',compact('change'));
}
public function Update($id, Request $request)
{
Article::update($request->all());
return redirect('Article');
}
Model
public $table = 'Article';
protected $fillable = ['title' , 'body'];
edit.blade.php
<h1>ویرایش بست {{$change->title}}</h1>
{!! Form::model($change ,['method'=>'patch' , 'url'=>['Article/update' , $change->id ]]) !!}
{!! Form::label('title','عنوان') !!}
{!! Form::text('title') !!}
<br>
{!! Form::label('body','متن') !!}
{!! Form::textarea('body') !!}
<br>
{!! Form::submit('send') !!}
{!! Form::close() !!}
#if($errors->any())
<ul class ='alert alert-danger'>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif

The easiest way to resolve routing issues with Laravel is to use 'artisan'.
http://laravel.com/docs/5.1/artisan
If you use this command:
php artisan route:list
You'll see every possible route and HTTP verb available for use. Your error is in the RouteCollection so you can always fix these issues by looking at your app/http/routes.php file.
You defined a route as follows:
Route::get('Article/update/{id}','ArticleController#update');
Then you call that route via your form as follows:
{!! Form::model($change ,['method'=>'patch' , 'url'=>['Article/update' , $change->id ]]) !!}
Your routes.php GET definition does not match your form's PATCH method, so you're getting a method not allowed exception because the PATCH route is not defined.
You need this line of code in your routes.php file:
Route::patch('article/update/{id}','ArticleController#update');
I would highly recommend using this instead of defining each method individually:
Route::resource('article', 'ArticleController');
Then run the following command again with artisan to see all routes created:
php artisan route:list

Related

Laravel Middleware Performing Action Before Form Submission

I am just creating a random app to check if the user is eligible for voting or not. I am using middleware to check if age is less than 18 then redirect to /age/validate. But the problem is the middleware is performing action before form submission. Please help.
Form::
{!! Form::open(['action'=>'AgeController#store', 'method'=>'POST']) !!}
{!! Form::number('age', null) !!}
{!! Form::submit('Check') !!}
{!! Form::close() !!}
Middleware::
public function handle($request, Closure $next)
{
if($request->age <= 18){
return redirect()->route('noteligble');
}
return $next($request);
}
Route:
Route::get('/age/validate', function(){
echo 'You are not eligible to vote';
})->name('noteligble');
Route::resource('checkage', 'AgeController')->middleware('agechecker');
Please Help me how i can make middleware work only after form submission.
A middleware is executed before every request. You're assigning the middleware to the whole resource and therefore to the route which displays the form.
The solution
Assign the middleware only to the store method in the controller. Remove the ->middleware('agechecker') method call from your routes file and add assign that in your controller constructor like this:
public function __construct()
{
$this->middleware('agechecker')
->only(['store']);
}

Laravel 5: not able to use pagination, I get error "Call to undefined method Illuminate\Database\Eloquent\Collection::render()"

I am quite new to Laravel and started to play around with L5 and tried to paginate my data (from my HomeController method):
someMethod(){
...
$messages = Message::paginate(50)->sortByDesc('timestamp');
return view('home', ['messages' => $messages]);
}
in my home.blade view:
...
<div class="list-group">
#foreach($messages as $message)
#if(!$message->processed)
...
#endif
#endforeach
</div>
{!! $messages->render() !!}
...
I get the error below:
FatalErrorException in b706d42af4b0adc08aee8abb2fdf4ba9 line 105:
Call to undefined method Illuminate\Database\Eloquent\Collection::render()
in b706d42af4b0adc08aee8abb2fdf4ba9 line 105
I followed the logic from the Pagination doc page : https://laravel.com/docs/5.1/pagination#basic-usage and https://laravel.com/docs/5.1/pagination#displaying-results-in-a-view
You have an error in your code. Try this:
$messages = Message::orderBy('timestamp', 'desc')->paginate(50);

Laravel session Flash Message Not working

Session message is not working i tried this code and many fix available online
Here id my store function `
public function store(Request $request)
{
// dd($request->all());
$this->validate($request, [
'name' =>'required',
'username' =>'required',
'email' =>'required',
'address' =>'required',
'likes' =>'required',
'gender' =>'required'
]);
$input = $request->all();
Contacts::create($input);
Session::put('flash_message', 'Task successfully added!');
return redirect()->back();
}
And Retrieving by this code
#if(Session::has('flash_message'))
<div class="alert alert-success">
{{ Session::get('flash_message') }}
</div>
#endif
I resolved issue with laravel 6.x
As soon as I moved \Illuminate\Session\Middleware\StartSession::class and \Illuminate\View\Middleware\ShareErrorsFromSession::class from web $middlewareGroups to $middleware in app\Http\Kernel.php everything started working as expected.
I Resolved the Issue with laravel 5.2.
I was having route like this
Route::group(['middleware' => [ 'web','auth']], function () {
.......
}
So Removed the web middle ware
Route::group(['middleware' => ['auth']], function () {
.......
}
and its start working
Analysis: By default Laravel Add web Middleware.
check by php artisan route:list it shows web, web,auth .
so by defining it again redirect two time for the web middleware.
I RESOLVED the issue with laravel 5.2.
I was having all the routes inside this:
Route::group(['middleware' => 'web'], function() {
I remove it because when I used the command php artisan route:list in the Name Middleware column the "web" shows to times: web, web.
If you have AUTH replace by:
Route::group(['middleware' => 'auth'], function() {
Also I delete a duplicate route (in routes.php). Now I just have:
Route::resource('/publicaciones', 'PublicacionesController');
My controller:
return redirect()->back()->with('success', 'Saved!');
My view:
#if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
#endif
have you include the following namespace
use Session;
instead of the following code
Session::put('flash_message', 'Task successfully added!');
use
Session::flash('flash_message', 'Task successfully added!');
in instead to
return redirect()->back();
try using
return redirect()->route('your route');
When the validation fails, no further code is executed and the previous page is loaded again. This is the reason why session message is not working. In order to check for any validation errors use the following code snippet at the top of your blade file.
#if ($errors->any())
#foreach ($errors->all() as $error)
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $error }}</strong>
</div>
#endforeach
#endif
A bit late for this forum. I encounter this problem, I've been different sites searching for the right solution but none works. Here's my case, I'm using v6.0, and I put the route inside routes\api.php.
I think there is difference of putting the route to the right place or file, can't explain more.
Here's how I solved, I transfer the route from routes\api.php to routes\web.php and thats it after so many researching I now successfully display the flash message.
Try this code
Session::flash('flash_message', 'Task successfully added!');
Session::save();
return redirect()->back();
This worked for me
This will work in case "Session" fails to display errors in your blade view.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Laravel 5 - FatalErrorException: Class 'User' not found

I am very new to Laravel and just started setting up things with Laravel 5. I am attempting to create a simple user authentication app with Laravel.
I created register.blade.php which includes form to register user.
Here is my routes.php
Route::post('/register', function()
{
$user = new User;
$user->email = Input::get('email');
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();
$theEmail = Input::get('email');
return View::make('thanks')->with('theEmail', $theEmail);
});
Here is the section of register.blade.php which creates form for the user registration.
{!! Form::open(array('url' => 'register')) !!}
{!! Form::label('email', 'Email Address') !!}
{!! Form::text('email') !!}
{!! Form::label('username', 'Username') !!}
{!! Form::text('username') !!}
{!! Form::label('password', 'Password') !!}
{!! Form::password('password') !!}
{!! Form::submit('Sign Up') !!}
{!! Form::close() !!}
I am getting this error when I click on Sign Up button on register page.
in routes.php line 30
at HandleExceptions->fatalExceptionFromError(array('type' => '1', 'message' => 'Class 'User' not found', 'file' => 'C:\xampp\htdocs\urlshort\app\Http\routes.php', 'line' => '30')) in HandleExceptions.php line 116
at HandleExceptions->handleShutdown()
After going through few queries in Google, I realized I forgot to load the User class. So, I included link to file with User class in composer.json file
"autoload": {
"classmap": [
"database",
"app/User.php"
],
"psr-4": {
"App\\": "app/"
}
},
I ran the composer dump-autoload command. But I am still getting the same error. I am unable to figure out where my code went work.
try to use
$user = new \App\User;
instead
$user = new User;
I had the same issue, the answer above didn't help, but I used
use App\Models\Access\User\User; instead of use User; in my controller and it worked.
Type App\Models\User it worked for me

Laravel 4 Authentication: Reminders Controller - GET reset not found

I am using Laravel 4's built in password reminder feature in a new application. It seems that the code it's generating and what the docs are saying is either incomplete, inconsistent, or I'm missing a vital point.
So far, I have...
Created Reminder Table
Migrated it
Created Reminder Controller
Tested both get / post for password/remind, successfully.
Where I am stuck is with the reset methods of the controller. The reminder url successfully sends to my email and once I click it, I get a Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException error.
The url that the Password::remind static method sends to my email is http://localhost/application/public/password/reset/3e5e7a5c8562b28909b9948e848c5692dccb4f8a.
My GET / POST reset methods in the reminder controller -
public function getReset($token = null)
{
if (is_null($token)) App::abort(404);
return View::make('password.reset')->with('token', $token);
}
public function postReset()
{
$credentials = Input::only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function($user, $password)
{
$user->password = Hash::make($password);
$user->save();
});
switch ($response)
{
case Password::INVALID_PASSWORD:
case Password::INVALID_TOKEN:
case Password::INVALID_USER:
return Redirect::back()->with('error', Lang::get($response));
case Password::PASSWORD_RESET:
return Redirect::to('/');
}
}
My password/reset.blade.php file -
{{ Form::open(array('url' => 'password/reset')) }}
{{ Form::hidden('token', $token) }}
{{ Form::email('email', null, array('class'=>'', 'placeholder'=>'Email Address')) }}
{{ Form::password('password', array('class'=>'', 'placeholder'=>'Password')) }}
{{ Form::password('password_confirmation', array('class'=>'', 'placeholder'=>'Password Confirmation')) }}
{{ Form::submit('Reset Password', array('class'=>'')) }}
{{ Form::close() }}
Anyone have any ideas as to where I'm going wrong??
Your most likely missing some routes add these if they don't already exist.
Route::get('password/reset/{token}', 'RemindersController#getReset');
It is also likely that you will need the reset post route as well.
Route::post('password/reset/{token}', 'RemindersController#postReset');

Categories