Why does the old() method fail in this Laravel 8 form? - php

I am making a blogging application with Laravel 8 and Bootstrap 5.
I run into a problem trying to validate my "Add new article" form: when the form fails validation, the valid fields do not keep their values, despite ne using Blade's old() method.
In the controller, I have:
namespace App\Http\Controllers\Dashboard;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\ArticleCategory;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
private $rules = [
'category_id' => ['required', 'exists:article_categories,id'],
'title' => ['required', 'string', 'max:255'],
'short_description' => ['required', 'string', 'max:255'],
'image' => ['mimes: jpeg, jpg, png, gif', 'max:2048'],
'content' => ['required', 'string']
];
private $messages = [
'category_id.required' => 'Please pick a category for the article',
'title.required' => 'Please provide a title for the article',
'short_description.required' => 'The article needs a short description',
'content.required' => 'Please add content'
];
public function categories() {
return ArticleCategory::all();
}
public function index() {
$articles = Article::paginate(10);
return view('dashboard/articles',
['articles' => $articles]
);
}
public function create() {
// Load the view and populate the form with categories
return view('dashboard/add-article',
['categories' => $this->categories()]
);
}
public function save(Request $request) {
// Validate form (with custom messages)
$validator = Validator::make($request->all(), $this->rules, $this->messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors());
}
$fields = $validator->validated();
// Upload article image
$current_user = Auth::user();
if (isset($request->image)) {
$imageName = md5(time()) . $current_user->id . '.' . $request->image->extension();
$request->image->move(public_path('images/articles'), $imageName);
}
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'content' => $fields['content'],
'image' => $fields['image'],
'featured' => $fields['featured']
];
// Insert data in the 'articles' table
$query = Article::create($form_data);
if ($query) {
return redirect()->route('dashboard.articles')->with('success', 'Article added');
} else {
return redirect()->back()->with('error', 'Adding article failed');
}
}
}
The form:
<form method="POST" action="{{ route('dashboard.articles.add') }}">
#csrf
<div class="row mb-2">
<label for="title" class="col-md-12">{{ __('Title') }}</label>
<div class="col-md-12 #error('title') has-error #enderror">
<input id="title" type="text" placeholder="Title" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="short_description" class="col-md-12">{{ __('Short description') }}</label>
<div class="col-md-12 #error('short_description') has-error #enderror">
<input id="short_description" type="text" placeholder="Short description" class="form-control #error('short_description') is-invalid #enderror" name="short_description" value="{{ old('short_description') }}" autocomplete="short_description" autofocus>
#error('short_description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="category" class="col-md-12">{{ __('Category') }}</label>
<div class="col-md-12 #error('category_id') has-error #enderror">
<select name="category_id" id="category" class="form-control #error('category_id') is-invalid #enderror">
<option value="0">Pick a category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
#error('category_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<div class="col-md-12 d-flex align-items-center switch-toggle">
<p class="mb-0 me-3">Featured article?</p>
<input class="mt-1" type="checkbox" name="featured" id="featured">
<label class="px-1" for="featured">{{ __('Toggle') }}</label>
</div>
</div>
<div class="row mb-2">
<label for="image" class="col-md-12">{{ __('Article image') }}</label>
<div class="col-md-12 #error('image') has-error #enderror">
<input type="file" name="image" id="file" class="file-upload-btn">
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="content" class="col-md-12">{{ __('Content') }}</label>
<div class="col-md-12 #error('content') has-error #enderror">
<textarea name="content" id="content" class="form-control #error('content') is-invalid #enderror" placeholder="Content" cols="30" rows="6">{{ old('content') }}</textarea>
#error('content')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-0">
<div class="col-md-12">
<button type="submit" class="w-100 btn btn-primary">
{{ __('Save') }}
</button>
</div>
</div>
</form>
The routes:
// Article routes
Route::group(['prefix' => 'articles'], function() {
Route::get('/', [ArticleController::class, 'index'])->name('dashboard.articles');
Route::get('/new', [ArticleController::class, 'create'])->name('dashboard.articles.new');
Route::post('/add', [ArticleController::class, 'save'])->name('dashboard.articles.add');
Route::get('/delete/{id}', [ArticleController::class, 'delete'])->name('dashboard.articles.delete');
});
The problem:
I was expecting this syntax for keeping the values of valid fields in an invalid form, should work: value="{{ old('title') }}". But, fo a reason I have been enable to spot, it does not. The form is reset entirely.
What is my mistake?

You're redirecting back to the previous page without telling Laravel to pass the old inputs. Use the method withInput() with the route return.
Change
return redirect()->back()->withErrors($validator->errors());
with
return redirect()->back()->withErrors($validator->errors())->withInput();

You can use this method instead, and then the return with inputs will happen automatically
$fields = $this->validate($request->all(), $this->rules, $this->messages);
// if ($validator->fails()) {
// return redirect()->back()->withErrors($validator->errors());
// }

Related

What makes the image type validation in this Laravel application fail?

I am making a blogging application with Laravel 8 and Bootstrap 5.
I run into a problem with validating the image field of the "Add new article" form.
In the controller, I have:
namespace App\Http\Controllers\Dashboard;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\ArticleCategory;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
private $rules = [
'category_id' => ['required', 'exists:article_categories,id'],
'title' => ['required', 'string', 'max:255'],
'short_description' => ['required', 'string', 'max:255'],
'image' => ['mimes: jpeg, jpg, png, gif', 'max:2048'],
'content' => ['required', 'string']
];
private $messages = [
'category_id.required' => 'Please pick a category for the article',
'title.required' => 'Please provide a title for the article',
'short_description.required' => 'The article needs a short description',
'content.required' => 'Please add content'
];
public function categories() {
return ArticleCategory::all();
}
public function index() {
$articles = Article::paginate(10);
return view('dashboard/articles',
['articles' => $articles]
);
}
public function create() {
// Load the view and populate the form with categories
return view('dashboard/add-article',
['categories' => $this->categories()]
);
}
public function save(Request $request) {
// Validate form (with custom messages)
$validator = Validator::make($request->all(), $this->rules, $this->messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors())->withInput();
}
$fields = $validator->validated();
// Upload article image
$current_user = Auth::user();
if (isset($request->image)) {
$imageName = md5(time()) . $current_user->id . '.' . $request->image->extension();
$request->image->move(public_path('images/articles'), $imageName);
}
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'content' => $fields['content'],
'image' => $fields['image'],
'featured' => $fields['featured']
];
// Insert data in the 'articles' table
$query = Article::create($form_data);
if ($query) {
return redirect()->route('dashboard.articles')->with('success', 'Article added');
} else {
return redirect()->back()->with('error', 'Adding article failed');
}
}
}
The form:
<form method="POST" action="{{ route('dashboard.articles.add') }}">
#csrf
<div class="row mb-2">
<label for="title" class="col-md-12">{{ __('Title') }}</label>
<div class="col-md-12 #error('title') has-error #enderror">
<input id="title" type="text" placeholder="Title" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="short_description" class="col-md-12">{{ __('Short description') }}</label>
<div class="col-md-12 #error('short_description') has-error #enderror">
<input id="short_description" type="text" placeholder="Short description" class="form-control #error('short_description') is-invalid #enderror" name="short_description" value="{{ old('short_description') }}" autocomplete="short_description" autofocus>
#error('short_description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="category" class="col-md-12">{{ __('Category') }}</label>
<div class="col-md-12 #error('category_id') has-error #enderror">
<select name="category_id" id="category" class="form-control #error('category_id') is-invalid #enderror">
<option value="0">Pick a category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
#error('category_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<div class="col-md-12 d-flex align-items-center switch-toggle">
<p class="mb-0 me-3">Featured article?</p>
<input class="mt-1" type="checkbox" name="featured" id="featured">
<label class="px-1" for="featured">{{ __('Toggle') }}</label>
</div>
</div>
<div class="row mb-2">
<label for="image" class="col-md-12">{{ __('Article image') }}</label>
<div class="col-md-12 #error('image') has-error #enderror">
<input type="file" name="image" id="file" class="file-upload-btn">
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="content" class="col-md-12">{{ __('Content') }}</label>
<div class="col-md-12 #error('content') has-error #enderror">
<textarea name="content" id="content" class="form-control #error('content') is-invalid #enderror" placeholder="Content" cols="30" rows="6">{{ old('content') }}</textarea>
#error('content')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-0">
<div class="col-md-12">
<button type="submit" class="w-100 btn btn-primary">
{{ __('Save') }}
</button>
</div>
</div>
</form>
The routes:
// Article routes
Route::group(['prefix' => 'articles'], function() {
Route::get('/', [ArticleController::class, 'index'])->name('dashboard.articles');
Route::get('/new', [ArticleController::class, 'create'])->name('dashboard.articles.new');
Route::post('/add', [ArticleController::class, 'save'])->name('dashboard.articles.add');
Route::get('/delete/{id}', [ArticleController::class, 'delete'])->name('dashboard.articles.delete');
});
The problem:
Even if I upload a valid image (a PNG file) I get this validation error:
The image must be a file of type: jpeg, jpg, png, gif.
What is my mistake?
First of all, when you are dealing with an image/file you must have enctype=" multipart/form-data " in your form. Otherwise, you cannot submit the form. and validation will not be working.
Next validation rule for image or file will be like this :
'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'

Why don't I get any validation errors in this invalid Laravel 8 form?

I am making a blogging application with Laravel 8 and Bootstrap 5.
I run into a problem trying to validate my Add article form. It fails to validate, meaning that no error messages appear, even if the required form data is not filled.
In the ArticleController controller, I have:
namespace App\Http\Controllers\Dashboard;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\ArticleCategory;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
private $rules = [
'category_id' => 'required|exists:categories,id',
'title' => 'required|string',
'short_description' => 'required|string',
'content' => 'required|longText'
];
private $messages = [
'category_id.required' => 'Please pick a category for the article',
'title.required' => 'Please provide a title for the article',
'short_description.required' => 'The article needs a short description',
'content.required' => 'Please add content'
];
public function categories() {
return ArticleCategory::all();
}
public function add(Request $request) {
// Pass the categories to the articles form
return view('dashboard/add-article',
['categories' => $this->categories()]
);
// Validate form (with custom messages)
$validator = Validator::make($request->all(), $this->rules, $this->messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors());
}
$fields = $validator->validated();
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'content' => $fields['content'],
'image' => $fields['image'],
'featured' => $fields['featured']
];
// Insert data in the 'articles' table
$query = Article::create($form_data);
if ($query) {
return redirect()->route('dashboard.articles')->with('success', 'Article added');
} else {
return redirect()->route('dashboard.articles')->with('error', 'Adding article failed');
}
}
}
The form:
<form method="POST" action="{{ route('dashboard.articles.add') }}">
#csrf
<div class="row mb-2">
<label for="title" class="col-md-12">{{ __('Title') }}</label>
<div class="col-md-12 #error('title') has-error #enderror">
<input id="title" type="text" placeholder="Title" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="short_description" class="col-md-12">{{ __('Short description') }}</label>
<div class="col-md-12 #error('short_description') has-error #enderror">
<input id="short_description" type="text" placeholder="Short description" class="form-control #error('short_description') is-invalid #enderror" name="short_description" value="{{ old('short_description') }}" autocomplete="short_description" autofocus>
#error('short_description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="category" class="col-md-12">{{ __('Category') }}</label>
<div class="col-md-12 #error('category_id') has-error #enderror">
<select name="category_id" id="category" class="form-control #error('category_id') is-invalid #enderror">
<option value="0">Pick a category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
#error('category_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<div class="col-md-12 d-flex align-items-center switch-toggle">
<p class="mb-0 me-3">Featured article?</p>
<input class="mt-1" type="checkbox" name="featured" id="featured">
<label class="px-1" for="featured">{{ __('Toggle') }}</label>
</div>
</div>
<div class="row mb-2">
<label for="image" class="col-md-12">{{ __('Article image') }}</label>
<div class="col-md-12 #error('image') has-error #enderror">
<input type="file" name="image" id="file" value="{{ old('image') }}" class="file-upload-btn">
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="content" class="col-md-12">{{ __('Content') }}</label>
<div class="col-md-12 #error('content') has-error #enderror">
<textarea name="content" id="content" class="form-control #error('content') is-invalid #enderror" placeholder="Content" cols="30" rows="6">{{ old('content') }}</textarea>
#error('content')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-0">
<div class="col-md-12">
<button type="submit" class="w-100 btn btn-primary">
{{ __('Save') }}
</button>
</div>
</div>
</form>
The routes:
// Article routes
Route::group(['prefix' => 'articles'], function() {
Route::get('/', [ArticleController::class, 'index'])->name('dashboard.articles');
Route::match(['get', 'post'],'/add', [ArticleController::class, 'add'])->name('dashboard.articles.add');
Route::get('/delete/{id}', [ArticleController::class, 'delete'])->name('dashboard.articles.delete');
});
Why does my form fail to validate?
Your public function add() starts with a return statement.
The rest of the code is irrelevant since you return from the function at this point.

Remove uploaded profile picture and reset to default image in laravel issue

I have a user update form with a user photo. Currently I'm saving my user photo (file name) in my user table's propic column.
The Problem
I'm trying to add a remove photo button when a user wants to remove the uploaded image. Once the user click the remove photo button user's propic column value need to be reset to default value (user-photo.png). And I need to display that remove photo button only for the users who have updated their profile photos. Users with default profile photo doesn't need the option.
What I have done so far
This is my form, in user blade
<form action="{{ route('settings.update',$user->id) }}" method="POST" enctype="multipart/form-data">
<div class="row mt-5">
<div class="col-sm-3">
<img src="/propics/{{$user->propic}}" alt="Profile Pic" id="profile_pic_display" class="mb-3">
<input type="file" name="propic" class="form-control">
#error('propic')
<span class="help-block" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-sm-9">
<!-- <form action="{{ route('settings.update',$user->id) }}" method="POST"> -->
#csrf
#method('PUT')
<div class="row">
<div class="col-md-6">
<div class="form-group field-user-firstname required">
<label class="control-label"
for="user-firstname">{{ __('sentence.First Name') }}</label>
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror"
name="name" value="{{$user->name}}" autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group field-user-lastname required">
<label class="control-label" for="user-lastname">{{ __('sentence.Last Name') }}</label>
<input id="last_name" type="text"
class="form-control #error('name') is-invalid #enderror" name="last_name"
value="{{$user->last_name}}" autocomplete="last_name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group field-user-mobile required">
<label class="control-label" for="user-mobile">{{ __('sentence.Mobile') }}</label><br/>
<input id="mobile_1" type="tel"
class="form-control #error('mobile') is-invalid #enderror" name="mobile"
value="{{$user->mobile}}" style="min-width:398px;" autocomplete="mobile"
autofocus>
#error('mobile')
<span class="help-block" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group field-user-email required">
<label class="control-label" for="user-email">{{ __('sentence.Email') }}</label>
<input id="email_" type="email"
class="form-control #error('email') is-invalid #enderror" name="email"
value="{{$user->email}}" autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
</div>
<div class="row">
<div class="col-sm">
<div class="form-group pull-right">
<button type="submit"
class="btn btn-default">{{ __('sentence.Cancel') }}</button>
<button type="submit"
class="btn btn-default subscribe px-5">{{ __('sentence.Update') }}</button>
</div>
</div>
</div>
</div>
</form>
And following is my controller (Only the update function is included)
public function update(Request $request, User $setting)
{
$changedAttributes = array_diff($request->all(), $setting->getAttributes());
$validationRules = array_intersect_key([
'name' => ['required', 'alpha','min:2', 'max:255'],
'last_name' => ['required', 'alpha','min:5', 'max:255'],
'mobile' => ['required', 'numeric','min:9','regex:/\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$/'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$setting->id.''],
'propic' => ['required','image','mimes:jpeg,png,jpg,gif,svg','max:2048'],
], $changedAttributes);
if($request->hasFile('propic'))
{
$this->validate($request, [
'name' => ['required', 'alpha','min:2', 'max:255'],
'last_name' => ['required', 'alpha','min:5', 'max:255'],
'mobile' => ['required', 'numeric','min:9','regex:/\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|3[70]|7|1)\d{1,14}$/'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$setting->id.''],
'propic' => ['required','image','mimes:jpeg,png,jpg,gif,svg','max:2048'],
],$request->all());
$imageName = time().'.'.$request->propic->extension();
$request->propic->move(public_path('propics'), $imageName);
$setting->propic=$imageName;
$setting->name=$request->input('name');
$setting->last_name=$request->input('last_name');
$setting->mobile=$request->input('mobile');
$setting->email=$request->input('email');
$setting->update();
return Redirect::back()->with('success',__('sentence.User updated successfully'));
}
$this->validate($request, $validationRules);
$setting->update($changedAttributes);
return Redirect::back()->with('success',__('sentence.User updated successfully'));
}
}
First you need to check in your view if user profile photo is not "user-photo.png" and if true insert a button to reset photo:
#if($user->propic != 'user-photo.png')
<button type="submit" name="resetphoto" class="btn btn-warning">Reset Profile Pic</button>
#endif
Then in your controller at the beginning of update() method check if the user has clicked on "Reset Profile Pic" button, and then if is true set the column back to default value, then save the model
if ($request->has('resetphoto')){
$setting->propic = 'user-photo.png';
$setting->update();
return Redirect::back()->with('success',__('sentence.User profile pic reset successfully'));
}
PS: Im assuming your "$setting" is the User model

Image source not readable Laravel 5.8

When I want to add a picture to a post I have this error:
create.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Créer une annoce</div>
<div class="card-body">
<form method="POST" action="{{ route('posts.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">Titre</label>
<div class="col-md-6">
<input id="title" type="text" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label for="descriptionpost">Description</label>
<div class="col-md-9">
<textarea id="descriptionpost" type="text" class="form-control #error('descriptionpost') is-invalid #enderror" name="descriptionpost" value="{{ old('descriptionpost') }}" autocomplete="descriptionpost" autofocus></textarea>
#error('descriptionpost')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<div class="custom-file">
<input type="file" name="image" class="custom-file-input #error('image') is-invalid #enderror" id="validatedCustomFile" >
<label class="custom-file-label" for="validatedCustomFile">Choisir une image</label>
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label for="price">Prix</label>
s
<div class="col-md-6">
<input id="price" type="text" class="form-control #error('price') is-invalid #enderror" name="price" value="{{ old('price') }}" autocomplete="price" autofocus>
#error('price')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Créer
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
PostController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Poststore;
use App\Post;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\DB;
class PostController extends Controller
{
public function postsabonnés()
{
auth()->user()->following->pluck('user_id');
$posts = Post::whereIn('user_id', $users)->latest()->get();
return view('welcome', compact('posts'));
}
public function index()
{
$posts = DB::table('posts')->orderBy('created_at', 'DESC')->paginate(1000);
return view('welcome',['posts'=> $posts]);
}
public function create()
{
return view('posts.create');
}
public function store()
{
$data = request()->validate([
'title' => ['required', 'string'],
'image' => ['required', 'image'],
'price' => ['required', 'integer'],
'descriptionpost' => ['required', 'string']
]);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("/storage/{$imagePath}"))->fit(1200, 1200);
$image->save();
auth()->user()->posts()->create([
'title' => $data['title'],
'descriptionpost' => $data['descriptionpost'],
'price' => $data['price'],
'image' => $imagePath
]);
return redirect()->route('profile.show', ['user' => auth()->user() ]);
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
public function search(Request $request)
{
$words = $request->words;
$posts = DB::table('posts')->where('title', 'LIKE', '%$words%')->orWhere('descriptionpost', 'LIKE', '%$words%')->orderBy('created_at', 'DESC')->get();
return response()->json(['success' => true, 'posts' => $posts]);
}
}
ProfileController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class ProfileController extends Controller
{
public function show(User $user)
{
$follows = (auth()->user()) ? auth()->user()->following->contains($user->profile->id) : false;
return view('profile.show', compact('user', 'follows'));
}
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profile.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'description' => 'required',
'image' => 'sometimes|image|max:3000'
]);
if (request('image')) {
$imagePath = request('image')->store('avatars', 'public');
$image = Image::make(public_path("/storage/{$imagePath}"))->fit(800, 800);
$image->save();
auth()->user()->profile->update(array_merge($data,
['image' => $imagePath]
));
} else {
auth()->user()->profile->update($data);
}
auth()->user()->profile->update($data);
return redirect()->route('profile.show', ['user' => $user]);
}
}
edit.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Modifier profile</div>
<div class="card-body">
<form method="POST" action="{{ route('profile.update', ['user' => $user]) }}" enctype="multipart/form-data">
#csrf
#method('PATCH')
<div class="form-group">
<label for="description">Description</label>
<div class="col-md-6">
<textarea id="description" type="text" class="form-control #error('description') is-invalid #enderror" name="description" autocomplete="description" autofocus>{{ old('description') ?? $user->profile->description }}</textarea>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<div class="custom-file">
<input type="file" name="image" class="custom-file-input #error('image') is-invalid #enderror" id="validatedCustomFile" >
<label class="custom-file-label" for="validatedCustomFile">Choisir une image</label>
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Modifier profile
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
I have this error when I want to add pictures in the post but when I try add picture in profile or want to edit a picture, the pictures load but its white.
I've read that I need to add enctype="multipart/form-data" but when I add this it still did not work, what i can do to resolve this?

How to make the login and register work with the code below

I am working on a laravel webshop and I have some problems with the Authentication, login and register. First of all, if I try to login with my email and password, who are already registered in the database, it will say "These credentials do not match our records." So it doesn't recognize my data. If I will navigate to the page it will actually recognize my email.
If I try to register it doesn't do anything.
I already have tried to do php artisan make:auth again but that won't change anything. Also, I have checked my models as following: I did some dd(); in the validator and in the create(){} but the dd(); will not launch in the create function so I suppose the create function isn't triggered.
//Login controller:
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
//Register controller:
protected function validator(array $data)
{
return Validator::make($data, [
'gebruikersnaam' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255',
'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'voornaam' => ['required', 'string', 'max:255'],
'achternaam' => ['required', 'string', 'max:255'],
'telefoonnummer' => ['required', 'string','min:9' ,'max:255'],
'klant_afbeelding' => ['required', 'string', 'max:255'],
]);
}
1. /**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'gebruikersnaam' => $data['gebruikersnaam'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'voornaam' => $data['voornaam'],
'achternaam' => $data['achternaam'],
'telefoonnummer' => $data['telefoonnummer'],
'klant_afbeelding' => $data['klant_afbeelding'],
]);
}
//User class:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'gebruikersnaam', 'email', 'password','voornaam','achternaam',
'telefoonnummer','klant_afbeelding'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
//My routes:
<?php
Route::get('/', function () {
return view('home');
});
// Route::get('/', function (Request $request) {
// $data = $request->validate([
// 'message' => 'required|max:255',
// 'rating' => 'required|url|max:255',
// ]);
//
// return view('home');
// });
Route::get('/Profiel', 'ProfielController#Profiel');
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/home', 'HomeController#Home' );
// route voor de review submit
Route::resource('reviewSubmit', 'ReviewController');
Route::get('/Profiel', 'ProfielController#Profiel');
Route::post('/profielupdate', 'ProfielController#update');
Route::post('/niewsbriefsubscribe', 'HomeController#subscribe');
Auth::routes();
Route::get('login', 'Auth\LoginController#showLoginForm')->name('login');
Route::get('register', 'Auth\RegisterController#showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController#register');
Route::get('/home', 'HomeController#index')->name('home');
//Login view
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="current-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
#if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
#endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
//Register view
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<label for="gebruikersnaam" class="col-md-4 col-form-label text-md-right">{{ __('Gebruikersnaam') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
#error('gebruikersnaam')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="voornaam" class="col-md-4 col-form-label text-md-right">{{ __('Voornaam') }}</label>
<div class="col-md-6">
<input id="voornaam" type="text" class="form-control #error('voornaam') is-invalid #enderror" name="voornaam" value="{{ old('voornaam') }}" required autocomplete="voornaam">
#error('voornaam')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="achternaam" class="col-md-4 col-form-label text-md-right">{{ __('Achternaam') }}</label>
<div class="col-md-6">
<input id="achternaam" type="text" class="form-control #error('achternaam') is-invalid #enderror" name="achternaam" value="{{ old('achternaam') }}" required autocomplete="achternaam">
#error('achternaam')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="telefoonnummer" class="col-md-4 col-form-label text-md-right">{{ __('Telefoonnummer') }}</label>
<div class="col-md-6">
<input id="telefoonnummer" type="text" class="form-control #error('telefoonnummer') is-invalid #enderror" name="telefoonnummer" value="{{ old('telefoonnummer') }}" required autocomplete="telefoonnummer">
#error('telefoonnummer')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="wachtwoord" class="col-md-4 col-form-label text-md-right">{{ __('Wachtwoord') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Registreer') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
The expected thing to happen is that i can register and actually save in the database and logging in.
The output at the moment is the opposite.

Categories