I have some problems with my code. I am following the tutorial in Laravel 5. I am doing the form validation but I got this error and I don't know how did it happened. I am new to Laravel.
I am creating the article sample.
Here's my controller:
<?php namespace App\Http\Controllers;
use App\Article;
use App\Http\Requests;
use App\Http\Controllers\Controller;
//use Illuminate\Http\Request;
use Carbon\Carbon;
//use Request;
class ArticlesController extends Controller {
public function index() {
//$articles = Article::all();
//$articles = Article::latest('published_at')->where('published_at', '<=', Carbon::now())->get();
/** select * from articles where published_at <= now() order by published_at desc */
$articles = Article::latest('published_at')->published()->get();
return view('articles.index', compact('articles'));
}
public function show($id) {
$article = Article::findOrFail($id);
//dd($article->published_at);
return view('articles.show', compact('article'));
}
public function create() {
return view('articles.create');
}
public function store(CreateArticleRequest $request) {
//$input = Request::all();
//$input['published_at'] = Carbon::now();
//$title = Request::get('title');
Article::create($request->all());
return redirect('articles');
}
}
Here's my Request
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class CreateArticleRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true; //permissions
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required',
'published_at' => 'required|date'
];
}
}
My Route:
<?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('/', 'WelcomeController#index');
Route::get('home', 'HomeController#index');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Route::get('articles','ArticlesController#index');
Route::get('articles/create','ArticlesController#create');
Route::get('articles/{id}','ArticlesController#show');
Route::post('articles','ArticlesController#store');
When I checked it doesn't allow me to insert in the database.
It is throwing ReflectionException because you are using wrong class. You should use App\Http\Requests\CreateArticleRequest instead of App\Http\Requests in ArticlesController
You have to include the CreateArticleRequest you are using in the controller file which is using it
Add this line after use Carbon\Carbon;
use App\Http\Requests\CreateArticleRequest;
It will include your request file in the controller
Related
I am new to Laravel. I decide to apply my understanding on Laravel to create a simple registration API.
This API will receive three data which are name, email, and password. These input data will be validated inside the Request file. But I found that, if I use the RegisterUserRequest $request inside my Controller file, the method inside controller file is not executed.
Here is my AuthController file:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\RegisterUserRequest;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(RegisterUserRequest $request)
{
return response()->json([
'message' => 'Here',
]);
}
}
Here is my RegisterUserRequest file
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Foundation\Http\FormRequest;
class RegisterUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
];
}
}
Here is my route
Route::group(['namespace' => 'App\Http\Controllers\Api'], function () {
Route::post('register', [AuthController::class, 'register']);
});
Here is the output show on Postman:
Because suppose the output show on Postman would be:
{
"message": "Here"
}
But it don't. So i think that the register method inside the AuthController is not executed.
Is anyone know the problem? Really Appreciated!!!
Thank you.
As you defined, the user is not authorized to make this request:
public function authorize()
{
return false;
}
Set it to true.
In my laravel project i have a login system from another table named agencie. Login functionality is working but view page is returning '404 error'.
Following is my code in Logincontroller.php
<?php
namespace App\Http\Controllers\Agency\AgencyAuth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Hesto\MultiAuth\Traits\LogsoutGuard;
use JsValidator;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers, LogsoutGuard {
LogsoutGuard::logout insteadof AuthenticatesUsers;
}
protected $validationRules = [
'email' => 'required|email',
'password' => 'required'
];
/**
* Where to redirect users after login / registration.
*
* #var string
*/
public $redirectTo = '/agencie/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('agencie.guest', ['except' => 'logout']);
}
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$validator = JsValidator::make($this->validationRules,[],[],'#loginform');
return view('agency.auth.login')->with('validator', $validator);
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('agencie');
}
public function logoutToPath() {
return '/agencie';
}
}
I have created custom roots for agencie to load that, foolowing is the codes in routes/agencie.php
<?php
Route::get('/home', function () {
$users[] = Auth::user();
$users[] = Auth::guard()->user();
$users[] = Auth::guard('agencie')->user();
//dd($users);
// echo "<pre>";print_r($users);exit;
// return view('admin.home');
return redirect()->route('agencie.home');
})->name('home');
Route::group(['prefix' => 'agencie'], function () {
Route::get('/home', 'HomeController#index')->name('agency_home');
});
?>
Following is the code in homecontroller.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
echo "agency page";
}
}
What is the problem here why it is not laoding?
public $redirectTo = '/agencie/home';
Doesn't seem to match:
Route::group(['prefix' => 'agency'], /*...*/);
I am doing MultiAuth in laravel 5.4 I create two tables one for users and the seonde for admins the authentification for usres works fine but when the admin login in it show me this error :
(1/1) ReflectionException
Class App\Http\Controllers\AdminController does not exist
i don't know what is the reason for it, so here is my code :
AdminLoginController:
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Route;
use App\Admin;
class AdminLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin', ['except' => ['logout']]);
}
public function showLoginForm()
{
return view('auth.admin_login');
}
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(route('admin.dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
public function logout()
{
Auth::guard('admin')->logout();
return redirect('/admin');
}
AdminController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//use App\Http\Controllers\Controller;
use App\Admin;
class AdminController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* show dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('admin');
}
}
Actually I'm very new of the php and Laravel5.3,and I have this problem when i want to set request of the form(Doing a simple blog page)
ReflectionException in Route.php line 339: Class App\Http\Controllers\Requests\ArticleRequest does not exist
And this is my controller code(Filename:ArticlesControllers.php):
<?php
namespace App\Http\Controllers;
//namespace App\Http\Controllers;
use App\Http\Requests\ArticleRequest;
use App\Article;
use Carbon\Carbon;
use Illuminate\Http\Request;
class ArticlesControllers extends Controller
{
//
public function index(){
$articles = Article::latest()->get();
//return 'articles';
return view('articles.index')->with('articles',$articles);
}
public function show($id){
$article = Article::find($id);
// if(is_null($article)){
// abort(404);
// }
//dd($artilce);
return view('articles.show',compact('article'));
}
public function create(){
return view('articles.create');
}
public function store(Requests\ArticleRequest $request){
//dd($request->all());
//接受post过来的数据
//存入数据库
//重定向
$input=$request->all();
//$input['published_at']=Carbon::now();
Article::create($input);
return redirect('/articles');
}
}
And the request File code:(Filename:ArticleRequest.php in the path Requests)
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ArticleRequest 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 [
'title'=>'required|min:3',
'content'=>'required',
'published'=>'require'
];
}
}
My Route/Web.php is:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//Route::get('/','SiteController#index');
Route::get('/', function () {
return view('welcome');
});
Route::get('/articles','ArticlesControllers#index');
Route::get('/articles/create','ArticlesControllers#create');
Route::get('/articles/{id}','ArticlesControllers#show');
Route::post('/articles/store','ArticlesControllers#store');
How can i get rid of this nasty problem,I've been searching on StackOverFlow but nearly all the answers may not solve it....
Change it to this to make it work:
public function store(ArticleRequest $request)
you already imported the class at the top
use App\Http\Requests\ArticleRequest
no need to use a full class name as an argument
just use
public function store(ArticleRequest $request)
or
public function store(\App\Http\Requests\ArticleRequest $request)
Hey guys i am newly working on Laravel. I am facing a problem regarding authentication.
Its that whenever i try to authenticate a user and redirect it to a view of a specific controller it works fine but then when i try to open the other view the user authentication does not work ( user logs out ). basically the issue is i have two controllers so if i redirects from authentication to any one of them the other one doesnt have the user.
I hope i have explained my problem clearly
Route List : Result
Route List
Main page routes are the ones that i am working with... others are just dummy as for now
This is my authentication class
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('/');
}
}
return $next($request);
}
}
This is the Index Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class IndexPageController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$user = Auth::user()->firstOrFail();
return view('index')
->with(compact('user'));
//
}
This is the UserProfileController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class UserProfileController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$user = Auth::user()->firstOrFail();
return view('profile.index')
->with(compact('user'));
//
}
Routes
<?php
use Illuminate\Support\Facades\Mail;
/*
|--------------------------------------------------------------------------
| 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.
|
*/
/*Welcome Page routes */
Route::get('/' , function(){
return view('auth.login');
});
Route::get('user/logout' , function(){
Auth::logout();
return redirect('/');
});
Route::post('user/do-login' , 'Auth\AuthController#doLogin');
Route::get('user/create' , 'Auth\AuthController#createUser');
/*---------------------------*/
/*Welcome Page AJAX routes*/
Route::get('/checkAvailibility' , 'WelcomePageController#usercheck');
/*---------------------------*/
/*Images Routes*/
Route::post('image/do-upload' ,'GalleryController#doImageUpload');
Route::post('gallery/save' , 'GalleryController#saveGallery');
Route::get('gallery/list' , 'GalleryController#viewGalleryList');
Route::get('gallery/view/{id}' , 'GalleryController#viewGalleryPics');
Route::get('gallery/delete/{id}' , 'GalleryController#deleteGallery');
/*---------------------------*/
/*Event Routes */
Route::post('create/Image-Upload' , 'CreateEventFormController#ImageUpload');
Route::post('create' , 'CreateEventFormController#store');
Route::get('create/event-image' , 'CreateEventFormController#createEventFormImage');
Route::post('create/event-image' , 'CreateEventFormController#UploadEventImg');
Route::get('create' , 'CreateEventFormController#create');
Route::get('event/{id}' , [ 'as' => 'event_list' , 'uses' => 'CreateEventFormController#show']);
/*---------------------------*/
/*-------------- Main Page Routes -------------------*/
Route::get('event/{id}' , [ 'as' => 'event_list' , 'uses' => 'CreateEventFormController#show']);
Route::get('index' ,[ 'as' => 'index' , 'uses' => 'IndexPageController#index']);
/*-------------- END -------------------*/
/*-------------- Main Page Routes -------------------*/
Route::get('profile' , 'UserProfileController#index');
Route::get('profile/{id}' , 'IndexPageController#show');
/*-------------- END -------------------*/
Route::get('/email', function () {
$data = array(
'name' => "Learning Laravel",
);
Mail::send('emails.test', $data, function ($message) {
$message->from('yourEmail#domain.com', 'Learning Laravel');
$message->to('yourEmail#domain.com')->subject('Learning Laravel test email');
});
return "Your email has been sent successfully";
});
It is possible that there is something with your AuthController.php.
Are you by any chance using Auth::attempt() to authenticate? If so, I have experienced problems in the past where echoing something out after authenticating causes problems.
Another possibility is that something is going wrong with storing the session. It could be something as simple as the session not being saved/written.