Laravel Store function ignored on production server - laravel

I'm making a website that 100% works locally but when uploaded to my server everything works except the Store function(/route) for pages.
Expected behaviour when I click the Add button: PageController#store to be executed.
What happens when I click the Add button locally: PageController#store gets executed.
What actually happens when I click the Add button on my server: It just seems to go to pages.index without executing PageController#store.
Let's say I put return "test"; in the Store function instead of the storing logic and change StoreRequest to Request, it still just goes to pages.index without showing the text test even though this also does work locally.
Why is this happening? All the code it the same, and all the other routes and functions work perfectly fine. Everything works except saving/storing.
Routes:
Auth::routes();
Route::get('/', 'HomeController#welcome')->name('welcome');
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('pages', 'PageController');
PageController:
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StorePage;
use App\Http\Requests\UpdatePage;
use App\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
class PageController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$data = [
'pages' => Page::all()
];
return view('pages.index')->with($data);
}
public function create()
{
return view('pages.create');
}
public function store(StorePage $request)
{
$page = new Page();
$page->fill($request->all());
$page->save();
return Redirect::route('pages.index');
}
public function edit(Page $page)
{
$data = [
'page' => $page
];
return view('pages.edit')->with($data);
}
public function update(UpdatePage $request, Page $page)
{
$page->fill($request->all());
$page->save();
return Redirect::route('pages.index');
}
public function destroy(Page $page)
{
$page->delete();
return Redirect::route("pages.index");
}
}
Form:
{{Form::open(array('route' => array('pages.store')))}}
#method('POST')
#csrf
<div class="row">
<div class="col-md-12">
{{ Form::label('title', 'Title:') }}
{{ Form::text('title', null, array('class' => 'form-control '.($errors->has('title') ? ' is-invalid' : ''),'required')) }}
#if ($errors->has('title'))
<small class="text-danger" role="alert">
<strong>{{ $errors->first('title') }}</strong>
</small>
#endif
</div>
</div>
<div class="row">
<div class="col-md-12">
{{ Form::label('identifier', 'Identifier:') }}
{{ Form::text('identifier', null, array('class' => 'form-control '.($errors->has('identifier') ? ' is-invalid' : ''),'required')) }}
#if ($errors->has('identifier'))
<small class="text-danger" role="alert">
<strong>{{ $errors->first('identifier') }}</strong>
</small>
#endif
</div>
</div>
<div class="row">
<div class="col-md-12">
{{ Form::label('content', 'Content:') }}
{{ Form::textarea('content', null, array('class' => 'form-control '.($errors->has('content') ? ' is-invalid' : ''),'required')) }}
#if ($errors->has('content'))
<small class="text-danger" role="alert">
<strong>{{ $errors->first('content') }}</strong>
</small>
#endif
</div>
</div>
<br />
<button type="submit" class="btn btn-primary">Add</button>
{{Form::close()}}

Some files are cached in the server, so you may not be seeing the effect of your application file changes all the time.
Try clearing and reloading your application and route caches by running these commands on the server cli in order:
php artisan cache:clear
php artisan route:cache
php artisan config:cache
composer dump-autoload

After a bit of digging I saw that the request returned 403 Forbidden. I had a folder called 'pages' which is exactly where the POST request was going: /pages/. Renaming this folder fixed my problem.

Related

Route is not defined after successful log in

little bit stuck with redirecting to other page after successful login for quite a long time. I believe that my understanding about sanctum auth is a bottleneck for this issue( Or maybe I am wrong ). However, after reading the docs still couldn't find the answer to my issue. Situation: I have declared few public routes and one private. I have created a user in my database and whenever I try successfully to log in it does not redirect to other page, and my credentials are 110% correct, but anyway after submit it only displays:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [/dashboard] not defined.
However, I have that route, it's protected but after sign in I assign it. Maybe I am doing in a wrong way?
welcome.blade:
#section('content')
<div class="container-fluid">
<div class="container">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
<form action="{{action('App\Http\Controllers\AuthController#login')}}" method="POST">
#csrf
<input type="text" class="form-control" placeholder="Email address" name="username" required>
<input type="password" class="form-control" placeholder="Password" name="password" required>
<div class="login-btn">
<button type="submit" class="btn btn-success">Sign in</button>
</div>
</form>
</div>
</div>
</div>
#endsection
AuthController:
public function login(Request $request)
{
$fields = $request->validate([
'username' => 'required',
'password' => 'required',
]);
$user = User::where('username', $fields['username'])->first();
if (!$user || !Hash::check($fields['password'], $user->password)) {
return Redirect::back()->withInput()->withErrors('Incorrect username or password');
} else {
$token = $user->createToken($request->username);
return redirect()->route('/dashboard')->with('token', $token);
}
}
web.php :
// Private routing
Route::group(['middleware' => ['auth:sanctum']], function () {
// Agents dashboard
Route::get('/dashboard', function () {
return view('dashboard.main');
})->name('dashboard');
});
// Public routing
Route::get('/', function () {
return view('welcome');
});
Route::post('/login', [AuthController::class, 'login'])->name('login');
Dashboard -> main:
#extends('layouts.app')
#section('content')
<h1>Private</h1>
#endsection
change ->route('/dashboard') to ->route('dashboard'). This value references the name value on a route. eg:
Route::get('/dashboard', function () {
return view('dashboard.main');
})->name('dashboard');

How to use the same form for add and edit in laravel

I'm new to laravel,i want to use the same form for add and edit.I created an form and form insertion is ok but i need to use the same form edit based on the id selected.When click the edit icon i want to direct the same page displaying the contents to edit.So give me idea for implementing this.
<form method="POST" action="/categoryinsert">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="card-body">
<div class="form-group">
<div class="col-md-4">
<label for="exampleInputEmail1">Category</label>
<input type="text" class="form-control" name="category" id="category" placeholder="Enter Category">
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
// To create a new user in controller
public function create()
{
// user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate');
}
// To update an existing user
public function edit($id)
{
$user = User::find($id);
// user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate')->with('user', $user);
}
Add/edit in view with the help of user model
#if(isset($user))
{{ Form::model($user, ['route' => ['updateroute', $user->id], 'method' => 'patch']) }}
#else
{{ Form::open(['route' => 'createroute']) }}
#endif
{{ Form::text('fieldname1', Input::old('fieldname1')) }}
{{ Form::text('fieldname2', Input::old('fieldname2')) }}
{{ Form::submit('Save', ['name' => 'submit']) }}
{{ Form::close() }}
// To create a new user in controller
public function create()
{
// user/createOrUpdate.blade.php view
return view('user.createOrUpdate')->with([
'view_type' => 'create',
]);
}
// To update an existing user
public function edit($id)
{
$user = User::find($id);
// user/createOrUpdate.blade.php view
return view('user.createOrUpdate')->with([
'view_type' => 'edit',
'user' => $user
]);
}
<form action="{{ ( $view_type == 'edit' ? route('example', $id) : route('control.mentors.store')) }}" role="form" method="post" name="frmDetail">

How can I display required message in laravel?

My view like this :
{!! Form::open(['url' => 'product/store','class'=>'form-horizontal') !!}
...
<div class="form-group">
<label for="description" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
{!! Form::textarea('description', null, ['class' => 'form-control', 'rows'=>5]) !!}
</div>
</div>
...
{!! Form::close() !!}
My controller like this :
use App\Http\Requests\CreateProductRequest;
public function store(CreateProductRequest $request)
{
dd($request->all());
}
My required like this :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateProductRequest extends FormRequest {
public function authorize() {
return true;
}
public function rules() {
return [
'description'=>'required'
];
}
}
If the description is not filled and click submit button, it will not be saved and it will return to the form. When returning to the form, I want to display a message that the description should be filled
I created an html to display a message like this :
<div class="alert alert alert-danger" role="alert">
Description is required
</div>
How can I call the html tag if the description is not filled?
For display a single message I usually use:
#if($errors->has('description'))
<label class="text-danger text-small">{{$errors->first('description')}}</label>
#endif
for more information please check https://laravel.com/docs/5.4/validation#quick-displaying-the-validation-errors
Your all the validation errors are stored in $errors variable. You can access them using $error varibable. But must check if the error message exist using has() method as
#if($errors->has('description'))
<label class="text-danger text-small">{{$errors->first('description')}}</label>
#endif

Laravel 5.4 Show flash error and success messages in different ways

Method from my PostController
public function store(PostRequest $request)
{
if (Post::create($request->all())) {
$request->session()->flash('status', 'Post was successfully added!');
} else {
$request->session()->flash('status', 'Error!');
}
return redirect('/');
}
index view
<?php if(session()->has('status')){
echo '<div style="text-align: center">';
echo session()->get('status');
echo '</div>';
}?>
How to show error and success messages in different ways?
You can use something like this:
public function store(PostRequest $request) {
if (Post::create($request->all())) {
$request->session()->flash('message.level', 'success');
$request->session()->flash('message.content', 'Post was successfully added!');
} else {
$request->session()->flash('message.level', 'danger');
$request->session()->flash('message.content', 'Error!');
}
return redirect('/');
}
In your blade file:
#if(session()->has('message.level'))
<div class="alert alert-{{ session('message.level') }}">
{!! session('message.content') !!}
</div>
#endif
The code above uses bootstrap's alert css classes for styling and is inspired by Jeffrey Way's Laracasts Flash package
You can display flash messages in this way:
In your controller:
$request->session()->flash('success', 'Record successfully added!');
//OR
$request->session()->flash('warning', 'Record not added!');
In your veiw:
#foreach (['danger', 'warning', 'success', 'info'] as $key)
#if(Session::has($key))
<p class="alert alert-{{ $key }}">{{ Session::get($key) }}</p>
#endif
#endforeach
Write code like this in your Blade template:
#if(Session::has('error'))
<p class="alert alert-danger">{{ Session::get('error') }}</p>
#endif
Write code like this in your Controller:
Session::flash('error', 'Some thing is wrong. Please try again');
Redirect::to(path to blade file route);
You can use ->with() in your controller
public function store(PostRequest $request) {
if (!Post::create($request->all())) {
return redirect('/')->with('error', 'Error!');
}
return redirect('/')->with('success', 'Post was successfully added!');
}
Your view could look like this:
#if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
#endif
#if (session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
#endif
or (with additional CSS for alert-error class):
#foreach (['error', 'success'] as $status)
#if(Session::has($status))
<p class="alert alert-{{$status}}">{{ Session::get($status) }}</p>
#endif
#endforeach

Laravel - If has errors on validation, insert class in the specifics inputs

I'm totally noob in PHP, but my question is, after the validation which has errors for specific inputs, how can I insert a class in the specific input?
Example, if i have this error in the validation: "The email field is required."
How can i insert a specific class in the email input?
Login routes:
Route::group(['prefix' => 'admin'], function () {
Route::get('/', 'Admin\AdminController#index');
Route::get('login', 'Admin\AuthController#getLogin');
Route::post('login', 'Admin\AuthController#postLogin');
Route::get('logout', 'Admin\AuthController#getLogout');
});
AdminController:
class AdminController extends AdminBaseController
{
public function index()
{
if(Auth::user()){
return view('admin/pages/admin/index');
}
return view('admin/pages/login/index');
}
}
AuthController:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
private $redirectTo = '/admin';
public $loginPath = '/admin';
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
public function getLogin()
{
if(Auth::user()){
return redirect('/admin');
}
return view('admin/pages/login/index');
}
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
}
}
My blade form:
<form class="s-form" role="form" method="POST" action="/admin/login">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="s-form-item text">
<input type="text" name="email" value="{{ old('email') }}" placeholder="Email">
</div>
<div class="s-form-item text">
<input type="password" name="password" value="{{ old('password') }}" placeholder="Senha">
</div>
<div class="s-form-item">
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif
</div>
<div class="s-form-item s-btn-group s-btns-right">
<input class="s-btn" type="submit" value="Entrar">
</div>
</form>
You can pass an argument to the has method to specify the specific key.
For example, for your email input...
<input class="#if($errors->has('email')) some-class #endif" ... >
I left out the rest of the input field for brevity. It basically checks if an error for the email input exists. If so, 'some-class' is outputted. Otherwise, it skips over it.
Edit: To answer the question on how you can customize where to output your error messages, you can use the get or first methods in conjunction with the has method. For example...
#if ($errors->has('email'))
#foreach ($errors->get('email') as $error)
<p>{{ $error }}</p>
#endforeach
#endif
The has method has already been explained. The get method retrieves the validation errors. Because there can be more than one validation error, you must loop through it and output it.
In the next example, I use first. This method just outputs the first error message so there is no need to loop through it.
#if ($errors->has('email'))
<p>{{ $errors->first('email') }}</p>
#endif

Resources