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?
Related
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'
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());
// }
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.
I've got problem with my laravel 8..
I Created Controller for edit profile, and when i access the page, it return view blank page or white screen with no error..
Here's my Controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function edit(Request $request)
{
return view('profile.edit', [
'user' => $request->user()
]);
}
}
Here's my route or web.php (Route for edit profile is at last)
Route::group(['prefix' => 'dashboard', 'middleware' => ['auth']], function () {
Route::get('/', [App\Http\Controllers\DashboardController::class, 'index'])->name('dashboard.index');
Route::get('/categories/select', [App\Http\Controllers\CategoryController::class, 'select'])->name('categories.select');
Route::resource('/categories', App\Http\Controllers\CategoryController::class);
Route::get('/tags/select', [App\Http\Controllers\TagController::class, 'select'])->name('tags.select');
Route::resource('/tags', App\Http\Controllers\TagController::class);
Route::resource('/posts', App\Http\Controllers\PostController::class);
Route::resource('/banners', App\Http\Controllers\BannerController::class);
Route::resource('/clients', App\Http\Controllers\ClientController::class);
Route::resource('/gallerys', App\Http\Controllers\GalleryController::class);
Route::resource('/products', App\Http\Controllers\ProductController::class);
Route::resource('/services', App\Http\Controllers\ServiceController::class);
Route::resource('/teams', App\Http\Controllers\TeamController::class);
Route::resource('/testimonies', App\Http\Controllers\TestimonyController::class);
Route::resource('/metas', App\Http\Controllers\MetaController::class);
Route::resource('/keywords', App\Http\Controllers\KeywordController::class);
Route::group(['prefix' => 'filemanager'], function () {
Route::get('/index', [App\Http\Controllers\FileManagerController::class, 'index'])->name('filemanager.index');
\UniSharp\LaravelFilemanager\Lfm::routes();
});
Route::group(['middleware' => 'auth'], function () {
Route::get('/profile', [App\Http\Controllers\ProfileController::class, 'edit'])->name('profile.edit');
});
});
And here's my view
#extends('layouts.dashboard')
#section('title')
Edit Profile
#endsection
#section('breadcrumbs')
{{ Breadcrumbs::render('edit_profile') }}
#endsection
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
Update Profile
</div>
<div class="card-body">
<form method="POST" action="{{ route('profile.update') }}">
#method('patch')
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name', $user->name) }}" autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Username') }}</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control #error('username') is-invalid #enderror" name="username" value="{{ old('username', $user->username) }}" autocomplete="username" autofocus>
#error('username')
<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', $user->email) }}" autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Update Profile
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
I still work this at localserver, anyone know where is the problem?
I think there is issue in your controller code. Please try below code. I have changed user fetch syntax.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function edit(Request $request)
{
return view('profile.edit', [
'user' => \Auth::user()
]);
}
}
Please help me to add upload profile picture on laravel 5.2 registration form.
I use Auth for my registration and login, but made some modification there.
this is my register.blade.php view
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-primary">
<div class="panel-heading">Pendaftaran Akun Baru</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
{!! csrf_field() !!}
<!-- start of nip -->
<div class="form-group{{ $errors->has('nip') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">Nomor Induk Pegawai</label>
<div class="col-md-6">
<input type="text" class="form-control" name="nip" value="{{ old('nip') }}">
#if ($errors->has('nip'))
<span class="help-block">
<strong>{{ $errors->first('nip') }}</strong>
</span>
#endif
</div>
</div>
<!-- end of nip -->
<!-- start of nama -->
<div class="form-group{{ $errors->has('nama') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">Nama</label>
<div class="col-md-6">
<input type="text" class="form-control" name="nama" value="{{ old('nama') }}">
#if ($errors->has('nama'))
<span class="help-block">
<strong>{{ $errors->first('nama') }}</strong>
</span>
#endif
</div>
</div>
<!-- end of nama -->
<!-- start of email -->
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">Alamat E-mail</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<!-- end of email -->
<!-- start of password -->
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<!-- end of password -->
<!-- start of konfirmasi -->
<div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">Konfirmasi Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
#if ($errors->has('password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('password_confirmation') }}</strong>
</span>
#endif
</div>
</div>
<!-- end of konfirmasi -->
<!-- start of foto -->
<div class="form-group{{ $errors->has('avatar') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">F o t o</label>
<div class="col-md-6">
<div id="kv-avatar-errors" class="center-block" style="width:800px;display:none">
</div>
<div class="kv-avatar" style="width:200px">
<input id="avatar" name="avatar" type="file" class="file-loading">
</div>
</div>
</div>
<!-- end of foto -->
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-user"></i>Daftar
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
this is my eloquent app\Daftarpegawai.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Daftarpegawai extends Authenticatable {
protected $fillable = [
'nip', 'nama', 'email', 'password', 'foto',
];
protected $hidden = [
'password', 'status', 'remember_token',
];
}
and this is my AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Daftarpegawai;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'nip' => 'required|max:20',
'nama' => 'required|max:255',
'avatar' => 'mimes:jpg',
'email' => 'required|email|max:255|unique:daftarpegawais',
'password' => 'required|confirmed|min:6',
]);
}
protected function create(array $data)
{
return Daftarpegawai::create([
'nip' => $data['nip'],
'nama' => $data['nama'],
'foto' => $data['avatar'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
I am new in learning laravel
i've tried some methods that i found here with the same problem, but nothing works for me
if($data->hasFile('avatar'))
{
$destinationPath = 'path/to/upload/the/file'
$imgName = 'yourimagename.jpg'
$data->avatar->move($destinationPath, $imgName)
$path = $destinationPath . '/' . $imgName
}
DaftarPegawai::create([
'foto' => $path
])
You can use the below code as your POST request code for uploading avatar to user profile
public function update_avatar(Request $request){
$request->validate([
'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user = Auth::user();
$avatarName = $user->id.'_avatar'.time().'.'.request()->avatar-
>getClientOriginalExtension();
$request->avatar->storeAs('avatars',$avatarName);
$user->avatar = $avatarName;
$user->save();
return back()
->with('success','You have successfully upload image.');
}
Source : Detailed tutorial https://www.5balloons.info/upload-profile-picture-avatar-laravel-5-authentication/
If someone is still facing problem, try using the following codes! Hope it will work...
$avatar = $data['avatar'];
$extension = $avatar->getClientOriginalExtension();
$avatar_name = time() . '.' . $extension;
$avatar->move(base_path('public/images/avatars/'), $avatar_name);
return User::create([
'avatar' => $avatar_name,
]);