I want to save a form input through Laravel 5.0
The page reloaded and back to the index page..But data does not save to mysql through routes.
Here is controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Requests\CreateTaskRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Task;
use Input;
class TodoController extends Controller {
public function index()
{
$data=Task::all();
// $options=Option::whereNotIn('id',$activeCourse)->lists('option_name','id');
return view('home')->with('data',$data);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//return view('home');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(CreateTaskRequest $request)
{
// dd($request->all());
/*$data=[
'name'=>Input::get('name'),
'status'=>Input::get('status'),
'description'=>Input::get('description'),
'task_img'=>Input::get('task_img'),
'dob'=>Input::get('dob')
];*/
$response=new Task();
$response->name=$request->input('name');
$response->status=$request->input('status');
$response->description=$request->input('description');
$response->description=$request->input('task_img');
$response->description=$request->input('dob');
$response->save();
// dd('working?');
//$response=Task::create(['name'=>$request->input('name'),'status'=>$request->input('status'),'description'=>$request->input('description')]);
if($response){
return redirect()->back()->with('success','Task Created Successfully');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$data=Task::find($id);
return view('todo_edit')->with('data',$data);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update(CreateTaskRequest $request, $id)
{
$data=[
'name'=>Input::get('name'),
'status'=>Input::get('status')
];
$response=Task::find($id)->update($data);
if($response){
return redirect('/');
}
}
public function destroy($id)
{
$response=Task::find($id)->delete();
if($response){
return redirect('/')->with('success','Task Deleted Successfully');;
}
}
}
Here is my View Page:
#extends('app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12 ">
<div class="col-lg-12">
<div class="col-lg-6">
{!! Form::open(array('route' =>'' ,'method'=>'post')) !!}
{!! Form::hidden('_token',csrf_token()) !!}
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Enter a task name"></br>
</br>
<lavel> <input name="status" type="radio" value="Complete"> Complete</lavel></br>
<label> <input checked="checked" name="status" type="radio" value="Incomplete"> Incomplete</label></br>
<textarea class="form-control" name="description" rows="3"></textarea></br>
<label>File input</label>
<input type="file" name="task_img"></br>
<input type="date" class="form-control datepicker" name="dob" style="width:95%">
{!! Form::submit('Save', array('class' => 'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
</div>
<h3> Todo Application </h3>
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>Task Name</td>
<td>Status</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
#foreach($data as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->name }}</td>
<td>{{$row->status}}</td>
<td>
Edit
<form action="{{route('postDeleteRoute',$row->id)}}" method="POST" style="display:inline;"
onsubmit="if(confirm('Are you sure?')) {return true} else {return false};">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#section('page-script')
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
#stop
#endsection
And here is the 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('/',
'TodoController#index');
Route::post('/', 'TodoController#store');
Route::get('/{id}/edit',['as'=>'getEditRoute','uses'=>'TodoController#edit']);
Route::post('/{id}/edit',['as'=>'postUpdateRoute','uses'=>'TodoController#update']);
Route::post('/{id}/delete',['as'=>'postDeleteRoute','uses'=>'TodoController#destroy']);
//Route::get('home', 'HomeController#index');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
To save data from a form you can do as below :
In you form replace
{!! Form::open(array('route' =>'' ,'method'=>'post')) !!}
with
{!! Form::open(array('route' =>'form.store' ,'method'=>'post')) !!}
In you route replace
Route::post('/', 'TodoController#store');
with
Route::post('/store',array('as'=>'form.store',uses=>'TodoController#store');
And in your controller replace
public function create()
{
//return view('home');
}
with
public function store(Request $request) //Http request object
{
Task::create($this->request->all());//assumes that you want to create task.
return \Redirect::route('/')->with('message', 'Task saved sucessfully!!!');
}
If you want to explore more then please read the documentation from the below links :
Laravel Routes
Laravel Request
Laravel Controllers
Hope it helps. Happy Coding :) .
Related
I am trying to add a delete function to my application where there will be a list of inventory presented and you can delete an item if you wish. However, I don't know where I am going wrong since it does say delete is supported.
Here my my router:
Route::delete('/inventories/{inventory}', [\App\Http\Controllers\InventoryController::class, 'destroy'])->name('inventories.destroy');
Here is my controller:
<?php
namespace App\Http\Controllers;
use App\Models\Inventory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Redirector;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Log;
class InventoryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Contracts\View\View
*/
public function index(): \Illuminate\Contracts\View\View
{
$inventories = Inventory::all();
return view('pages.inventories',[
"inventories" => $inventories
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Contracts\View\View
*/
public function create(): \Illuminate\Contracts\View\View
{
return view('pages.inventories.create');
}
/**
* Store a newly created resource in storage.
*
* #param Request $request
* #return Redirector
*/
public function store(Request $request): Redirector
{
$validated = $request->validate([
'title'=> 'required|string',
'description'=> 'required|string|max:300',
'price' => 'required|integer|min:0',
'in_stock' => 'required|integer',
'on_sale' => 'required|boolean'
]);
$inventory = new Inventory();
$inventory->fill($validated)->save();
return redirect('/inventories');
}
/**
* Show the form for editing the specified resource.
*
* #return \Illuminate\Contracts\View\View
*/
public function edit(Inventory $inventory): \Illuminate\Contracts\View\View
{
return view('pages.inventories.edit',[
"inventory" => $inventory
]);
}
/**
* Update the specified resource in storage.
*
* #param Request $request
* #param Inventory $inventory
* #return RedirectResponse
* #throws ValidationException
*/
public function update(Request $request, Inventory $inventory): RedirectResponse
{
$validated = $this->validate($request, [
'title'=> 'required|string',
'description'=> 'required|string|max:300',
'price' => 'required|integer|min:0',
'in_stock' => 'required|integer',
'on_sale' => 'required|boolean'
]);
$inventory->fill($validated)->save();
return redirect()->route('inventories.index')->with('status',
'Item has been updated!' . $inventory->title);
}
/**
* Remove the specified resource from storage.
*
* #param Inventory $inventory
* #return RedirectResponse
*/
public function destroy(Inventory $inventory): RedirectResponse
{
$inventory = Inventory::find($inventory);
$inventory->delete();
return redirect()->route('inventories.index')->with('status',
'Item has been deleted!' . $inventory->title);
}
}
Here is my delete.blade file:
#extends('layouts.app')
#section('title', 'Delete Inventory')
#section('content')
<h1><strong>Delete inventory</strong></h1>
<x-inventory-form :inventory=$inventory />
{{ $inventory }}
<form method="POST" action="{{url('/inventories',[$inventory->id])}}"></form>
<input type="hidden" name="_method" value="delete">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#endsection
Here is my inventories.blade file:
#extends('layouts.app')
#section('title', 'My Inventory')
#section('content')
<h1>Inventory Table</h1>
<p>This is the inventory table made using PHP Laravel that is randomly generated.</p>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
<th>Price</th>
<th>In stock</th>
<th>On sale</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach($inventories as $inventory)
<tr>
<td>{{$inventory->id}}</td>
<td>{{$inventory->title}}</td>
<td>{{$inventory->description}}</td>
<td> £{{ number_format($inventory->price, 2) }}</td>
<td>{{$inventory->in_stock}}</td>
<td>{{ $inventory->on_sale ? 'Yes' : 'No' }}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
#endforeach
</tbody>
</table>
#endsection
Here is my inventory form component:
<?php
namespace App\View\Components;
use App\Models\Inventory;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class InventoryForm extends Component
{
/**
* #var Inventory|null
*/
public $inventory;
/**
* #param Inventory|null $inventory
*/
public function __construct(Inventory $inventory = null)
{
$this->inventory = $inventory;
}
/**
* #return string
*/
public function action(): string
{
if ($this->inventory) {
return route('inventories.update', ['inventory' => $this->inventory]);
}
return route('inventories.store');
}
/**
* Get the view / contents that represent the component.
*
*
* #return View|\Closure|string
*/
public function render()
{
return view('components.inventory-form');
}
And here is my inventory form component blade file:
<form action="{{ $action }}" method="post">
#if($inventory)
#method('patch')
#endif
#csrf
<label for="title">Enter an item name:</label>
<input type="text" name="title" value="{{ $inventory?->title }}" required /><br><br>
<label for="description">Enter the item's description:</label>
<textarea name="description" required>{{ $inventory?->description }}</textarea><br><br>
<label for="price">Enter the item's price:</label>
<input type="number" name="price" value="{{ $inventory?->price }}" required/><br><br>
<label for="in_stock">Enter a number of items in stock:</label>
<input type="number" name="in_stock" value="{{ $inventory?->in_stock }}" required/><br><br>
<label for="on_sale">Select yes/no if item is on sale:</label>
<select name="on_sale" value="{{ (int) $inventory?->on_sale }}" required>
<option value="" disabled {{ $inventory ? '' : 'selected' }}>--Please choose an option--</option>
<option value="1" {{ $inventory?->on_sale ? 'selected' : '' }}>Yes</option>
<option value="0" {{ (false === $inventory?->on_sale) ? 'selected' : '' }}>No</option>
</select><br><br>
<button type="submit">Submit</button>
</form>
Any help would be appreciated!!
Your name is wrong __method it should _method only.
You may use blade directive instead.
#section('content')
<h1><strong>Delete inventory</strong></h1>
{{ $inventory }}
#method('DELETE')
#csrf
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#endsection
Use this for delete method.
#method('DELETE')
#csrf
OR
<input type="hidden" name="_method" value="delete" />
<input type="hidden" name="_token" value="{{ csrf_token() }}">
If you are using laravel 5.*
{!! method_field('delete') !!}
{!! csrf_field() !!}
To change the method used in a form, the attribute to use is _method not __method. Same thing for _token
<input type="hidden" name="_method" value="delete">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
You are missing the
<form method="POST" action="{{url('/inventories',[$inventory->id])}}"></form>
so it is picking the current url as a get method. so adding the should fix it.
#extends('layouts.app')
#section('title', 'Delete Inventory')
#section('content')
<h1><strong>Delete inventory</strong></h1>
{{ $inventory }}
<form method="POST" action="{{url('/inventories',[$inventory->id])}}">
#method('delete')
#csrf
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</form>
#endsection
In my routes file I needed to write a get request with delete and a delete request with destroy. My new edited code is:
Route::get('/inventories/{inventory}/delete', [\App\Http\Controllers\InventoryController::class, 'delete'])->name('inventories.delete');
Route::delete('/inventories/{inventory}', [\App\Http\Controllers\InventoryController::class, 'destroy'])->name('inventories.destroy');
And my controller:
/**
* #param Inventory $inventory
* #return \Illuminate\Contracts\View\View
*/
public function delete(Inventory $inventory)
{
return view('pages.inventories.delete', ["inventory" => $inventory]);
}
/**
* Remove the specified resource from storage.
*
* #param Inventory $inventory
* #return RedirectResponse
*/
public function destroy(Inventory $inventory): RedirectResponse
{
$inventory->delete();
return redirect()->route('inventories.index')->with('status',
'Item has been deleted!');
}
Whenever a user goes to mywebsite.com/profile I want a form to pre populate the values they've entered during the signup/registration flow. I was able to do that with my form here
<h1><b>Your Profile</b></h1>
<form method="POST" action="/profile/update">
<div class="form-group hidden">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="PATCH">
</div>
<div class="form-group {{ $errors->has('name') ? ' has-error' : '' }}">
<label for="email" class="control-label"><b>Name:</b></label>
<input type="text" name="name" placeholder="Please enter your email here" class="form-control" value="{{ $user->name }}"/>
<?php if ($errors->has('name')) :?>
<span class="help-block">
<strong>{{$errors->first('name')}}</strong>
</span>
<?php endif;?>
</div>
<div class="form-group {{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="control-label"><b>Email:</b></label>
<input type="text" name="email" placeholder="Please enter your email here" class="form-control" value="{{ $user->email }}"/>
<?php if ($errors->has('email')) :?>
<span class="help-block">
<strong>{{$errors->first('email')}}</strong>
</span>
<?php endif;?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default"> Submit </button>
</div>
</form>
But now im running into the issue if the user just hits submit button without changing any fields, laravel's built in validations checks and gives me an error message of The name has already been taken. which is true. so im not sure how to handle this issue, but here is my controller below
<?php
namespace App\Http\Controllers;
use Auth;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ProfileController extends Controller
{
/**
* Update user profile & make backend push to DB
*
**/
public function index() {
/**
* fetching the user model
**/
$user = Auth::user();
//var_dump($user);
/**
* Passing the user data to profile view
*/
return view('profile', compact('user'));
}
public function update(Request $request) {
/**
* Validate request/input
**/
$this->validate($request, [
'name' => 'required|max:255|unique:users',
'email' => 'required|email|max:255|unique:users',
]);
/**
* storing the input fields name & email in variable $input
* type array
**/
$input = $request->only('name','email');
/**
* fetching the user model
*/
$user = Auth::user();
/**
* Accessing the update method and passing in $input array of data
**/
$user->update($input);
/**
* after everything is done return them pack to /profile/ uri
**/
return back();
}
}
and here is my routes file.
// only authenticated users
Route::group( ['middleware' => 'auth'], function() {
Route::get('/home', 'HomeController#index');
// practicing using forms for sending data to the DB & populating form fields with DB data
Route::get('profile', 'ProfileController#index');
Route::patch('profile/{id}', 'ProfileController#update');
});
Issue is due to unique validation rule. You can exclude the current user id by specifying unique validation rule. your code will be like this
public function update(Request $request) {
/**
* fetching the user model
*/
$user = Auth::user();
/**
* Validate request/input
**/
$this->validate($request, [
'name' => 'required|max:255|unique:users,name,'.$user->id,
'email' => 'required|email|max:255|unique:users,email,'.$user->id,
]);
/**
* storing the input fields name & email in variable $input
* type array
**/
$input = $request->only('name','email');
/**
* Accessing the update method and passing in $input array of data
**/
$user->update($input);
/**
* after everything is done return them pack to /profile/ uri
**/
return back();
}
here is laravel documentation link for this https://laravel.com/docs/5.1/validation#rule-unique
in laravel 5 i try the PasswordController and the ResetsPasswords but always i have a route probleme
Route.php
Route::controllers(['uses' => 'Auth/PasswordController']);
Route::get('home/ResetsPasswords',array('as'=>'getEmail' ,'uses' => 'home/ResetsPasswords#getEmail') );
Route::post('home/ResetsPasswords',array('as'=>'postEmail' ,'uses' => 'home/ResetsPasswords#postEmail' ));
Route::get('home/ResetsPasswords/{token}',array('as' => 'getReset','uses' => 'home/ResetsPasswords#getReset' ) );
Route::post('home/ResetsPasswords/{token}', array( 'as' => 'postReset','uses' => 'home/ResetsPasswords#postReset'));
Route::get('home/ResetsPasswords',array('as'=>'getEmailSubject' ,'uses' => 'home/ResetsPasswords#getEmailSubject') );
Route::get('home/ResetsPasswords',array('as'=>'redirectPath' ,'uses' => 'home/ResetsPasswords#redirectPath') );
The PasswordController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
use ResetsPasswords;
public function __construct()
{
$this->middleware('guest');
}
}
the ResetsPasswords.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
ResetsPasswords.php
<?php
//namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
trait ResetsPasswords
{
/**
* Display the form to request a password reset link.
*
* #return \Illuminate\Http\Response
*/
public function getEmail()
{
return view('auth.password');
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return redirect()->back()->with('status', trans($response));
case Password::INVALID_USER:
return redirect()->back()->withErrors(['email' => trans($response)]);
}
}
/**
* Get the e-mail subject line to be used for the reset link email.
*
* #return string
*/
protected function getEmailSubject()
{
return isset($this->subject) ? $this->subject : 'Your Password Reset Link';
}
/**
* Display the password reset view for the given token.
*
* #param string $token
* #return \Illuminate\Http\Response
*/
public function getReset($token = null)
{
if (is_null($token)) {
throw new NotFoundHttpException;
}
return view('auth.reset')->with('token', $token);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postReset(Request $request)
{
$this->validate($request, [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath());
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $password
* #return void
*/
protected function resetPassword($user, $password)
{
$user->password = bcrypt($password);
$user->save();
Auth::login($user);
}
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
if (property_exists($this, 'redirectPath')) {
return $this->redirectPath;
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
}
and for the views
first the emails/password.blade.php
<?php
Click here to reset your password: {{ url('password/reset/'.$token) }}
?>
the auth/password.blade.php
#extends('layouts.master')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="/password/email">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Send Password Reset Link
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
the reset.blade.php
#extends('layouts.master')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="/password/reset">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="token" value="{{ $token }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Reset Password
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
and finally my login view
Mot de passe oublié?
so the error is
Call to undefined method Laravel\Routing\Route::controllers()
can you please help me :/ i try to change the route many time but always the same problem !!!!!!!
thank you
Implicit controllers are deprecated on Laravel 5. You need to remove this:
Route::controllers(['uses' => 'Auth/PasswordController']);
More info: https://laravel.com/docs/5.2/routing#route-model-binding
This is for laravel 5
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
This is for laravel 5.2
Route::group(['middleware' => ['web']], function () {
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
});
I think you are using in routes.php
use Illuminate\Routing\Route;
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
if you use this then the error comes.
Call to undefined method Illuminate\Routing\Route::controllers()
to avoid this error use this
use Illuminate\Support\Facades\Route;
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Note:Dont need to import anything route
leave it as
The below one also works
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
I am new to Laravel and other PHP frameworks.
Try simple form and validating, like examples in https://laravel.com/docs/5.1/validation
routes.php
Route::get('/post/', 'PostController#create');
Route::post('/post/store', 'PostController#store');
create.blade.php
<html>
<head>
<title>Post form</title>
</head>
<body>
<h1>Create Post</h1>
<form action="/post/store" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name='title'>
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
</body>
PostController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use View;
use Validator;
class PostController extends Controller
{
/**
* Show the form to create a new blog post.
*
* #return Response
*/
public function create()
{
return view('post.create');
}
/**
* Store a new blog post.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
// Validate and store the blog post...
$validator = Validator::make($request->all(), [
'title' => 'required|min:5'
]);
if ($validator->fails()) {
dd($validator->errors);
//return redirect('post')
//->withErrors($validator)
//->withInput();
}
}
}
When I post not valid data:
ErrorException in PostController.php line 37: Undefined property: Illuminate\Validation\Validator::$errors
Validator object nor have errors.
If enabled in controller
return redirect('post')->withErrors($validator)
->withInput();
and enabled in form
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Have error
ErrorException in c5df03aa6445eda15ddf9d4b3d08e7882dfe13e1.php line 1: Undefined variable: errors (View: /www/alexey-laravel-1/resources/views/post/create.blade.php)
This error in default get request to form and after redirect from validator.
For $errors to be available in the view, the related routes must be within the web middleware:
Route::group(['middleware' => ['web']], function () {
Route::get('/post/', 'PostController#create');
Route::post('/post/store', 'PostController#store');
});
I'm trying to post some stuff into the database using laravel, but It seems not to work...
This is what I get:
The HTML:
{{ Form::open(array('role' => 'form')) }}
<div class="form-body">
<div class="form-group">
<label>Titel</label>
<input type="text" class="form-control" name="title" placeholder="Titel komt hier">
</div>
<div class="form-group">
<label>Textarea</label>
<textarea class="form-control" name="message" rows="5" placeholder="Uw bericht..."></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile1">Nieuws afbeelding</label>
<input type="file" name="img">
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn green" value="Oplsaan" />
</div>
{{ Form::close() }}
#if ($errors->any())
<ul>
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</ul>
#endif
That displays all well....
Exept when I try to 'post' the news, because that is what I try to do, it just refreses the page. The URL to that page is mydomain.com/admin/news/write
My router looks like this:
Route::resource('admin/news/write', 'AdminController#create');
First it was authenticated in a group:
Route::group(array('before' => 'auth'), function()
{
Route::resource('admin', 'AdminController');
Route::resource('admin/news/write', 'AdminController#create');
});
This all works, but when I change the Route::resource('admin/news/write', 'AdminController#create'); to Route::post('admin/news/write', 'AdminController#create'); I get an error, that I can't see...
Good, now my controller:
public function store()
{
$rules = array(
'title' => 'required',
'message' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes())
{
if (Input::only('title', 'message'))
{
return Redirect::to('admin/news/write')->with('message', 'Het nieuws werd gemaakt!');
}
}
else
{
return Redirect::to('admin/news/write')->with('message', "Er ging iets mis: ")->withErrors($validator);
}
}
The problem is, I don't know how I can store an image to
/public/pictures/news
And then store the full file name into the database, if someone could help me out... I need a response quick, beacause I have a deadline... :{
Kindest regards
First you need to tell your form using the laravel helper that this is going to be uploading a file...
Form::open(['method'=>'POST', 'role' => 'form', 'files' => true])
In your controller you want to get the file from the input
$imgFile = Input::file('img');
Now to move the file from the temporary location it's been uploaded, to a more permanent location call the following (where $filename is what you want to call the uploaded file)...
$dir = '../storage/app/upload/';
$imgFile->move($dir.$filename);
The path for the root of the app from here is ../ (one up from public) so..
../storage/app/upload/ would be a great location to use for uploaded files.
You can then just write:
$dir.$filename;
back to the database - job done :)
Edit :: -- Your Controller --
Your controller for parsing this is based on resources...
So your route will be:
Route::group(array('before' => 'auth'), function()
{
Route::resource('admin', 'AdminController');
}
Your controller itself will have a structure such as (remembering this: http://laravel.com/docs/4.2/controllers#restful-resource-controllers):
class AdminController extends BaseController {
public function index(){...}
public function create(){...}
public function
//The store() method is an action handled by the resource controller
//Here we're using it to handle the post action from the current URL
public function store()
{
$imgFile = Input::file('img');
//processing code here....
}
public function show(){...}
public function edit(){...}
public function update(){...}
public function destroy(){...}
}
I fixed the issue.
My controller:
<?php
class AdminNewsController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return View::make('admin.news.create');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return View::make('admin.news.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'title' => 'required',
'message' => 'required',
'publish' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
//process the storage
if ($validator->fails())
{
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/news/create')->withErrors($validator);
}else{
//store
$news = new News;
$news->title = Input::get('title');
$news->message = Input::get('message');
$news->img_url = Input::file('img')->getClientOriginalName();
$news->posted_by = Auth::user()->username;
$news->published_at = time();
$news->published = Input::get('publish');
$news->save();
//save the image
$destinationPath = 'public/pictures/news';
if (Input::hasFile('img'))
{
$file = Input::file('img');
$file->move('public/pictures/news', $file->getClientOriginalName());
}
//redirect
Session::flash('success', 'Nieuws succesvol aangemaakt!');
return Redirect::to('admin/news/create');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
My create.blade.php
<div class="portlet-body form">
{{ Form::open(['method'=>'POST', 'role' => 'form', 'files' => true]) }}
<div class="form-body">
<div class="form-group">
<label>Titel</label>
<input type="text" class="form-control" name="title" placeholder="Titel komt hier">
</div>
<div class="form-group">
<label>Textarea</label>
<textarea class="form-control" name="message" rows="5" placeholder="Uw bericht..."></textarea>
</div>
<div class="form-group">
<label>Nieuws afbeelding</label>
{{ Form::file('img') }}
</div>
<div class="form-group">
<label>Bericht publiceren?</label>
<div class="radio-list">
<label class="radio-inline">
<span>
{{ Form::radio('publish', '1') }}
</span>
<b style="color:green">Publiceren</b>
</label>
<label class="radio-inline">
<span>
{{ Form::radio('publish', '0', true) }}
</span>
<b style="color:red">Niet publiceren</b>
</label>
</div>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn green" value="Oplsaan" />
</div>
{{ Form::close() }}
</div>
Then It all work!
Thanks to Matt Barber for the help!