Basic Information
I' developing a simple Web Application using Laravel6.0.
And I made image post form at my create2.blade.php (blade file) file.
But my form seems to be having a routing Problem.
Problem
My Codes
routes/web.php
<?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('login');
Route::group(['middleweare' => 'auth'], function () {
Route::get('/', 'StoriesController#index');
Route::post('/', 'StoriesController#index');
Route::post('/stories/create', 'StoriesController#store');
Route::post('/stories/create', 'StoriesController#upload');
Route::get('/stories/create', 'StoriesController#add');
Route::post('/stories/create', 'StoriesController#add');
});
Route::group(['middleweare' => 'auth','name'=>'profile'], function () {
Route::get('/profile/edit', 'ProfileController#edit');
Route::get('/profile/create', 'ProfileController#add');
Route::post('/profile/create', 'ProfileController#add');
Route::post('/profile/create', 'ProfileController#store');
Route::post('/profile/create', 'ProfileController#upload');
});
Route::get('/home', 'HomeController#index')->name('home');
Auth::routes();
app/Http/Controllers/StoriesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Story;
use Auth;
use App\Posts;
use App\History;
use App\Attachment;
use Carbon\Carbon;
use Storage;
class StoriesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
$images = Attachment::all();
return view('stories.index2', compact('images'));
}
public function add()
{
return view('stories.create2');
}
public function store(Request $request)
{
$d = new \DateTime();
$d->setTimeZone(new \DateTimeZone('Asia/Tokyo'));
$dir = $d->format('Y/m');
$path = sprintf('public/images/%s', $dir);
$data = $request->except('_token');
foreach ($data['images'] as $k => $v) {
$filename = '';
$attachments = Attachment::take(1)->orderBy('id', 'desc')->get();
foreach ($attachments as $attachment) {
$filename = $attachment->id + 1 . '_' . $v->getClientOriginalName();
}
unset($attachment);
if ($filename == false) {
$filename = 1 . '_' . $v->getClientOriginalName();
}
$v->storeAs($path, $filename);
$attachment_data = [
'path' => sprintf('images/%s/', $dir),
'name' => $filename
];
$a = new Attachment();
$a->fill($attachment_data)->save();
}
unset($k, $v);
return redirect('/');
}
public function upload(Request $request)
{
$this->validate($request, [
'file' => [
'required',
'file',
'image',
'mimes:jpeg,png',
]
]);
if ($request->file('file')->isValid([])) {
$path = $request->file->store('public');
return view('stories.index2')->with('filename', basename($path));
} else {
return redirect('/')
->back()
->withInput()
->withErrors();
}
}
}
resources/views/stories/create2.blade.php
#extends('layouts.front2')
#section('title','StoryCreate')
#section('content')
<link href="{{ asset('/css/main22.css' )}}" rel="stylesheet">
<div class="poststory">
<h1>Post Story</h1>
</div>
#if ($errors->any())
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<form action="{{ url('/') }}" method="POST" enctype="multipart/form-data">
<div class="form">
<label for="photo" class="file">Choose Image or Video</label>
<div class="post">
<input type="file" class="here" name="images[]">
</div>
</div>
<br>
</div>
{{ csrf_field() }}
<div class="post">
<div class="btn postbtn">
<input type="submit" value="post" />
</div>
</div>
</form>
#endsection
resources/views/stories/index2.blade.php
#extends('layouts.front2')
#section('title','mainpage')
#section('content')
<div class="profile">
<div class="profileimg">
#foreach ($images as $image)
<img src="/storage/{{ $image->path . $image->name }}" style="height: 210px; width: 210px; border-radius: 50%;">
#endforeach
</div>
<div class="name">
#guest
<a class="nav-link2" href="{{ route('register')}}">{{ __('Create Accout!')}}</a>
#else
<a id="navbarDropdown" class="nav-link2" href="#" role="button">
{{Auth::user()->name}}<span class="caret"></span></a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</div>
#endguest
<div class="aboutme">
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
</div>
</div>
<div class="new">
<div class="newtitle">
<h1>New</h1>
</div>
<div class="container1">
#foreach ($images as $image)
<img src="/storage/{{ $image->path . $image->name }}" class="images" style="height: 150px; width: 150px; border-radius: 50%;">
#endforeach
<div class="more">
more...
</div>
</div>
</div>
<div class="stories">
<div class="titlestories">
<h1>Stories</h1>
</div>
<div class="container2">
<div class="titleclose">
<h2>#CloseFriends</h2>
</div>
#foreach ($images as $image)
<img src="/storage/{{ $image->path . $image->name }}" class="images" style="height: 150px; width: 150px; border-radius: 50%;">
#endforeach
<div class="titlefollow">
<h2>#Follows</h2>
</div>
</div>
</div>
{{ csrf_field() }}
#endsection
What I tried.
I cleared the caches using this command,
$php artisan route: clear
and I' made a new cache using
$composer dump-autoload
$php artisan clear-compiled
$php artisan optimize
$php artisan config:cache
and I update my composer using this command
$composer update
but nothing has changed.
Sorry for my terrible English.
Waiting your comments and Answers!
You are submitting your from to {{ url('/') }} using POST method that means it is submitting as a POST to / route and your / route is defined by GET method in your web.php that is why you are getting this error
<form action="{{ url('/') }}" method="POST" enctype="multipart/form-data">
Route::get('/', 'StoriesController#index');
Related
After setting up my profile page my uploaded images initially produced an image on my local host. However lately it shows up as an icon instead https://i.stack.imgur.com/pp0Yt.png
I should note I am using php 7.3.19
profiles/index.blade.php
<div class="container">
<div class="row">
<div class="col-3 p-5">
<img src="{{ $user->profile->profileImage() }}" class="rounded-circle w-100">
</div>
<div class="col-9 pt-5">
<div class="d-flex justify-content-between align-items-baseline">
<div class="d-flex align-items-center pb-3">
<div class="h4">{{ $user->username }}</div>
<follow-button user-id="{{ $user->id }}" follows="{{ $follows }}"></follow-button>
</div>
#can('update', $user->profile)
Add New Post
#endcan
</div>
#can('update', $user->profile)
Edit Profile
#endcan
<div class="d-flex">
<div class="pr-5"><strong>{{ $postCount }}</strong> posts</div>
<div class="pr-5"><strong>{{ $followersCount }}</strong> followers</div>
<div class="pr-5"><strong>{{ $followingCount }}</strong> following</div>
</div>
<div class="pt-4 font-weight-bold">{{ $user->profile->title }}</div>
<div>{{ $user->profile->description }}</div>
<div>{{ $user->profile->url }}</div>
</div>
</div>
<div class="row pt-5">
#foreach($user->posts as $post)
<div class="col-4 pb-4">
<a href="/p/{{ $post->id }}">
<img src="/storage/{{ $post->image }}" class="w-100">
</a>
</div>
#endforeach
</div>
</div>
#endsection
Is there an issue in the way I am picking it up from the storage?
I used 'php artisan storage:link'
create.blade.php
<div class="container">
<form action="/p" enctype="multipart/form-data" method="post">
#csrf
<div class="row">
<div class="col-8 offset-2">
<div class="row">
<h1>Add New Image</h1>
</div>
<div class="form-group row">
<label for="caption" class="col-md-4 col-form-label">Post Caption</label>
<input id="caption"
type="text"
class="form-control{{ $errors->has('caption') ? ' is-invalid' : '' }}"
name="caption"
value="{{ old('caption') }}"
autocomplete="caption" autofocus>
#if ($errors->has('caption'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('caption') }}</strong>
</span>
#endif
</div>
<div class="row">
<label for="image" class="col-md-4 col-form-label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#if ($errors->has('image'))
<strong>{{ $errors->first('image') }}</strong>
#endif
</div>
<div class="row pt-4">
<button class="btn btn-primary">Add New Post</button>
</div>
</div>
</div>
</form>
</div>
#endsection
PostsController.php
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$users = auth()->user()->following()->pluck('profiles.user_id');
$posts = Post::whereIn('user_id', $users)->with('user')->latest()->paginate(5);
return view('posts.index', compact('posts'));
}
public function create()
{
return view('posts.create');
}
public function store()
{
$data = request()->validate([
'caption' => 'required',
'image' => ['required', 'image'],
]);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
$image->save();
auth()->user()->posts()->create([
'caption' => $data['caption'],
'image' => $imagePath,
]);
return redirect('/profile/' . auth()->user()->id);
}
public function show(\App\Post $post)
{
return view('posts.show', compact('post'));
}
}
ProfilesController.php
<?php
namespace App\Http\Controllers;
use App\Profile;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Cache;
class ProfilesController extends Controller
{
public function index(User $user)
{
$follows = (auth()->user()) ? auth()->user()->following->contains($user->id) : false;
$postCount = Cache::remember(
'count.posts.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->posts->count();
});
$followersCount = Cache::remember(
'count.followers.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->profile->followers->count();
});
$followingCount = Cache::remember(
'count.following.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->following->count();
});
return view('profiles.index', compact('user', 'follows', 'postCount', 'followersCount', 'followingCount'));
}
//($user = (User::findOrFail($user));)
//('user' => $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([
'title' => 'required',
'description' => 'required',
'url' => 'url',
'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}");
}
public function show($user_id)
{
$user = User::find(1);
$user_profile = Profile::info($user_id)->first();
return view('profiles.show', compact('profile', 'user'));
}
public function profile()
{
return $this->hasOne('Profile');
}
}
Use asset helper function to get the uploaded image URL.
<img src="{{ asset('storage/' . $post->image) }}" class="w-100">
OR
<img src="{{ asset(Storage::url($post->image)) }}" class="w-100">
I am having a little problem here. I am trying to put an image in my User Profile. The image is saved in the database and no errors are shown up, but I never see the default image that I gave to it. It says that it's there but The place for the pic stays empty.
This is what I've got for now:
UserController.php
<?php
namespace app\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
// namespace App\Http\Controllers\Controller;
// use App\Http\Requests\Request;
// use Illuminate\Http\Request;
class UserController extends Controller
{
public function profile()
{
$user = Auth::user();
return view('profile',compact('user',$user));
}
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.');
}
/** Return view to upload file */
public function uploadFile(){
return view('uploadfile');
}
/** Example of File Upload */
public function uploadFilePost(Request $request){
$request->validate([
'fileToUpload' => 'required|file|max:1024',
]);
$request->fileToUpload->store('logos');
return back()
->with('success','You have successfully upload image.');
}
}
profile.blade.pbp
<hidden='Illuminate\Support\Facades\Auth'>
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
<div class="row justify-content-center">
<div class="profile-header-container">
<div class="profile-header-img">
<img class="rounded-circle" width="150" height="150" src="/storage/avatars/{{ $user->avatar }}" />
<!-- badge -->
<div class="rank-label-container">
<span class="label label-default rank-label">{{$user->name}}</span>
</div>
</div>
</div>
</div>
<div class="row justify-content-center">
<form action="/profile" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input type="file" class="form-control-file" name="avatar" id="avatarFile" aria-describedby="fileHelp">
<small id="fileHelp" class="form-text text-muted">Please upload a valid image file. Size of image should not be more than 2MB.</small>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
#endsection
filesystems.php
'default' => env('FILESYSTEM_DRIVER', 'public'),
How can I make the default avatar visible?
Also, do you have any suggestions on how to put a watermark on the photos that will appear each time someone uploads photos?
Thanks in advance!
You can try this. First execute this command
php artisan storage:link
Then
<img class="rounded-circle" width="150" height="150" src="{{url('')}}/storage/avatars/{{ $user->avatar }}"/>
i want to create some CMS project with the laravel, when the user trying to click the categories, the app will show the post that only shows the category that user clicked. When the user click the categories, the app says error Bad Method Call. What should i do? Any help will be appreciated.
Here's the code from web.php
<?php
use App\Http\Controllers\Blog\PostsController;
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('/', 'WelcomeController#index')->name('welcome');
Route::get('blog/posts/{post}', [PostsController::class, 'show'])->name('blog.show');
Route::get('blog/categories/{category}', [PostsController::class, 'category'])->name('blog.category');
Route::get('blog/tags/{tag}', [PostsController::class, 'tag'])->name('blog.tag');
Auth::routes();
Route::middleware(['auth'])->group(function () {
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('categories', 'CategoriesController');
Route::resource('posts','PostsController');
Route::resource('tags','TagsController');
Route::get('trashed-posts','PostsController#trashed')->name('trashed-posts.index');
Route::put('restore-post/{post}', 'PostsController#restore')->name('restore-posts');
});
Route::middleware(['auth', 'admin'])->group(function () {
Route::get('users/profile', 'UserController#edit')->name('users.edit-profile');
Route::put('users/profile', 'UserController#update')->name('users.update-profile');
Route::get('users','UserController#index')->name('users.index');
Route::post('users/{user}/make-admin', 'UserController#makeAdmin')->name('users.make-admin');
});
Here's the code from PostsController.php
<?php
namespace App\Http\Controllers\Blog;
use App\Http\Controllers\Controller;
use App\Post;
use Illuminate\Http\Request;
use App\Tag;
use App\Category;
class PostsController extends Controller
{
public function show(Post $post) {
return view('blog.show')->with('post', $post);
}
public function category(Category $category) {
return view('blog.category')
->with('category', $category)
->with('posts', $category->posts()->simplePaginate())
->with('categories', Category::all())
->with('tags', Tag::all());
}
public function tag(Tag $tag) {
return view('blog.tag')
->with('tag', $tag)
->with('posts', $tag->posts()->simplePaginate(3));
}
}
Here's the code from App\Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name'];
public function post() {
return $this->hasMany(Post::class);
}
}
Here's the code from category.blade.php
#extends('layouts.blog')
#section('title')
Category {{ $category->name }}
#endsection
#section('header')
<header class="header text-center text-white" style="background-image: linear-gradient(-225deg, #5D9FFF 0%, #B8DCFF 48%, #6BBBFF 100%);">
<div class="container">
<div class="row">
<div class="col-md-8 mx-auto">
<h1>{{ $category->name }}</h1>
<p class="lead-2 opacity-90 mt-6">Read and get updated on how we progress</p>
</div>
</div>
</div>
</header><!-- /.header -->
#endsection
#section('content')
<main class="main-content">
<div class="section bg-gray">
<div class="container">
<div class="row">
<div class="col-md-8 col-xl-9">
<div class="row gap-y">
#forelse($posts as $post)
<div class="col-md-6">
<div class="card border hover-shadow-6 mb-6 d-block">
<img class="card-img-top" src="{{ asset($post->image) }}" alt="Card image cap">
<div class="p-6 text-center">
<p>
<a class="small-5 text-lighter text-uppercase ls-2 fw-400" href="#"></a>
{{ $post->category->name }}
</p>
<h5 class="mb-0">
<a class="text-dark" href="{{ route('blog.show',$post->id) }}">
{{ $post->title }}
</a>
</h5>
</div>
</div>
</div>
#empty
<p class="text-center">
No Results found for query <strong>{{ request()->query('search') }} </strong>
</p>
#endforelse
</div>
{{-- <nav class="flexbox mt-30">
<a class="btn btn-white disabled"><i class="ti-arrow-left fs-9 mr-4"></i> Newer</a>
<a class="btn btn-white" href="#">Older <i class="ti-arrow-right fs-9 ml-4"></i></a>
</nav> --}}
{{ $posts->appends(['search' => request()->query('search') ])->links() }}
</div>
#include('partials.sidebar')
</div>
</div>
</div>
</main>
#endsection
If you guys didn't see which file that i don't show up, just ask,.
If you guys see any problems that confusing, i can use teamviewer.
Any Help will be appreciated.
Thank you.
The error told that you don't have posts. Indeed it is. What you have is post() method on Category class, as evidently seen in this line:
public function post() {
You should change this ->with('posts', $category->posts()->simplePaginate()) to be:
public function category(Category $category) {
return view('blog.category')
->with('category', $category)
->with('posts', $category->post()->simplePaginate())
->with('categories', Category::all())
->with('tags', Tag::all());
}
In your model, you defined a post relationship whereas you use a posts relationship then, they're not the same one. You should replace post by posts because it's a to-many relationship.
Your relationship is post and you have multiple ->with('posts', $category->posts()->simplePaginate()). Can you change those to ->with('post') and try again?
I am making CRUD operation in laravel 5.4. I am deleteing an image from database and storage. I did it, but it deletes image name from database only. And do not delete from storage folder.
And I am doing one more thing, If I click on delete button then one confirmation box should be display. If click yes, then delete otherwise not delete. BUt it is also not working.
My web.php is:
Route::resource('todo','todocontroller');
My todocontroller.php is:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\todo;
class todocontroller extends Controller
{
public function index()
{
$todos = todo::paginate('3');
return view('todo.home',compact('todos'));
}
public function destroy($id)
{
$todos = todo::find($id);
if(\File::exists(public_path('public/storage/images/'.$todos->image))){
\File::delete(public_path('public/storage/images/'.$todos->image));
}
$todos->delete();
session()->flash('message','Deleted Successful');
return redirect('todo');
}
}
My home.blade.php is:
#extends('layout.app')
#section('body')
<br>
#if(session()->has('message'))
{{session()->get('message')}}
#endif
<div class="col-lg-4 col-lg-offset-4">Add new
<h1>Todo Lists</h1>
<ul class="list-group">
#foreach($todos as $todo)
<li class="list-group-item d-flex justify-content-between align-items-center">
<span><img src="{{asset('public/storage/images/'.$todo->image)}}" style="height: 100px;width: 100px;"></span>
{{$todo->title}}
{{$todo->body}}
<span>
<form class="delete" action="{{'todo/'.$todo->id}}" method="POST">
{{csrf_field()}}
{{method_field('DELETE')}}
<button type="submit">Delete</button>
</form>
</span>
</li>
#endforeach
{{$todos->links()}}
</ul>
</div>
<script>
$(".delete").on("submit", function(){
return confirm("Do you want to delete this item?");
});
</script>
#endsection
It seems you given wrong path to the images directory. that's why delete image is not working.
public function destroy($id)
{
$todos = todo::find($id);
if(\File::exists(public_path('storage/images/'.$todos->image))){
\File::delete(public_path('storage/images/'.$todos->image));
}
$todos->delete();
session()->flash('message','Deleted Successful');
return redirect('todo');
}
I think this will work.
Edited home.blade.php file
#extends('layout.app')
#section('body')
<br>
#if(session()->has('message'))
{{session()->get('message')}}
#endif
<div class="col-lg-4 col-lg-offset-4">Add new
<h1>Todo Lists</h1>
<ul class="list-group">
#foreach($todos as $todo)
<li class="list-group-item d-flex justify-content-between align-items-center">
<span>
<img src="{{asset('public/storage/images/'.$todo->image)}}" style="height: 100px;width: 100px;">
</span>
{{$todo->title}}
{{$todo->body}}
<span>
<form class="delete" action="{{'todo/'.$todo->id}}" method="POST" onsubmit="return confirm('Do you really want to submit the form?');">
{{csrf_field()}}
{{method_field('DELETE')}}
<button type="submit">Delete</button>
</form>
</span>
</li>
#endforeach
{{$todos->links()}}
</ul>
</div>
#endsection
you can use unlink function to delete file.
public function destroy($id)
{
$todos = todo::find($id);
if(\File::exists(public_path('storage/images/'.$todos->image))){
unlink(public_path('storage/images/'.$todos->image));
}
$todos->delete();
session()->flash('message','Deleted Successful');
return redirect('todo');
}
hope this will help.
Yesterday I started with Laravel, currently busy with my first project, a simple news page.
Unfortunately, I've met some problems while validating my post request, I've tried to search on Google for my issue. And I tried to use those fixes, but strange enough I had no result.
The problem is:
When I post data the normal 'form page' will be shown without any errors. I'm aware that I have double error outputs, it's just for the test.
What do I want to reach?
I want that the validation error will be shown
routes.php
<?php
Route::group(['middleware' => ['web']], function() {
Route::get('/', function() {
return redirect()->route('home');
});
Route::get('/home', [
'as' => 'home',
'uses' => 'HomeController#home',
]);
Route::get('/add_article', [
'as' => 'add_article',
'uses' => 'HomeController#add_article',
]);
Route::post('/add_article', [
'as' => 'add_article.newarticle',
'uses' => 'HomeController#post_article',
]);
});
HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\News;
class HomeController extends Controller
{
public function home(News $news)
{
$articles = $news->orderBy('id','desc')->take(3)->get();
return view('home.home')->with('articles', $articles);
}
public function add_article()
{
return view('home.add_article');
}
public function post_article(Request $request)
{
$this->validate($request, [
'title' => 'required|max:64',
'content' => 'required|max:2048',
]);
// $newNews = new News;
// $newNews->title = $request->title;
// $newNews->content = $request->content;
// $newNews->save();
}
}
add_article.blade.php
#extends('templates.default')
#section('content')
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-6 col-xl-6 offset-md-3 offset-lg-3 offset-xl-3">
<p class="lead">New news article</p>
<div class="card">
<div class="card-header">
<h5 class="mb-0"> </h5>
</div>
<div class="card-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ route('add_article.newarticle') }}">
<div class="form-group">
<label for="title" style="margin-bottom:0px;">
Title:
</label>
<input class="form-control" type="text" name="title" placeholder="Please enter your title!" id="title">
#if ($errors->has('title'))
{{ $errors->first('title') }}
#endif
</div>
<div class="form-group">
<label for="content" style="margin-bottom:0px;">
Content:
</label>
<textarea class="form-control" rows="3" name="content" placeholder="Please enter your message!" id="content" style="resize:none;"></textarea>
#if ($errors->has('content'))
{{ $errors->first('content') }}
#endif
</div>
<div class="form-group text-right">
<button class="btn btn-primary" type="submit">
Create news
</button>
</div>
{{ csrf_field() }}
</form>
</div>
</div>
</div>
</div>
#endsection
I hope someone can help me to resolve this issue!
use App\Http\Requests;
Remove This from HomeController.php and try.
Your validation is passing but you are not doing anything after so it's not going to show anything unless you tell it to.
Also make sure you use $request->all() instead of $request in the validator as the first one will return the actual input values that were submitted.
use Validator;
public function post_article(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|max:64',
'content' => 'required|max:2048',
]);
if ($validator->fails()) {
return redirect('home')
->withErrors($validator)
->withInput();
}
// $newNews = new News;
// $newNews->title = $request->title;
// $newNews->content = $request->content;
// $newNews->save();
return redirect()->route('home')->with('message', 'Article created.');
}
}
Then in your view add the following at the top:
#if(Session::has('message'))
<div class="alert alert-success">
×
{{ Session::get('message') }}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Based on those validation rules you will only see errors when the title is empty or longer than 64 characters, or the content is empty or longer than 2048 characters. Make sure the data you are testing with is long enough to trigger any errors.
For data that passes validation the code currently does not save (commented out), nor does it return a new location or view so it will show a blank page. You should probably save the data and redirect to the index or a show page with a success message.