Method App\Http\Controllers\todocontroller::validate does not exist error in laravel - laravel

I am using Laravel 5.7 and while validating my form fields I am getting this error:
"Method App\Http\Controllers\todocontroller::validate does not exist error."
Here is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\todo;
class todocontroller extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$todos= todo::all();
return view('todo.home',compact('todos'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('todo.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$todo = new todo;
$this->validate($request,[
'body'=>'required',
'title'=>'required|unique:todos',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect('/todo');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$todo=todo::find($id);
return view('todo.show',compact('todo'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$todo=todo::find($id);
return view('todo.edit',compact('todo'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$todo = todo::find($id);
$this->validate($request,[
'body'=>'required',
'title'=>'required',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->updated_at = now();
$todo->save();
session()->flash('message','Updated Successfully!');
return redirect('/todo');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$todo = todo::find($id);
$todo -> delete();
session()->flash('message','Deleted Successfully!');
return redirect('/todo');
}
}
error is in this code
$this->validate($request,[
'body'=>'required',
'title'=>'required|unique:todos',
]);
but as per laravel documentation my validate method is right.
Please let me know what I am doing wrong in my controller.
I have also googled for this error but no success.
I have also tried using these lines :
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Validator;
But no success. Please help me since i am getting this error for last 10 days. I don't understand what to do now. Your help will be appreciated. thanks.

Although other answers might contain valid alternative way, $this->validate(...) should work without any problem in your controller. But you should make sure you haven't changed anything from standard Laravel base controller.
Default controller located here looks like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
As you see it contains ValidatesRequests trait and this trait provides validate method. So take a look at your app/Http/Controllers/Controller.php file and make sure it looks like this above.

$validatedData = $request->validate([
'body'=>'required',
'title'=>'required|unique:todos',
]);
$todo = new todo;
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect('/todo');
If the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.
Check Writing The Validation Logic in docs again.

Try this :
use Validator;
....
....
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
link : https://laravel.com/docs/5.7/validation#automatic-redirection

I was getting an issue as I was trying to use it like this
$this->validate(request(), [
"title" => "required",
]);
Made a silly mistake there.
make sure you use your controller from right place.
use App\Http\Controllers\Controller;

Related

Laravel: How do I raise a 404 error instead of a 50X error when ID for resource is non-integer

I created a simple crud in Laravel, but I'm having a problem:
I am using Illuminate\Support\Facades\Route::resource method, this is my routes/web.php:
<?php
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
Route::get('/', function () {
return Inertia::render('Welcome', [
'canLogin' => Route::has('login'),
'canRegister' => Route::has('register'),
'laravelVersion' => Application::VERSION,
'phpVersion' => PHP_VERSION,
]);
});
Route::get('dashboard', [App\Http\Controllers\PageController::class, 'dashboard'])
->middleware('auth:sanctum')
->name('dashboard');
Route::resource('notes', App\Http\Controllers\NoteController::class)
->middleware('auth:sanctum');
app/Http/Controllers/NoteController.php:
<?php
namespace App\Http\Controllers;
use App\Models\Note;
use Illuminate\Http\Request;
use Inertia\Inertia;
class NoteController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if ($request->q) {
return Inertia::render('Notes/Index', [
'notes' => Note::where('title', 'ilike', "%$request->q%")->get(),
]);
}
return Inertia::render('Notes/Index', [
'notes' => Note::all()
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return Inertia::render('Notes/Create', [
'note' => new Note()
]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$note = Note::create($request->validate([
'title' => 'required',
'content' => 'required',
]));
return redirect()->route('notes.show', $note)->with('success', 'Nota creada');
}
/**
* Display the specified resource.
*
* #param \App\Models\Note $note
* #return \Illuminate\Http\Response
*/
public function show(Note $note)
{
return Inertia::render('Notes/Show', compact('note'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Note $note
* #return \Illuminate\Http\Response
*/
public function edit(Note $note)
{
return Inertia::render('Notes/Edit', compact('note'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Note $note
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Note $note)
{
$request->validate([
'title' => 'required',
'content' => 'required',
]);
$note->update($request->all());
return redirect()->route('notes.show', $note)->with('success', 'Nota actualizada');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Note $note
* #return \Illuminate\Http\Response
*/
public function destroy(Note $note)
{
$note->delete();
return redirect()->route('notes.index')->with('success', 'Nota eliminada');
}
}
When I go to /notes/a where 'a' is supposed to be the index of the note I want to see, I get a 500 error:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type bigint: "a"
select * from "notes" where "id" = a limit 1
At this point, none of my code has yet run. How can I catch this error to raise a 404 error instead?
you can use firstOrFail() or findOrFail example code below
public function find(Request $request){
return Note::findOrFail($request->id);
}
You can use abort(404) which abort your code if no data found.
public function findNote($id)
{
$note = Note::find($id)
if($note == null)
{
abort(404);
}
}
you can use try catch block to modify the response
public function whatEverMyMethodIs( Request $request ) {
try {
return ModeL::find( $request->input('id') );
} catch (\Throwable $th) {
return response()->json(['message' => $th->getMessage()], 404 );
}
}
Since you're using the built-in resource controller, the following URIs, among others, will have been created and model binding happens. If the parameter doesn't fit the id's type it will error out.
GET /notes/{note}
GET /notes/{note}/edit
I have not found a way to modify the request validation when model binding happens. If you wish to customise the behaviour, you can do so by leaving the show and edit functions out of the route resource declaration and writing custom endpoints listed above.
routes/web.php
Route::resource('notes', NoteController::class)->except([
'show', 'edit'
]);
Route::get('/notes/{note}', [
'as' => 'notes.show',
'uses' => '\App\Http\Controllers\NoteController#show',
]);
app/Http/Controllers/NoteController.php
use Illuminate\Http\Request;
...
public function show(Request $request)
{
$noteId = $request->note;
...
}
You can perform the validation by switching Request to a custom request which inherits FormRequest.
More information can be found here:
https://laravel.com/docs/9.x/validation#form-request-validation

"Class 'App\Models\Post' not found"

I'm trying to let my users made posts in my social media website. I already have a 'App\Models\Post'. How do I solve it??
Also the error appears when I try to submit the post, and the trouble is in the line that says: "$post = new Post();"
Ok, so here says that it looks like my post is mostly code, so I'll write no sense things so this pritty little thing go off. I'm not a native english speaker, so if you find a spelling or grammatical error please correct me :)
Here is the code of my Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post ;
use App\User;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('makePost');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function makePost(Request $request)
{
$this->validate($request, array(
'post' => 'required',
'title' => 'nullable|max:50',
'label' => 'nullable|max:25',
));
$post = new Post();
$post->post = $request->post;
$post->title = $request->title;
$post->label = $request->label;
$post->save();
return redirect()->route('index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
And here is my Post Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function Users() {
return $this->belongsTo(User::class);
}
}
You defined the namespace in your Model wrong, if its in the Model directory change it to:
namespace App\Models;
If not you can always change your controller to:
use App\Post;
Try to use:
use App\Post;
Instead of use App\Models\Post ;

ErrorException in SessionGuard.php | Getting error when trying to register user while creating new order

I want user to register and also buy a package. To do that I took input for registration details and package details. Now when I'm processing order to save package details in session and register, I get this error : Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\View\View given, called in C:\xampp\htdocs\rename\app\Traits\OrderRegister.php on line 63 and defined. I'm using an trait to register user and return back to function when registration is complete.
OrderController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Package;
use App\ListingType;
use Illuminate\Support\Facades\Auth;
use App\Order;
use Carbon\Carbon;
use App\Traits\OrderRegister;
class OrderController extends Controller
{
use OrderRegister;
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index($type)
{
$listingtype = ListingType::where('type', '=', $type)->first();
if ($listingtype) {
$packages = $listingtype->packages()->get();
return view('packages.index', compact('packages'));
}
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
$package = Package::where('id', '=', $id)->first();
if (Auth::check()) {
return view('order.create_loggedin', compact('package'));
}
else {
return view('order.create_register', compact('package'));
}
}
/**
* Process a new order request. Store order values in session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function process(Request $request)
{
$order = ['package_id' => $request->package_id, 'order_qty' => $request->no_of_listing];
session(['order' => $order]);
if (Auth::guest()) {
return $this->register($request); // need to check session for orders available in OrderRegister trait.
}
return $this->store($request);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if($request->session()->has('order')) {
$package = Package::where('id', '=', $request->package_id )->first();
if($request->user() == Auth::user()) {
for( $n=1;$n<=$request->no_of_listing;$n++) {
$order = new Order;
$order->package_id = $request->package_id;
$order->user_id = Auth::user()->id;
$order->expire_at = Carbon::now()->modify('+'.$package->duration_in_months.' months');
$order->save();
}
return redirect('/');
}
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
trait : OrderRegister.php
<?php
namespace App\Traits;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
trait OrderRegister
{
use RedirectsUsers;
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'username' => 'required|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
$user->profile()->save(new UserProfile);
return $user;
}
/**
* Execute the job.
*
* #return void
*/
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::guard($this->getGuard())->login($this->create($request->all()));
return $this->store($request);
}
/**
* Get the guard to be used during registration.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
I could not find any solution for this error so created my own thread for the first time please someone help.
It throws an error because you are trying to login a vue.
in your OrderController.php you are using create method which return a view.
this method will override the create method on your trait.
So you have something like this :
Auth::guard($this->getGuard())->login(/* A view */);
you can at least rename the method on the trait from create to createUser for example.
then you call it from the guard like this :
Auth::guard($this->getGuard())->login($this->createUser($request->all()));

I can't get data when i am editing in laravel 5.1

i have address Book table and user table i am assigning
the many user in my address book while i am created everything is fine(ok)
but when i am editing every data back in my form without assign user .
how can i get the user in editing form ?? this is my Address Book Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\AddressRequest;
use App\Http\Requests;
use App\Models\Address;
use App\Models\User;
use App\Http\Controllers\Controller;`enter code here`
use Illuminate\Pagination\Paginator;
use Auth;
use DB;
use Session;
class AddressesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(Request $request)
{
Session::forget('searchaddress');
$addresses = Address::orderby('company_name');
$company_name = $request->input('company_name');
if(!empty($company_name)) {
//$addresses->where('company_name','LIKE','%'.$company_name.'%');
$addresses->where('company_name','LIKE','%'.$company_name.'%');
Session::set('searchaddress', $company_name);
}
$addresses = $addresses->paginate(5);
return view('address.index',compact('addresses'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$users = User::lists('first_name','id');
return view('address.create',compact('users'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(AddressRequest $request)
{
$address = Address::create($request->all());
$firstname = Auth::user()->first_name;
$lastname = Auth::user()->last_name;
$address->created_by =$firstname." ".$lastname;
$address->users()->attach($request->input('user_list'));
$address->save();
return redirect('/addresses');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$address = Address::find($id);
return view('address.show',compact('address'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{ $users = User::lists('first_name','id');
$address = Address::findorFail($id);
return view('address.edit',compact('address','users'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update( AddressRequest $request ,$id)
{
$address = Address::findOrFail($id);
$address->update($request->all());
$address->users()->sync($request->input('user_list'));
return redirect('/addresses');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$address = Address::find($id);
$address->delete();
return redirect('/addresses');
}
}
and that is my AddressBook Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
protected $fillable = [
'created_by',
'company_name',
'phone',
'email', 'address','comment'
];
public function users()
{
return $this->belongsToMany('App\Models\User')->withTimestamps();
}
public function getUserListAttribute()
{
return $this->users->lists('id');
}
}
[![enter image description here][1]][1]
[1]: http://i.stack.imgur.com/D4jXQ.png
You have belongsToMany relation, so in your edit action you also should get current Address users like this
public function edit($id)
{ $users = User::lists('first_name','id');
$address = Address::findorFail($id);
$address_users = $address->users->lists('id')->toArray();
return view('address.edit',compact('address','users', 'address_users'));
}
then in your view in select you should intersect arrays of $users and $address_users to get selected options.
{!! Form::select('user_list[], $users, isset($address_users) ? $address_users : null, ['id' => 'users_list', 'class' => 'form-control', 'multiple']) !!}
to avoid
isset($address_users) ? $address_users : null
you can define empty address_users array in your create method and do it like this
$address_users

Form request not working for controllers within subfolder of Controller folder

My folder structure for controllers is:
and I use following route code to access those controllers.
here I have allocated sub-folders inside Controller folder and updated namespaces as per needed on files and routes accordingly, this works perfectly, however when I use request file for validating form. It gives error:
Argument 1 passed to App\Http\Controllers\site\usersController::store()
must be an instance of Illuminate\Http\Request, string given
but when I move all controllers file to Controller folder and don't use sub-folder,form request validation works.My usersController and UserRegReq request files are:
usersController.php
<?php
namespace App\Http\Controllers\zcms;
use Illuminate\Http\Request;
use App\Services\FieldService;
use App\Services\UserService;
use App\Http\Requests;
use App\Http\Requests\UserRegReq;
use App\Http\Controllers\Controller;
class usersController extends Controller {
public function __construct(FieldService $field, UserService $user)
{
$this->field = $field;
$this->user = $user;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function throwLogin()
{
return view('zcms.pages.login');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$field = $this->field->fieldList();
return view('zcms.users.addnew', compact('field'));
}
/**
* Store a newly created resource in storage.
*
* #param Request $request
* #return Response
*/
public function store(UserRegReq $request)
{
return "hello";
}
/**
* 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 Request $request
* #param int $id
* #return Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
UserRegReq.php
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class UserRegReq extends Request {
/**
* 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 [
'field_id' => 'required',
'name' => 'required',
'username' => 'required',
'password' => 'required'
];
}
// public function messages(){
// return [
// 'field_id.required'=>'The related Field of your Job is required',
// ];
// }
}
What should I do beside updating namespace in routes and controller file to make everything work?

Resources