Form request not working for controllers within subfolder of Controller folder - laravel-5

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?

Related

Laravel, Show(), Edit (), update functions not working

In the code below methods show, edit update are not working.
<?php
namespace App\Http\Controllers\admins;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\contact;
use Image;
use Auth;
use Storage;
use File;
class ContactController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$contact = Contact::orderby('created_at', 'desc')->paginate(5);
//$agent=Agent::orderby('id','desc')->paginate(5);
return view('admin.messages.index', ['contacts' => $contact]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return back()->with('success', 'Message can only be created by Users end.');
}
/** * Display the specified resource.
*
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function show(contact $contact)
{
dd(['contact' => $contact]);
//return back()->with('success','Message Contents Are Already Shown');
}
/**
* Show the form for editing the specified resource.
*
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function edit(contact $contact)
{
return view('admin.messages.edit', compact('contact'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function update(Request $request, contact $contact)
{
dd($request);
}
/**
* Remove the specified resource from storage.
*
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function destroy(contact $contact)
{
return back()->with('success', 'Message history can not be Deleted. ');
}
}
Assuming you are using a slug in a route like contacts/{ slugĀ }
public function show(contact $contact)
{
dd(['contact' => $contact]);
//return back()->with('success','Message Contents Are Already Shown');
}
Receives an id not a contact... you are initializing/declaring in the function parameter as contact thats why it somehow gets casted to a contact... but it's an id you should do something like:
public function show($id)
{
$contact = Contact::findOrFail($id);
dd(['contact' => $contact]);
//return back()->with('success','Message Contents Are Already Shown');
}

"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 ;

laravel 5.5 FormRequest class is redirecting to me i need send array errors response

I have a problem when i validate a request with a FormRequest extended class. Because is redirecting when a bad request is recived and i need a response with the validation errors.
I'm using:
PHP 7.1.1 (cli) (built: Jan 18 2017 18:51:14) ( ZTS MSVC14 (Visual C++ 2015) x86 )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies.
Laravel v5.5.2.
My FormRequest class:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BillRequest 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 [
'testfield' => 'required'
];
}
}
My Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\BillRequest;
use App\Bill;
class BillController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(BillRequest $request)
{
$bills = Bill::paginate(10);
return $bills;
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(BillRequest $request)
{
$bill = new Bill($request->all());
$bill->save();
return response('', 201);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$bill = Bill::find($id);
$bill->customer->person;
$bill->vehicle;
$bill->items;
return response($bill, 200);
}
/**
* 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(BillRequest $request, $id)
{
$bill = Bill::find($id);
$bill->fill($request->all());
$bill->save();
return response('', 200);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$bill = Bill::find($id);
$bill->delete();
return response('', 204);
}
}
Route (api.php):
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['prefix' => 'admin' ], function () {
Route::resource('bills', 'BillController', [
'only' => ['index', 'update', 'show']
]);
});
Finally, the response with the field 'testfield' (in the request) is the JSON with the data paginated. But when i send the request without the field then redirect to localhost:8000/
I solved the problem. It's for a missing header in the request.
Content-Type:application/json
X-Requested-With:XMLHttpRequest
I experience the same problem using Laravel 5.5.3
There are many people who recommend to overwrite the response method in the custom FormRequest class, anyway this doesn't seem to work any longer since the method failedValidation is called before. This method throws an Illuminate\Validation\ValidationException.
You can catch this exception in app/Exceptions/Handler.php
To validate json in Laravel, check Laravel documentation
https://laravel.com/docs/5.5/validation#available-validation-rules

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()));

Laravel 5.0 | Changing default actions' names is not working for a resource controller

I have created a productController resource in the route.php file like this:-
Route::resource('products','ProductController',['names' => ['create' => 'products.add']]);
Here is how my productController.php file looks like:-
<?php namespace lvtest\Http\Controllers;
use lvtest\Http\Requests;
use lvtest\Product;
use lvtest\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ProductController extends Controller {
/**
* Class constructor .. requires authentication
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$products = Product::all();
return view('products.productsList', ['products' => $products]);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function add()
{
return 'Add a product';
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
return 'store new product?';
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id = null)
{
// $products = Product::all();
// print_r($products);
}
/**
* 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)
{
return 'store new product?';
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
and passed the 'names' array to change the default name of the create method to add.
When I go to localhost:8000/products/add I get a blank page.
How do I fix this
Adding the ['names' => ['create' => 'products.add'] to your resource route will only change the Route Name, and not the Route Method. This means that you can refer to your route as route('products.add') and it will point to the create() method on your controller.
When you use Route::resource Laravel will expect that you have a create() method on your controller. To be able to do what you suggest, you might need to add the method to your controller, and then add a separate route:
Route::resource('products','ProductController');
Route::get('products/add', ['as' => 'products.add', 'uses' => 'ProductController#add']);

Resources