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)
Related
I'm learning Laravel and I can't solve one thing.
I would like that the users after the login are directed in their own profile, the local domain of the single profile is composed http://127.0.0.1:8000/profile/user_id.
I try modify this:
//public const HOME = '/home';
public const HOME = "/profile/{user_id}";
but doesn't working I get this URL http://127.0.0.1:8000/profile/%7Buser_id%7D
Laravel Version 8.83.5
Routeserviceprovider.PHP
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* #var string
*/
public const HOME = "/profile/{user_id}";
/**
* The controller namespace for the application.
*
* When present, controller route declarations will automatically be prefixed with this namespace.
*
* #var string|null
*/
// protected $namespace = 'App\\Http\\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* #return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
}
}
Web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/', 'App\Http\Controllers\ProfilesController#index');
Route::get('/c/create', 'App\Http\Controllers\CoursesController#create');
Route::get('/c/{course}', 'App\Http\Controllers\CoursesController#show');
Route::post('/c', 'App\Http\Controllers\CoursesController#store');
Route::get('/profile/{user}', [App\Http\Controllers\ProfilesController::class, 'index'])->name('profile.show');
Route::get('/profile/{user}/edit', 'App\Http\Controllers\ProfilesController#edit')->name('profile.edit');
Route::patch('/profile/{user}', 'App\Http\Controllers\ProfilesController#update')->name('profile.update');
Profilescontroller.PHP
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Intervention\Image\Facades\Image;
class Profilescontroller extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
// public function invoke()
//{
//$users = auth()->user()->profile()->pluck('profiles.user_id');
//$profiles = Profilescontroller::whereIn('user_id', $users)->get();
//return view("/profile/{$user->id}");
//}
public function index(User $user)
{
$this->authorize('update', $user->profile);
return view('profiles.index', compact('user'));
}
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profiles.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'description' => '',
'image' => '',
]);
if (request('image')) {
$imagePath = request('image')->store('profile', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1000, 1000);
$image->save();
$imageArray = ['image' => $imagePath];
}
auth()->user()->profile->update(array_merge(
$data,
$imageArray ?? []
));
return redirect("/profile/{$user->id}");
}
}
I think what you are looking for is
App\Http\Controllers\Auth\LoginController.php
From here is where you do the redirecting after log in. If you go into the authenticated function. You can do your logic here like know who the user is and grab their id and return a redirect to their profile page.
You can override the LoginResponse class.
You can find the LoginResponse file in vendor/laravel/fortify/src/Http/Responses directory. Then create a new php file in your app/Http/Responses directory (if it does not exists, create the directory) named "LoginResponse.php".
Then you need to copy & paste that the code inside LoginResponse class that you found in vendor directory and change the namespace line as namespace App\Http\Responses;.
Then edit redirect line as you want. In this situation you need to edit like following code.
: redirect()->route('your_profile_route_name', auth()->user()->id);
Then you need to add the following code in the end of boot() function inside the app/Providers/FortifyServiceProvider.
$this->app->singleton(\Laravel\Fortify\Contracts\LoginResponseContract::class, \App\Http\Responses\LoginResponse::class);
Now it's all over.
I am working with laravel API and I want that when I type this endpoint "verify" as in " http://.../api/verify" the users email automatically gets verified. This is my code so far, but it isn't working. It is giving me this error "message": "", please let me know if you have any idea on how I can get this done. Thank you
this is my first trial
Route::group(['middleware' => ['auth:sanctum']], function (){
Route::get('/verify', [VerifyEmailController::class, 'verify'])->name('verification.verify');
});
and this is the controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\Request;
use Illuminate\Auth\Access\AuthorizationException;
class VerifyEmailController extends Controller
{
/**
* Mark the authenticated user's email address as verified.
*
* #param \Illuminate\Foundation\Auth\EmailVerificationRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function __invoke(EmailVerificationRequest $request)
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(RouteServiceProvider::HOME.'?verified=1');
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect()->intended(RouteServiceProvider::HOME.'?verified=1');
}
public function verify(Request $request)
{
if ($request->route('id') != $request->user()->getKey()) {
throw new AuthorizationException;
}
if ($request->user()->hasVerifiedEmail()) {
return response(['message'=>'Already Verified']);
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return response(['message'=>'Successfully Verified']);
}
}
this is my second trial
Route::group(['middleware' => ['auth:sanctum']], function (){
Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
$request->fulfill();
})->middleware(['auth', 'signed'])->name('verification.verify');
});
this is my last trial
Route::group(['middleware' => ['auth:sanctum']], function (){
Route::get('/email/verify/{id}/{hash}', [VerificationController::class, 'verify'])->name('verification.verify');
});
and this is the controller
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\Auth;
class VerificationController extends Controller
{
/*
|--------------------------------------------------------------------------
| Email Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
use VerifiesEmails;
/**
* Where to redirect users after verification.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('signed')->only('verify');
$this->middleware('throttle:6,1')->only('verify', 'resend');
}
public function verify($id, Request $request) {
if (! $request->hasValidSignature()) {
return response(['message'=>'invalid_email_verification_url']);
}
$user = User::findOrFail($id);
if (!$user->hasVerifiedEmail()) {
$user->markEmailAsVerified();
}
return redirect()->to('/');
}
}
I created middleware: php artisan make:middleware CheckUserStatus
In this middleware I have:
namespace App\Http\Middleware;
use Closure;
class CheckUserStatus
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth()->check() AND Auth()->user()->status === 0) { // user is logged in but it is blocked
auth()->logout();
return redirect('/');
}
return $next($request);
}
}
Then, one of my controller I have:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Middleware\CheckUserStatus;
class productsController extends Controller
{
public function __construct () {
$this->middleware('auth');
$this->middleware('CheckUserStatus');
}
}
This gives ReflectionException - Class CheckUserStatus does not exist
What I'm doing wrong ?
You need to register your middleware if you want to reference it by a string key. Check out the docs here.
Alternatively, you could use the fully qualified class name: try CheckUserStatus::class instead of 'CheckUserStatus'.
You need to use the fully qualified class name:
Either:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class productsController extends Controller
{
public function __construct () {
$this->middleware('auth');
$this->middleware('\App\Http\Middleware\CheckUserStatus');
}
}
or
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Middleware\CheckUserStatus;
class productsController extends Controller
{
public function __construct () {
$this->middleware('auth');
$this->middleware(CheckUserStatus::class); //No quotes
}
}
You need to add your middleware in kernel.php
protected $routeMiddleware = [
'your_desire_name'=>\App\Http\Middleware\CheckUserStatus::class,
];
I'm new to Laravel so I'm not familiar with errors in the framework .I'm trying to get the user to make a post but I'm getting the above error .Could you please tell where I'm going wrong ?Thank you
This is my HomeController class:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $r)
{
if(Input::has('status-text'))
{
$text = e(Input::get('status-text'));
$userStatus = new Status();
$userStatus->status_text = $text;
$userStatus->save();
Flash::success('Your status has been posted');
return redirect(route('home'));
}
return view('home');
}
}
And this is my web.php class :
<?php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::any('/home', ['as'=> 'home','uses' =>'HomeController#index']);
Don't use Input::get(), use $r->get() as you're injecting the request as a dependency to the index method already, and Input:: is merely a alias to access the underlaying Request.
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