Laravel 5.1 $this->validate(...) throws error - php

I'm trying to add validation to my resource controller using the laravel's validation (http://laravel.com/docs/5.1/validation) but I get this error:
ErrorException in ValidatesRequests.php line 30:
Argument 1 passed to App\Http\Controllers\Controller::validate() must be an
instance of Illuminate\Http\Request,
instance of Illuminate\Support\Facades\Request given,
called in
/Users/lextoc/Documents/Sites/partyrecycler/app/
Http/Controllers/MarkerController.php on line 30 and defined
This is the controller:
namespace App\Http\Controllers;
use Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Marker;
class MarkerController extends Controller
{
...
public function create()
{
return view('markers.create');
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'x' => 'required',
'y' => 'required',
]);
$marker=Request::all();
Marker::create($marker);
return redirect('markers');
}
...
}
And the view:
<h1>Create marker</h1>
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{!! Form::open(array('route' => 'markers.store')) !!}
{!! csrf_field() !!}
<div>
Name
<input type="text" name="name">
</div>
<div>
x
<input type="text" name="x">
</div>
<div>
y
<input type="text" name="y">
</div>
<div>
<button type="submit">Create</button>
</div>
{!! Form::close() !!}
I don't know why it's using the wrong Request class, and why are there two being used in the controller?

The error is due to your include headers:
Try
use Illuminate\Http\Request;
Instead of
use Request;
Example:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Marker;

Related

Laravel Trait Doesn't Excite

I've a trait function that updating a report, i've done its route and its namespace also im using it in the controller everything is right but when i submit it doesn't run and the page only refreshs
Trait Function
<?php
namespace App\Http\Controllers\Permit\Trait;
use App\Models\Log;
use App\Models\Permit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
trait HazardsInfo
{
public function HazardsInfo(Request $request, $id)
{
dd($request);
$permit = Permit::findOrFail($id);
$permit->Update([
'gaurd_names' => $request->gaurd_names,
]);
Log::create([
'permit_id' => $permit->id,
'created_by' => Auth::user()->id,
'status' => 'og-complete'
]);
return Redirect::to("/permit/{$id}/edit")->withSuccess('Hazards Has Been Updated');
}
}
Route
Route::post('/permit/{permit}/edit', [PermitController::class, 'HazardsInfo'])->name('permit.HazardsInfo');
blade form
<form action="{{ route('permit.HazardsInfo', $permit->id) }}">
#if (Session::has('success'))
<div class="alert alert-success w-25 ms-2 text-center">
{{ Session::get('success') }}
</div>
#endif
<input type="text" name="gaurd_names">
<button type="submit" class="btn btn-success btn-label right ms-auto nexttab nexttab" data-nexttab=""><i
class="ri-arrow-left-line label-icon align-middle fs-16 ms-2"></i>
Submit</button>
</form>

Laravel 6 one --> many relationship in resource controller

I currently have an application that can have a modifier with many options. An example use case is a modifier of Toppings with options of cheese, lettuce, salt, and pepper. A modifier can have 1 --> N options.
I want to have a form that displays the Modifier name and also allows the ability to edit/delete Option records at same time. I want to embed this in my current form for adding/editing modifiers.
Is there a simple way to do this so I can have just one Modifier resource controller that also manages Options?
web.php
Route::resource('modifiers', 'ModifierController')->middleware('auth');
Controller:
namespace App\Http\Controllers;
use App\Modifier;
use Illuminate\Http\Request;
class ModifierController extends Controller
{
public function create()
{
$data = ['action' => route('modifiers.store'),'method' => 'POST', 'modifier' => new Modifier()];
return view('modifiers.form',$data);
}
public function store(Request $request)
{
$modifier = new Modifier($request->all());
$this->do_validate($request);
$modifier->save();
return redirect(route('modifiers.index'));
}
}
views/modifiers/form.blade.php
#extends('layouts.layout-2')
#section('content')
<div class="container">
<div class="row justify-content-center">
#include ('layouts.errors')
<div class="col-md-12">
{!! Form::open(['url' => $action, 'method' => 'post', 'class' => 'form', 'id' => 'form'])!!}
#csrf
#method($method)
<div class="form-group">
<label for="name">{{ __('modifiers.name')}}</label>
<input type="text" class="form-control" id="name" name="name" value = "{{old('name',$modifier->name)}}">
</div>
<button id="btnSubmit" class="btn btn-primary">{{ __('common.submit') }}</button>
{!! Form::close() !!}
</div>
</div>
</div>
#endsection
Models:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Modifier extends Model
{
use SoftDeletes;
protected $guarded = ['id'];
public function options()
{
return $this->hasMany('App\Option');
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Option extends Model
{
use SoftDeletes;
protected $guarded = ['id'];
public function modifier()
{
return $this->belongsTo('App\Modifier');
}
}
I think you can use a select element:
<select name="options[]" id="options" class="form-control">
#foreach($options as $option)
<option value="{{ $option->id }}" {{ $modifier->options->contains('id', $option->id) ? 'selected' : '' }}>{{ $option->name }}</option>
#endforeach
</select>
Hope it helps.
Then, within some controller:
public function update(Request $request, $id)
{
$modifier = Modifier::find($id);
$modifier->options()->sync($request->input('options'));
// Do whatever more you want to do
}

Submitting a request in Laravel and sending mail

I am trying to submit a form and send an email based on data submitted through the form, but it doesn't seem to be working because I don't get back the success message.
Controller
public function contact(Request $request)
{
$request = request()->validate([
'name' => 'required',
'email' => 'required| email',
'message' => 'required | max:1000',
]);
Mail::to('support#mail.com')->send(new contact($request));
return redirect()->back()->with("success", "You email has successfully been sent");
}
Form
#if (session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
#endif
#if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
#endif
<form action="/contact" method="POST">
#csrf
<div class="col-md-12">
<input type="text" placeholder="Full Name" required name="name">
</div>
<div class="col-md-8">
<input type="text" placeholder="email" required name="email">
</div>
<div class="col-md-2">
<textarea name="message"></textarea>
</div>
<div class="col-md-12">
<button class="btn btn-black no-margin-bottom btn-small"
type="submit">Contact</button>
</div>
</form>
Route
`Route::post('/contact', 'HomeController#contact');`
If you're being redirected back to the form page without error messages or your sucess flash message then I am inclined to think the problem is in your template. Assuming you are using the laracasts/flash package your method should look like this
public function contact(Request $request)
{
$request = request()->validate([
'name' => 'required',
'email' => 'required| email',
'message' => 'required | max:1000'
]);
Mail::to('support#mail.com')->send(
new contact($request)
);
return redirect()->back()->with("success", "You email has successfully been sent");
}
redirect()->with() adds data to the session but it doesn't display a message unless you manually do so in the template like this
#if (session('sucess'))
<div class="alert alert-success">
{{ session('success') }}
</div>
#endif
Make sure you're displaying errors properly in your form, replace your session('error') block with the following:
#if($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
In your controller:
use App\Mail\Contact;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class HomeController extends Controller
{
// ...
public function contact(Request $request)
{
// Note I'm not overwriting the $request variable.
// This method returns an array of the validated data.
$request->validate([
'name' => 'required',
'email' => 'required|email',
'message' => 'required|max:1000'
]);
Mail::to('support#mail.com')->send(new Contact($request));
return back()->with('success', 'Your email has successfully been sent');
}
}
Your mail class should look something like this:
namespace App\Mail;
use Illuminate\Http\Request;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class Contact extends Mailable
{
use Queueable, SerializesModels;
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function build()
{
// The request instance must be passed to the view...
return $this->markdown('emails.contact', [
'request' => $this->request
]);
}
}
You can now use the Request object in your email markdown (emails.contact). For example:
**Name**<br>
{{ $request->input('name') }}
**Email**<br>
{{ $request->input('email') }}
**Message**<br>
{{ $request->input('message') }}

Laravel form validation doesn't seem to work

I'm making my first form in Laravel and the generation of the form is all working. It's just that the store function seems to blindly return the user to my contact page irrelevant of the result of the form validation.
So if the email address posted isn't an email but a random string I still get returned to the /contact page with the thank you message being sent to the view.
My controller looks like this:
namespace App\Http\Controllers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\ContactFormRequest;
class ContactController extends Controller {
public function create(){
return view('contact');
}
public function store(ContactFormRequest $request) {
return \Redirect::route('contact')
->with('message', 'Thanks for contacting us!');
}
}
And the form handler like this:
namespace App\Http\Requests;
use Illuminate\Http\Request;
class ContactFormRequest extends Request {
public function authorize() {
return true; // don't need to be registered to run form so true
}
public function rules() {
return [
'email' => 'required|email',
];
}
}
This is controlled by the following routes
if (config('app.tan_site_page_contact')===true){
Route::get('/contact', ['as' => 'contact', 'uses' => 'ContactController#create']);
Route::post('/contact', ['as' => 'contact_store', 'uses' => 'ContactController#store']);
});
And the form like this:
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#if(Session::has('message'))
<div class="alert alert-info">
{{Session::get('message')}}
</div>
#endif
{!! Form::open(array('route' => 'contact_store', 'id' => 'contactCallMeForm')) !!}
{!! Form::label('Your E-mail Address') !!}
{!! Form::text('email', null, array('required', 'class'=>'form-control', 'placeholder'=>'Your e-mail address')) !!}
{!! Form::submit('Contact Us!', array('class'=>'btn btn-primary')) !!}
{!! Form::close() !!}
The form html seems fine,with a token and valid url
<form method="POST" action="http://localhost/contact" accept-charset="UTF-8" id="contactCallMeForm" novalidate="">
<input name="_token" type="hidden" value="VNHchLZhfsXadVZXCZWHGdAuJ4zgmO6cDJIGhR59">
<label for="Your E-mail Address">Your E-mail Address</label>
<input required="required" class="form-control" placeholder="Your e-mail address" name="email" type="text">
<input class="btn btn-primary" type="submit" value="Contact Us!">
</form>
The problem here is your ContactFormRequest class.
You extends it from invalid Request class. You extend it from \Illuminate\Http\Request class but you should extend it from \Illuminate\Foundation\Http\FormRequest (or \App\Http\Requests\Request class)

Laravel : BadMethodCallException Method [store] does not exist

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.

Categories