Laravel Controller Not Passing through Data - php

I am creating a very simple survey web app and in the answering of a created survey the controller is not functioning in the controller instead of dumping the array data and its information it instead redirects straight back to the form, and doesn't dump anything, there are no errors when executing the code it just redirects back to the form. I have tried remigrating, and rewriting the form in the view that fixed some things but still not the main issue
Survey Controller:
public function store(Questionnaire $questionnaire, $slug){
$data = request()->validate([
'responses.*.answerid' => 'required',
'responses.*.question_id' => 'required',
'survey.name' => 'required',
'survey.email' =>'required | email',
]);
dd($data);
}
Blade.php View:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<h1>{{ $questionnaire->title }}</h1>
<form action = "/surveys/{{ $questionnaire->id }}-{{Str::slug($questionnaire->title)}}" method = "post">
#csrf
#foreach($questionnaire->questions as $key => $question)
<div class="card mt-4">
<div class="card-header"><strong> {{ $key + 1 }} </strong>{{ $question->question }}</div>
<div class = "card-body">
#error('responses.' . $key . '.answerid')
<small class = "text-danger">{{ $message }}</small>
#enderror
<ul class = "list-group">
#foreach($question->answers as $answer)
<label for="answer{{$answer->id}}">
<li class="list-group-item">
<input type = "hidden" name = 'responses[{{$key}}][questionid]' value = '{{$question->id}}'>
<input type = "radio" name = 'responses[{{$key}}][answerid]' id = 'answer{{ $answer->id }}' class = "mr-2" value= "{{$answer->id}}" {{ old('responses.' . $key . '.answer_id') == $answer->id ? 'checked' : '' }}>
{{ $answer->answer }}
</li>
</label>
#endforeach
</ul>
</div>
</div>
#endforeach
<div class="card mt-4">
<div class="card-header">Your Information</div>
<div class="card-body">
<div class="form-group">
<label for="name">Your Name</label>
<input name = "survey[name]" type="text" class="form-control" id="name" aria-describedby="nameHelp" placeholder="Enter Name">
<small id="nameHelp" class="form-text text-muted">Please Enter Your Name</small>
#error('name')
<small class = "text-danger">{{ $message }}</small>
#enderror
</div>
</div>
<div class="card-body">
<div class="form-group">
<label for="email">Your Email</label>
<input name = "survey[email]" type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter Email">
<small id="emailHelp" class="form-text text-muted">Please enter your Email</small>
#error('email')
<small class = "text-danger">{{ $message }}</small>
#enderror
</div>
</div>
<div>
<button class = "btn btn-dark" type="submit">Complete Survey</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
#endsection
Routes file:
Route::get('/surveys/{questionnaire}-{slug}', 'SurveyController#show');
Route::post('/surveys/{questionnaire}-{slug}', 'SurveyController#store');
Questionnaire Model:
protected $guarded = [];
public function surveys(){
return $this->hasMany(Survey::class);
}
Survey Model:
protected $guarded = [];
public function questionnaire(){
return $this->belongsTo(Questionnaire::class);
}
public function responses(){
return $this->hasMany(SurveyResponse::class);
}
SurveyResponses Model:
protected $guarded = [];
public function survey(){
return $this->belongsTo(Survey::class);
}
Survey Migration:
Schema::create('surveys', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('questionnaire_id');
$table->string('name');
$table->string('email');
$table->timestamps();
});
Survey Responses Migration:
Schema::create('survey_responses', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('survey_id');
$table->unsignedBigInteger('questionid');
$table->unsignedBigInteger('answerid');
$table->timestamps();
});
This is the form in the blade.php file:
<form action = "/surveys/{{ $questionnaire->id }}-{{Str::slug($questionnaire->title)}}" method = "post">
#csrf
#foreach($questionnaire->questions as $key => $question)
<div class="card mt-4">
<div class="card-header"><strong> {{ $key + 1 }} </strong>{{ $question->question }}</div>
<div class = "card-body">
#error('responses.' . $key . '.answerid')
<small class = "text-danger">{{ $message }}</small>
#enderror
<ul class = "list-group">
#foreach($question->answers as $answer)
<label for="answer{{$answer->id}}">
<li class="list-group-item">
<input type = "hidden" name = 'responses[{{$key}}][questionid]' value = '{{ $question->id }}'>
<input type = "radio" name = 'responses[{{$key}}][answerid]' id = 'answer{{ $answer->id }}' class = "mr-2" value= "{{$answer->id}}" {{ old('responses.' . $key . '.answer_id') == $answer->id ? 'checked' : '' }}>
{{ $answer->answer }}
</li>
</label>
#endforeach
</ul>
</div>
</div>
#endforeach
<div class="card mt-4">
<div class="card-header">Your Information</div>
<div class="card-body">
<div class="form-group">
<label for="name">Your Name</label>
<input name = "survey[name]" type="text" class="form-control" id="name" aria-describedby="nameHelp" placeholder="Enter Name">
<small id="nameHelp" class="form-text text-muted">Please Enter Your Name</small>
#error('name')
<small class = "text-danger">{{ $message }}</small>
#enderror
</div>
</div>
<div class="card-body">
<div class="form-group">
<label for="email">Your Email</label>
<input name = "survey[email]" type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter Email">
<small id="emailHelp" class="form-text text-muted">Please enter your Email</small>
#error('email')
<small class = "text-danger">{{ $message }}</small>
#enderror
</div>
</div>
<div>
<button class = "btn btn-dark" type="submit">Complete Survey</button>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
</div>
</form>
This is the input where the question id should be passed through:
<input type = "hidden" name = 'responses[{{$key}}][questionid]' value = '{{ $question->id }}'>

Your dd($data); in your controller not run if your request validate fails because when validation fails it redirect to your view with errors. So you have two way to see error:
1- use below code in your controller:
use Illuminate\Support\Facades\Validator; // Important to use Validator Facade in this case
public function store(Questionnaire $questionnaire, $slug){
$validator = Validator::make($request->all(), [
'responses.*.answerid' => 'required',
'responses.*.question_id' => 'required',
'survey.name' => 'required',
'survey.email' =>'required|email',
]);
if ($validator->fails()) {
//dd($validator);
return redirect(route('route-name'))
->withErrors($validator)
->withInput();
}
}
2- use below code in your view:
<!-- /resources/views/view-name.blade.php -->
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Related

How to create category tags for posts? I am using laravel 8

I am trying to allow users to create and add category tags to a post when creating that post in the form.
I would further want those tags to appear in the profile view and function as filter buttons to show posts according to the tag names they possess.
However, in my attempt to achieve this overall result, I am stuck because everytime I submit a post with tags, the tags array keeps showing up empty in the view.
My post table is:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('url');
$table->string('image');
$table->text('tags');
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
My Post Model is:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Post extends Model
{
use \Conner\Tagging\Taggable;
use HasFactory;
protected $fillable = ['caption','url','image', 'tags'];
public function user()
{
return $this->belongsTo(User::class);
}
protected $dates = [
'created_at',
'updated_at',
];
}
My create and store methods in PostsController are:
public function create()
{
return view('posts.create');
}
public function store(Request $request)
{
$data = request()->validate([
'caption' => 'required',
'url' => 'required',
'image' => ['required', 'image'],
'tags' => 'required',
]);
$tags = explode(", ", $request->tags);
$imagePath = request('image')->store('uploads', 'public');
auth()->user()->posts()->create([
'caption' => $data['caption'],
'url' => $data['url'],
'image' => $imagePath,
'tags' => $data['tags'],
]);
return redirect('/users/' . auth()->user()->id);
}
My form to create post is:
<form action="/posts" enctype="multipart/form-data" method="post">
#csrf
<div class="form-group">
<label for="caption" class="create_caption_label">Post Caption</label>
<div class="create_caption_div">
<input id="caption"
type="text"
class="form-control #error('caption') is-invalid #enderror"
name="caption"
value="{{ old('caption') ?? '' }}"
autocomplete="caption" autofocus>
#error('caption')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="form-group">
<label for="tags" class="create_tags_label">Tags</label>
<div class="create_tags_div">
<input id="tags"
type="text"
data-role="tagsinput"
class="form-control #error('tags') is-invalid #enderror"
name="tags"
value="{{ old('tags') ?? '' }}"
autocomplete="tags" autofocus>
#error('tags')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="form-group">
<label for="url" class="edit_title_label">URL</label>
<div class="edit_url_div">
<input id="url"
type="text"
class="form-control #error('url') is-invalid #enderror"
name="url"
value="{{ '' }}"
autocomplete="url" autofocus>
#error('url')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="create_post_image_div">
<label for="image" class="create_image_label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#error('image')
<div class="invalid-feedback-div">
<strong>{{ $message }}</strong>
</div>
#enderror
<div class="create_post_btn_div">
<button class="create_post_btn">Save Post</button>
</div>
</div>
</form>
Finally, my view is: (This is where the tags array shows up empty after submitting a post)
#foreach( $user->posts as $post )
<div class="carousel_posts_container">
<div class="post_date_and_edit_div">
<div class="posted_date_div">
<p class="posted_date">posted: {{ $post->created_at->diffForHumans() }}</p>
</div>
<div class="post_edit_div">
<form action="/posts/{{$post->id}}/edit">
<input class="post_edit_btn" type="submit" value="• • •">
</form>
</div>
</div>
<div class="post_counter_div">
<p class="post_counter">1 like</p>
</div>
<div class="post_counter_div">
<p class="post_counter">1 comment</p>
</div>
<div class="carousel_post_img_div">
<img src="/storage/{{ $post->image }}" class="carousel_img_placeholder">
</div>
<div class="like_comment_view_container">
<div class="view_btn_div">
<form action="{{$post->url}}">
<input class="like_comment_view_btns" type="submit" value="( View Post )">
</form>
</div>
<div class="like_btn_div">
<button type="button" class="like_comment_view_btns">( Like )</button>
</div>
<div class="comment_btn_div">
<button type="button" class="like_comment_view_btns">( Comment )</button>
</div>
</div>
<div class="carousel_caption_container">
<div class="carousel_caption_div">
<p class="carousel_caption_username">{{$user->username}} - {{$post->caption}}</p>
<p class="carousel_caption">{{$post->caption}}</p>
</div>
<div class="post-tags mb-4">
<strong>Tags : </strong>
#foreach($post->tags as $tag)
<span class="badge badge-info">{{$tag->name}}</span>
#endforeach
</div>
</div>
</div>
#endforeach
How can I resolve this issue?
And furthermore, how can I allow the tags to function as filter buttons to show posts according to the tag names they possess?
You can save tags as json array in db. Then cast to array in model, so it will be automatically array when you will retrieve. When saving you will pass tags as array then it will automatically convert to json string.
protected $casts = [
'tags' => 'array',
];

Uploading file to database from input

I am learning Laravel and got stuck with one issue. I have created form with validation and all goes to database. Except my image_url with type="file"
<form method="POST" action="{{route('photos.store')}}" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="">
#component('components.back', ['url' => route('photos.index')])
#endcomponent
<hr>
</div>
<div class="form-all">
<ul class="form-section page-section">
<li class="form-line" data-type="control_image" id="id_1">
<div id="cid_1" class="form-input-wide">
<div style="text-align:center;">
<img alt="" class="form-image" style="border:0px;" src="" height="42px" width="42px" data-component="image">
</div>
</div>
</li>
<li class="form-line" data-type="control_text" id="id_12">
<div id="cid_12" class="form-input-wide">
<div id="text_12" class="form-html" data-component="text">
<p><span style="color:#363636;font-size:xx-large;">Įkelti nuotrauką</span></p>
</div>
</div>
</li>
<li class="form-group{{ $errors->has('title')?' has-error' : ''}}" id="id_7">
<label class="form-label form-label-top" id="label_7" for="title">Pavadinimas</label>
<div id="cid_7" class="form-input-wide">
<input id="title" type="text" name="title" value="{{ old('title') }}" class="form-control" placeholder="Pavadinimas">
#if ($errors->has('title'))
<span class="help-block">
<strong>
{{ $errors->first('title')}}
</strong>
</span>
#endif </div>
</li>
<li class="form-group{{ $errors->has('description')?
' has-error' : ''}}">
<label class="form-label form-label-top" id="label_5" for="description">Aprašymas</label>
<div id="cid_5" class="form-input-wide">
<input id="description" type="text" name="description" value="{{ old('description') }}" class="form-control" placeholder = "Aprašymas">
#if ($errors->has('description'))
<span class="help-block">
<strong>
{{ $errors->first('description')}}
</strong>
</span>
#endif
</div>
</li>
<li class="form-group {{ $errors->has('image_url')?
' has-error' : ''}}">
<label class="form-label form-label-top" id="label_11" for="image_url">Nuotrauka</label>
<div id="cid_11" class="form-input-wide">
<input id="image_url" type="file" name="image_url" value="{{ old('image_url') }}" class="form-control">
#if ($errors->has('image_url'))
<span class="help-block">
<strong>
{{ $errors->first('image_url')}}
</strong>
</span>
#endif
</div>
</li>
<li class="form-group {{ $errors->has('category_id') ? 'has-error': ''}}">
<label class="form-label form-label-top" id="label_11">Kategorija</label>
#if(isset($photo))
<select name="category_id" class="form-control">
<option value="">Pasirinkti kategoriją</option>
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#endforeach
</select>
#else
<select name="category_id" class="form-control">
<option value="">Pasirinkti kategoriją</option>
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#endforeach
</select>
#endif
#if($errors->has('category_id'))
<span class="help-block">
<strong>{{ $errors->first('category_id')}}</strong>
</span>
#endif
</li>
<li class="form-line" data-type="control_button" id="id_2">
<div id="cid_2" class="form-input-wide">
<div style="text-align:center;" class="form-buttons-wrapper">
<button id="input_2" type="submit" class="form-submit-button" data-component="button">
Patvirtinti
</button>
</div>
</div>
</li>
</ul>
</div>
and my Controller looks like this:
public function create()
{
$categories = Category::all();
return view('photo.create', compact('photo','categories'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|min:3',
'image_url'=> 'required',
'category_id' => 'required',
]);
$photo = new Photo;
$photo->title = $request->input('title');
$photo->image_url = $request->input('image_url');
$photo->description = $request->input('description');
$photo->category_id = $request->input('category_id');
$photo->save();
$request->session()->flash('create', $request->title. "Sekmingai sukurta");
$path = $request->image_url->store('images');
return redirect()->route('photos.index');
}
and seeder:
public function __construct( Photo $photo, Category $category) {
$this->photo = $photo;
$this->category = $category;
}
public function run()
{
$categories_ids = $this->category->pluck('id');
DB::table('photos')->insert(
[
'title' => '',
'image_url' => '',
'description' => '',
'category_id' => $categories_ids->random()
]);
}
I understand that I should put some if into Controller telling "If its not text, but file- accept file". But I am not able to find answer online.
Thank you for your advises in advance.
You will get image name from $fileName = $request->image_url->store('images');
and note $fileName wil return folder name also images/2Q3J1gU3j8NkMgt5HtGurSDtu5BIbeATNZb13Ih3.jpeg
$photo = new Photo;
if ($request->hasFile('image_url')) {
$fileName = $request->image_url->store('images');
$photo->image_url = $fileName;
}
$photo->title = $request->input('title');
$photo->description = $request->input('description');
$photo->category_id = $request->input('category_id');
$photo->save();
$request->session()->flash('create', $request->title. "Sekmingai sukurta");
return redirect()->route('photos.index');

Laravel admin login isn't working

Admin login don't work and don't give me any error.
I have this routes in web.php file:
Auth::routes();
Route::prefix('admin')->group(function () {
Route::get('/login','Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login','Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/','AdminController#getIndex')->name('admin.dashboard');
Route::get('/logout','Auth\AdminLoginController#logout')->name('admin.logout');
Route::post('/password/email','Auth\AdminForgotPasswordController#sendResetLinkEmail')->name('admin.password.email');
Route::get('/password/reset','Auth\AdminForgotPasswordController#showLinkRequestForm')->name('admin.password.request');
Route::post('/password/reset','Auth\AdminResetPasswordController#reset');
Route::get('/password/reset/{token}','Auth\AdminResetPasswordController#showResetForm')->name('admin.password.reset');
});
And this functions in controller(I only put here which have the problems)
public function showLoginForm()
{
return view('auth.adminlogin');
}
public function login(Request $request)
{
//validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
//attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
//if successful, then redirect to their intended location
return redirect('/admin');
}
return redirect()->back()->withInput($request->only('email','remember'));
}
And in resources/views/auth/adminlogin.blade.php i have this code:
#extends('backend.public.includes.head')
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">ADMIN Login</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('admin.login.submit') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('admin.password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
This was working days ago.. and now not, i'm looking all but don't find the error. In networking isn't showing anything and with a debug i don't see anything.
I try to reset password and when i reset it (i have a redirect in the function he redirect me good, only not working in normal login).
Errors aren't showed too
EDIT
Migrate file:
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name',50)->unique();
$table->string('email',200)->unique();
$table->string('password');
$table->boolean('public')->default(true);
$table->rememberToken();
$table->timestamps();
});
}
Seed file:
private $arrayAdmins = array(
array(
'name' => 'Lluis',
'email' => 'lluis.puig#correo.biz',
'password' => 'correo1',
'public' => 1
)
);
public function run()
{
self::seedAdmins();
}
public function seedAdmins()
{
DB::table('admins')->delete();
foreach ($this->arrayAdmins as $admin)
{
$a = new Admin;
$a->name = $admin['name'];
$a->email = $admin['email'];
$a->password = $admin['password'];
$a->public = $admin['public'];
$a->save();
}
}
The admin login isn't working if i created with the seed. (So the problem i guess is with the "user created" with the seed.
I try to create one with php artisan tinker and it works.
SOLVED
I check the seed. The problem was de password isn't encrypted!
This line :
$a->password = $admin['password'];
Must be like this:
$a->password = bcrypt($admin['password']);

How to use CRUD operation in Laravel 5.4

I am new to Laravel. I want to use MongoDB with laravel so I have installed mongodb and configured php extension also(copied mongo dll file) and it works fine.
Now I want to use CRUD operation in laravel using mongoDB. How can I use. How to create model. What I need to modify in model.
Note: show me model code. In model what I have to write.
Thank You
It seems that there's a package that enables you to use MongoDB with Eloquent. I'm not a fan of linking external sources without quoting information here, but copying their readme sounds counterproductive as well. The instructions seem easy enough, so I hope this can help you: Laravel MongoDB.
Example code MongoDb + Php:
Insert:
$mongo = new MongoClient();
$db = $mongo->mydb1;
$data = array('emp_id' => '1', 'first_name' => 'Tiger' , 'last_name' => 'Nixon', 'position' => 'System Architect', 'email' => 't.nixon#datatables.net', 'office' => 'Edinburgh', 'start_date' => '2011-04-25 00:00:00', 'age' => '61', 'salary' => '320800', 'projects' => array('Project1', 'Project2', 'Project3'));
$collection = $db->createCollection("emp_details");
if($collection->insert($data))
{
echo '<p style="color:green;">Record inserted successfully</p>';
}
Update:
$mongo = new MongoClient();
$db = $mongo->mydb1;
/* Note: Here we are using the update() method. The update() method update values in the existing document */
$collection = $db->createCollection("emp_details");
$newdata = array('$set' => array("age" => "55", "salary" => "320000"));
// specify the column name whose value is to be updated. If no such column than a new column is created with the same name.
$condition = array("emp_id" => "1");
// specify the condition with column name. If no such column exist than no record will update
if($collection->update($condition, $newdata))
{
echo '<p style="color:green;">Record updated successfully</p>';
}
else
{
echo '<p style="color:red;">Error in update</p>';
}
Delete:
$mongo = new MongoClient();
// name of database which is to be created
$db_name = 'local';
// get the list of database and check if DB exist, if not than create it.
$dblists = $mongo->listDBs();
if(count($dblists) > 0)
{
$count = 0;
$exist = false;
foreach($dblists['databases'] as $databases)
{
if($databases['name'] == $db_name)
{
$exist = true;
break;
}
}
}
if($exist)
{
$db = $mongo->db_name; // select the db which is to be deleted
if($db)
{
if($db->drop())
{
echo '<p style="color:green;">Database deleted successfully</p>';
}
}
}
else
{
echo '<p style="color:red;">No such database exist</p>';
}
In case of Laravel, you have to study the basic CRUD operation then you will use this very well.
Create Customer Controller
<?php
namespace App\Http\Controllers;
use App\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Hash;
class CustomerController extends Controller
{
public function index(Request $request)
{
$search = $request->get('search');
$field = $request->get('field') != '' ? $request->get('field') : 'firstname';
$sort = $request->get('sort') != '' ? $request->get('sort') : 'asc';
$customers = new Customer();
$customers = $customers->where('firstname', 'like', '%' . $search . '%')
->orderBy($field, $sort)
->paginate(5)
->withPath('?search=' . $search . '&field=' . $field . '&sort=' . $sort);
return view('theme.customers_list', compact('customers'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
public function add()
{
return view('theme.customer_form');
}
public function add_record(Request $request)
{
$this->validate($request,
[
'firstname' =>'required|max:20',
'lastname' =>'required|max:20',
'email' =>'required|email|unique:users',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password',
'phone' =>'required|numeric|phone',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
], [
'firstname.required' => ' The first name field is required.',
//'firstname.min' => ' The first name must be at least 5 characters.',
'firstname.max' => ' The first name may not be greater than 20 characters.',
'lastname.required' => ' The last name field is required.',
//'lastname.min' => ' The last name must be at least 5 characters.',
'lastname.max' => ' The last name may not be greater than 20 characters.',
]);
$customers = new Customer;
$customers->firstname = $request->input('firstname');
$customers->lastname = $request->input('lastname');
$customers->email = $request->input('email');
$customers->phone = $request->input('phone');
$customers->password = Hash::make($request->input('password'));
$customers->confirm_password = $request->input('confirm_password');
if($request->hasFile('image'))
{
$filename = $request->image->getClientOriginalName();
$request->image->storeAs('public/uploads',$filename);
}
$customers->image = $filename;
$customers->save();
return redirect()->action('CustomerController#index');
}
public function edit($id)
{
$customers = Customer::find($id);
return view('theme.customer_edit',compact('customers'));
}
public function update(Request $request, $id)
{
$this->validate($request,
[
'firstname' =>'required|max:20',
'lastname' =>'required|max:20',
'email' =>'required|email|unique:users',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password',
'phone' =>'required|numeric|phone',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
], [
'firstname.required' => ' The first name field is required.',
//'firstname.min' => ' The first name must be at least 5 characters.',
'firstname.max' => ' The first name may not be greater than 20 characters.',
'lastname.required' => ' The last name field is required.',
//'lastname.min' => ' The last name must be at least 5 characters.',
'lastname.max' => ' The last name may not be greater than 20 characters.',
]);
$customers = Customer::find($id);
$customers->firstname = $request->input('firstname');
$customers->lastname = $request->input('lastname');
$customers->email = $request->input('email');
$customers->phone = $request->input('phone');
$customers->password = $request->input('password');
$customers->confirm_password = $request->input('confirm_password');
if($request->hasFile('image'))
{
$filename = $request->image->getClientOriginalName();
$request->image->storeAs('public/uploads',$filename);
}
$customers->image = $filename;
$customers->save();
return redirect()->action('CustomerController#index');
}
public function delete($id)
{
Customer::find($id)->delete();
return redirect()->action('CustomerController#index');
}
public function search()
{
$name = Input::get('search');
if ($name != "")
{
$customers = Customer::where('firstname','Like','%' . $name . '%')
->orWhere('email','Like','%' . $name . '%')
->get();
return view('theme.customers_list',compact('customers'));
}
else
{
dd('no data found');
}
}
public function login()
{
return view('theme.login');
}
public function do_login(Request $request)
{
$email=$request->input('email');
$password = Hash::check($request->input('password'));
dd($password);exit();
$data=with(new Customer)->SignIn($email,$password);
$row=count($data);
if($row > 0){
echo "Login success";
}else{
echo "usename and password Mismatch!";
}
}
}
Now create customer_form.blade.php
#extends('theme.default')
#section('content')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Customer</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<!-- #if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif -->
<form role="form" action="<?php echo url('customer/add_record')?>" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="Firstname">
<span class="text-danger">{{ $errors->first('firstname') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('lastname') ? 'has-error' : '' }}">
<label for="lastname">Lastname</label>
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Lastname">
<span class="text-danger">{{ $errors->first('lastname') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control" placeholder="Email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}">
<label for="phone">Contact Number</label>
<input type="text" name="phone" id="phone" class="form-control" placeholder="Contact Number">
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('confirm_password') ? 'has-error' : '' }}">
<label for="confirm_password">Confirm Password</label>
<input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password">
<span class="text-danger">{{ $errors->first('confirm_password') }}</span>
</div>
</div>
</div>
<div class="row">
<div class= "col-lg-6">
<div class="form-group">
<label>Image</label>
<input type="file" name="image" id="image">
</div>
</div>
<!-- <div class= "col-lg-6">
<div class="form-group">
<label>Text area</label>
<textarea class="form-control" rows="3"></textarea>
</div>
</div> -->
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
<!-- /.col-lg-6 (nested) -->
<!-- /.col-lg-6 (nested) -->
<!-- /.row (nested) -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#add_customer').validate({
rule: {
firstname: {
required: true,
}
},
messages: {
firstname: {
required:"firstname name cannot be blank."
}
},
});
});
</script>
#endsection
create list view customer_list.blade.php
#extends('theme.default')
#section('content')
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Users
<a class="pull-right btn btn-primary" href="<?php echo url('customer/add') ?>">Add Customer</a></h1>
</div>
<!-- /.col-lg-12 -->
</div>
<form action="<?php echo url('customer/index')?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="pull-right btn btn-primary" href="<?php echo url('customer/index') ?>">view all</button>
<div class="pull-right col-lg-3 input-group custom-search-form">
<input class="form-control" name="search" placeholder="Search..." type="text" value="{{ request('search') }}">
<span class="input-group-btn ">
<button class="btn btn-default" type="submit">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<input type="hidden" value="{{request('field')}}" name="field"/>
<input type="hidden" value="{{request('sort')}}" name="sort"/>
<!-- <button type="button" class="pull-right btn btn-primary">Add Customer</button> -->
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>Iamge</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=firstname&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
FirstName
</a>
{{request('field','firstname')=='firstname'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=lastname&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
LastName
</a>
{{request('field','lastname')=='lastname'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=email&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Email
</a>
{{request('field','email')=='email'?(request('sort','asc')=='asc'?'▴':'▾'):''}}</th>
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=phone&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Phone Number
</a>
{{request('field','phone')=='phone'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
#php
$i=1;
#endphp
<?php foreach ($customers as $customer)
{
?>
<tr>
<td><?php echo $i++;?></td>
<td> <img height="50px" width="50px" class="user-pic" src="<?php echo asset("/storage/uploads/$customer->image")?>"></td>
<td><?php echo $customer->firstname;?></td>
<td><?php echo $customer->lastname;?></td>
<td><?php echo $customer->email;?></td>
<td><?php echo $customer->phone;?></td>
<td><a href ='edit/<?php echo $customer->id?>'>Edit</a></td>
<td><a href ='delete/<?php echo $customer->id?>'>Delete</a></td>
</tr>
<?php
}
?>
</tbody>
</table>
<nav>
<ul class="pagination justify-content-end pull-right">
{{$customers->links('vendor.pagination.bootstrap-4')}}
</ul>
</nav>
</form>
#endsection
create edit form customer_edit.blade.php
#extends('theme.default')
#section('content')
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script> -->
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Customer</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<!-- #if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif -->
<form role="form" action="{{ url('customer/update', $customers->id)}}" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $customers->firstname;?>" class="form-control" placeholder="Firstname">
<span class="text-danger">{{ $errors->first('firstname') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('lastname') ? 'has-error' : '' }}">
<label for="lastname">Lastname</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $customers->lastname;?>" class="form-control" placeholder="Lastname">
<span class="text-danger">{{ $errors->first('lastname') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
<label for="email">Email</label>
<input type="text" name="email" id="email" value="<?php echo $customers->email;?>" class="form-control" placeholder="Email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}">
<label for="phone">Contact Number</label>
<input type="text" name="phone" id="phone" value="<?php echo $customers->phone;?>" class="form-control" placeholder="Contact Number">
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class= "col-lg-6">
<div class="form-group">
<label>Image</label>
<div class="fileinput-preview thumbnail" id="profile" data-trigger="fileinput" style="width: 60px; height: 60px;">
<img height="90px" width="70px" class="user-pic" src="<?php echo asset("/storage/uploads/$customers->image")?>">
</div>
<input type="file" name="image" id="image">
</div>
</div>
<!-- <div class= "col-lg-6">
<div class="form-group">
<label>Text area</label>
<textarea class="form-control" rows="3"></textarea>
</div>
</div> -->
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
<!-- /.col-lg-6 (nested) -->
<!-- /.col-lg-6 (nested) -->
<!-- /.row (nested) -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection
create Model Customer.php
<?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function SignIn($email,$password)
{
$sql=DB::table('customers')->where('email',$email)->where('password',$password)->get();
return $sql;
}
}
create routing in web.php
Route::get('home/my-home', 'HomeController#myHome');
Route::get('customer/index', 'CustomerController#index');
Route::get('customer/add', 'CustomerController#add');
Route::post('customer/add_record', 'CustomerController#add_record');
Route::get('customer/edit/{id}', 'CustomerController#edit');
Route::post('customer/update/{id}', 'CustomerController#update');
Route::get('customer/delete/{id}','CustomerController#delete');
Route::post('customer/index','CustomerController#index');
Route::get('customer/login','CustomerController#login');
Route::post('customer/do_login','CustomerController#do_login');
for validation create function in AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
return substr($value, 0, 3) == '+91';
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
Create Routes
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/role', 'RoleController#index')->name('role');
Route::get('/create', 'RoleController#create')->name('role.create');
Route::post('/store', 'RoleController#store')->name('role.store');
Route::get('/edit/{id}', 'RoleController#edit')->name('role.edit');
Route::post('/update/{id}', 'RoleController#update')->name('role.update');
Route::any('/destroy/{id}', 'RoleController#destroy')->name('role.destroy');
Create Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Role;
use Validate;
use Collective\Html\FormFacade;
class RoleController extends Controller
{
public function index(){
$roles = Role::all();
return view('role.index',compact('roles'));
}
public function create(){
return view('role.create');
}
public function store(Request $request)
{
request()->validate([
'name' => 'required',
]);
Role::create($request->all());
return redirect()->route('role')
->with('success','Role created successfully');
}
public function edit($id){
$roles = Role::find($id);
return view('role.edit',compact('roles'));
}
public function update(Request $request, $id){
request()->validate([
'name' => 'required',
]);
Role::find($id)->update($request->all());
return redirect()->route('role')
->with('success','Role updated successfully');
}
public function destroy($id)
{
Role::find($id)->delete($id);
return redirect()->route('role')
->with('success','Role updated successfully');
}
}
Create Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $fillable = [ 'name' ];
}
create layoyt file in layouts folder
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.5 CRUD Application</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
#yield('content')
</div>
</body>
</html>
create index.blade.php
#extends('layouts.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Role</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('role.create') }}"> Create New role</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th width="280">Action</th>
</tr>
#foreach ($roles as $role)
<tr>
<td>{{ $role->id }}</td>
<td>{{ $role->name}}</td>
<td>
<a class="btn btn-primary" href="{{ route('role.edit',$role->id) }}">Edit</a>
<form action="{{ route('role.destroy', $role->id) }}" method="DELETE">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
<!-- <button class="deleteRecord" data-id="{{ $role->id }}" >Delete Record</button> -->
</td>
</tr>
#endforeach
</table>
#endsection
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$(".deleteRecord").click(function(){
var id = $(this).data("id");
//var token = $("meta[name='csrf-token']").attr("content");
$.ajax(
{
url: "destroy/"+id,
type: 'Post',
data: { "id": id, "_token": "{{ csrf_token() }}",},
dataType: "JSON",
success: function (){
console.log("it Works");
}
});
});
});
</script>
Create create.blade.php
#extends('layouts.layout')
#section('content')
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Role</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form role="form" action="{{ route('role.store') }}" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Name">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
</div>
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection
Create edit.blade.php
#extends('layouts.layout')
#section('content')
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Role</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form role="form" action="{{ route('role.update',$roles->id) }}" id="update_role" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" value="<?php echo $roles->name ?>" placeholder="Name">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
</div>
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection

Validation error message not showing and datas not being saved to database

I am trying to first validate the inputs and then add the values to database but neither I am able to see the validation error message nor I am able to insert records to database. I have a table in database named 'news' where I have
this is my boxed.blade.php
<form class="form-horizontal" role="form" method="post" action="/addNews" novalidate>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 col-sm-2 control-label">Title</label>
<div class="col-lg-10">
<input type="text" name="title" class="form-control" id="inputEmail1" placeholder="News Title" value="{{ Input::old('title') }}">
</div>
</div>
<div class="form-group">
<label for="inputPassword1" class="col-lg-2 col-sm-2 control-label">Description</label>
<div class="col-lg-10">
<textarea name="description" class="form-control" rows="6">{{ Input::old('description') }}</textarea>
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 col-sm-2 control-label">Reporter</label>
<div class="col-lg-10">
<input type="text" name="reported_by" class="form-control" id="inputEmail1" placeholder="Reporter Name" value="{{ Input::old('reported_by') }}">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<div class="checkbox">
<label>
<input type="checkbox" name="status"> Status
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-danger"><i class="fa fa-comments"></i> Add To List</button>
</div>
</div>
</form>
And routes.php
Route::get('addNews', function()
{
return View::make('pages.boxed');
}
);
Route::post('addNews', function()
{
//processing the form
$rules = array(
'title' => 'required',
'description' => 'required|min:50',
'reported_by' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
$message = $validator->message();
return Redirect::to('addNews')->withErrors($validator)->withInput(Input::all());
}
else{
$news = new News;
$news->title = Input::get('title');
$news->description = Input::get('description');
$news->reported_by = Input::get('reported_by');
$news->status = Input::get('status');
$news->save();
return Redirect::to('addNews');
}
}
This is my model News.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class News extends Model
{
protected $fillable = array('title', 'description', 'reported_by', 'status');
}
If you want to see the error, place the following code above your form:
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<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
UPDATE 1: Instead of defining the methods in routes.php file, define it in a Controller called NewsController
So, to do this, update your routes.php file to this:
Route::get('/addNews', 'getNewsForm');
Route::post('/addNews', 'postNewsForm');
NewsController.php
/**
* Display the add news form to the user.
*
* #return view
*/
public function getNewsForm()
{
return View::make('pages.boxed');
}
/**
* Store the input in the database after validation
*
* #param $request Illuminate\Http\Facade\Request
*/
public function postNewsForm(Request $request)
{
$this->validate($request, [
'title' => 'required',
'description' => 'required|min:50',
'reported_by' => 'required'
]);
News::create($request->all());
return redirect('/addNews');
}

Categories