My form:
<form action="{{route('settings.update')}}" method="POST">
#csrf
<div class="col-sm-3">
<div class="form-group">
<label for="avatar">Upload a new one:</label>
<input type="file" id="pic" name="pic"/>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Upload avatar</button>
</div>
</form>
My Controller:
public function update_settings($request)
{
$this->validate($request, [
'pic' => 'required|image'
]);
$path = $request->image->store('/img/');
Auth::user()->image = $path;
return view('pages.settings');
}
The error:
Too few arguments to function App\Http\Controllers\PagesController::update_settings(), 0 passed and exactly 1 expected
I am passing only the image file in the $request, but for some reason the controller doesn't see it, what am I doing incorrectly?
To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller constructor or method. The current request instance will automatically be injected by the service container:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class UserController extends Controller
{
/**
* Store a new user.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$name = $request->input('name');
//
}
}
Look well that in the method I am injecting the dependence of Illuminate\Http\Request
You need to add enctype='multipart/form-data' to your opening form tag
<form action="{{route('settings.update')}}" method="POST" enctype="multipart/form-data">
Related
How to suppress validation errors with a back button in Laravel ??
Details: I have form with two buttons and I made validation how to skip validation when click on (back-button)?
the code in the view page:
<form method="POST" action="{{route("movies.store")}}" class="mt-5 w-50 m-auto">
#csrf
<div class="mb-3">
<label class="form-label">Movie Name</label>
<input type="text" name="movie_name" class="form-control">
#error('movie_name')
<span class="error">{{$message}}</span>
#enderror
</div>
<div class="mb-3">
<label class="form-label">Movie Descrption</label>
<input type="text" name="movie_description" class="form-control">
#error('movie_description')
<span class="error">{{$message}}</span>
#enderror
</div>
<div class="mb-3">
<label class="form-label">Movie Gener</label>
<input type="text" name="movie_gener" class="form-control">
#error('movie_gener')
<span class="error">{{$message}}</span>
#enderror
</div>
<button type="submit" name="action" value="back" class="btn btn-warning me-3">Back</button>
<button type="submit" name="action" value="add" class="btn btn-primary">Add</button>
</form>
the code in the controller file:
public function store(MoviesFormRequest $request)
{
switch ($request->input('action')) {
case 'back':
return redirect()->route("movies.index");
case 'add':
$data = $request->validated();
Movie::create($data);
return redirect()->route("movies.index");
}
}
If you just want to solve the problem by implementing back button instead of using button tag use anchor tag as follows
Back
And remove the switch statement and just do as follows:
public function store(MoviesFormRequest $request)
{
Movie::create($request->all());
return redirect()->route("movies.index");
}
Inside your MoviesFormRequest class do all the validations like :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MoviesFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'movie_name' => 'required',
'movie_description' => 'required',
'movie_gener' => 'required',
];
}
}
This will work for you just customize the anchor tag to look good. Hope this solve your problem.
The validation happens in your custom request (MoviesFormRequest) before the code in the controller method is executed.
So in order to skip validation given a specific request input, you have to make the it part of the switch block
use Illuminate\Http\Request;
// use the base request here (no validation at this point)
public function store(Request $request)
{
switch ($request->input('action')) {
case 'back':
return redirect()->route("movies.index");
case 'add':
// in our case block we can validate
$this->validate($request, [
'title' => ['required'],
//... your rules here
]);
$data = $this->validated();
Movie::create($data);
return redirect()->route("movies.index");
}
}
I am very new to Laravel, and our system uses multiple forms within a single page to insert the single bitcoin wallet into each input field, but as it stands the user is able to use it on all inputs and this is wrong as could i make only one valid? such as "username" "email" etc ..
html:
<form method="POST" action="/wallet3-edit/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('bitzpayer_id3') ? ' has-error' : '' }}">
<label for="bitzpayer_id3" class="control-label"><b>Wallet:</b></label>
<input type="text" name="bitzpayer_id3" placeholder="Please enter your Wallet here" class="form-control" value="{{ $user->bitzpayer_id3 }}"/>
<?php if ($errors->has('bitzpayer_id3')) :?>
<span class="help-block">
<strong>{{$errors->first('bitzpayer_id3')}}</strong>
</span>
<?php endif;?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-warning text-white"> Submit </button>
</div>
</form>
Controller:
<?php
namespace App\Http\Controllers;
use Auth;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class Wallet3Controller 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('/wallet3-edit', compact('user'));
}
public function update(Request $request) {
/**
* fetching the user model
*/
$user = Auth::user();
/**
* Validate request/input
**/
$this->validate($request, [
'bitzpayer_id3' => 'max:255|unique:users,bitzpayer_id3,'.$user->id,
]);
/**
* storing the input fields name & email in variable $input
* type array
**/
$input = $request->only('bitzpayer_id3');
/**
* 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();
}
}
Routes:
Route::get('wallet3-edit', 'Wallet3Controller#index');
Route::patch('wallet3-edit/{id}', 'Wallet3Controller#update');
if you want to validate not duplication in a single page:
because The page dosent send any request to server until the form completes,
you can check this within javascript/jquery like this:
$(".inputs").change(function(){
if($("#input1").val()==$("#input2").val()){
$("#input1").addClass("error");
}
});
but if your input are seprated in different pages and save in database you can validate with them with this kind of rules in Laravel controller or Laravel Request Class:
$validationRules = ["wallet" => "required|unique:wallets_table,btc"];
where "wallet" is the name of your input field. "wallets_table" is your database table and "btc" is table column.
but if you are not willing to save the wallet public keys in Database and the requests are from a single user, you can save the "Address"es in a Session Array and check them out when a user submit a request. but this solution works User Scope .
please give me more details if I misunderstood.
I'm learning Laravel and I got stuck trying to get data from a form.
I already am able to get data back with GET, but with POST I've been having a ton of trouble. Here's what I'm working with:
Form:
<form id="forms" method="POST" action="sugestoes" novalidate>
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-12">
<label for="obs">Observações:</label>
<textarea type="text" class="form-control" name="obs" placeholder="Observações" required></textarea>
</div>
</div>
<hr>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
#php
if (isset($_POST["obs"])) {
echo "IN";
}
#endphp
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$name = $request->input('obs');
return redirect('sugestoes');
//
}
}
Route:
Route::post('sugestoes', 'PostController#store');
The intended behaviour that I'm trying to reach is for the post to be submitted, and then returning to the same page with an empty form. Later on I'll be sending the input data into a database, but for now I just want to get the post to work.
I guess I'm missing something really basic, but I've been following guides and looking online, I've done some progress but I'm really stuck here.
(some more info, this is Laravel 5.4, and I'm using XAMPP)
First, you need to call the model, use App/Your_model_name; then you have to save the data.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Suggest; //Suggest model, let's hope you have suggest table
class PostController extends Controller
{
public function store(Request $request)
{
$suggest = new Suggest; //model
$suggest->name = $request->obs; //name is DB name, obs is request name
$suggest->save(); //save the post to DB
return redirect()->back()->with('success', 'Saved successfully'); //return back with message
}
}
Then if you want to flash the message on the HTML page
#if(session('success'))
<div class="alert alert-warning alert-dismissible" id="error-alert">
<strong style="color: white;">{{session('success')}}</strong>
</div>
#endif
<form id="forms" method="POST" action="{{ route('sugestoes') }}" novalidate>
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-12">
<label for="obs">Observações:</label>
<textarea type="text" class="form-control" name="obs" placeholder="Observações" required></textarea>
</div>
</div>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
Remove the #php tag below the form, then in router.php
Route::post('/sugestoes', 'PostController#store')->name('sugestoes');
Then in Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$name = $request->input('obs');
return redirect('/sugestoes'); // you should have GET in Route.php
//
}
}
Add the following code in your action attribute on the form. It will capture the post URL. When you submit the form it will send the form data to the URL end-point.
action="{{ url('sugestoes')}}"
Then die and dump in your controller store function
public function store(Request $request)
{
dd($request->all());
}
PS: I am new to Laravel. And following this tutorial to create sample project
Everything is working fine.
But I am not able to figure out how data is inserted into the database.
here is the form code
<form method="post" action="{{url('products')}}">
{{csrf_field()}}
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" >
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="price">Price:</label>
<input type="text" class="form-control" name="price">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<button type="submit" class="btn btn-success" style="margin-left:38px">Add Product</button>
</div>
</div>
</form>
Here at the onsubmit action it is calling "{{url('products')}}" .
What is the mean of this? Can anybody help?
If you need any other code let me know.
web.php
<?php
Route::resource('products','ProductController');
Route::get('/', function () {
return view('welcome');
});
ProductController.php
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$products = Product::all()->toArray();
return view('products.index', compact('products'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$product = $this->validate(request(), [
'name' => 'required',
'price' => 'required|numeric'
]);
Product::create($product);
return back()->with('success', 'Product has been added');;
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
}
{{url('/products')}} means url() function will return base url and whatever added inside that method will append to base ur;
for example my website url is https://stackoverflow.com/ then above method will return
https://stackoverflow.com/products
in your route you have to define
Route::resource('products','ProductController');
Laravel route will point to your controller and method and in method you have a logic to insert into database
for better understanding
url()
The url function generates a fully qualified URL to the given path:
Ref:
https://laravel.com/docs/5.5/helpers#method-url
Also to learn more about route resource you can refer
https://laravel.com/docs/5.5/controllers#resource-controllers
What you are asking for is Generating Urls This means it uses your app base url with the other urls you have in the string argument. Therefore, url('products') is the same thing as http://yourwebsite.com/products as the action on your form i.e where the form will be submitted to.
The other counterpart is Urls for named routes I will add a caption here in case the document link breaks at any point:
You see. This means that in your one of your routes has that name which you use to generate a url.
Since some of these helper functions are new to you (supposing you are learning by following a tutorial), my recommendation is to open Laravel's documentation and see how things are by yourself.
This seems to be a Route::ressource called 'product' and redirecting to ProductController.
I just downloaded and started a new project with the latest Laravel 4.2. When trying to submit a form I get the following error : BadMethodCallException Method [store] does not exist
Here are my files : controller - admin/AdminController
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index() {
if (Input::has('Login')) {
$rules = array(
'email' => 'required',
'password' => 'required|min:3',
'email' => 'required|email|unique:users'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('admin\AdminController')->withErrors($validator);
} else {
// redirect
Session::flash('message', 'Successfully created user!');
return Redirect::to('admin\AdminController');
}
}
$data['title'] = ADMIN;
return View::make('admin.index', $data);
}
}
View page - admin/index.blade.php
<div class="container">
{{ Form::open(array('url' => ADMIN,'id' => 'login')) }}
<div id="icdev-login-wrap">
<div class="raw align-center logoadmin">{{ HTML::image('images/logo.png') }}</div>
<div id="icdev-login">
<h3>Welcome, Please Login</h3>
<div class="mar2_bttm input-group-lg"><input type="text" class="form-control loginput" placeholder="Email" name="email"></div>
<div class="mar2_bttm input-group-lg"><input type="password" class="form-control loginput" placeholder="Password" name="password"></div>
<div ><input type="submit" class="btn btn-default btn-lg btn-block cus-log-in" value="Login" /></div>
<div class="row align-center forgotfix">
<input type="hidden" name="Login" value="1">
</div>
</div>
<div>
</div>
</div>
{{ Form::close() }}
</div>
The error message tells you what the problem is: the method called store() doesn’t exist. Add it to your controller:
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index()
{
// leave code as is
}
public function store()
{
// this is your NEW store method
// put logic here to save the record to the database
}
}
A couple of points:
Use camel-casing for name spaces (i.e. namespace admin should be namespace Admin)
Read the Laravel documentation on resource controllers: http://laravel.com/docs/controllers#resource-controllers
You can also automatically generate resource controllers with an Artisan command. Run $ php artisan make:controller ItemController, replacing ItemController with the name of the controller, i.e. ArticleController or UserController.