Data is not showing in view - php

I am new to Laravel and I am using Laravel 9. I am creating a migraine diary web app. I managed to create a custom log in and register system and created a page to display the diary entries and a diary entry form. Currently that page shows the username and user id with a couple of other lines. For showing the diary entries, I am currently trying to show the diary date to get it working, once I can show the date, I should be able to show the rest.
However, after completing the form I am redirected to the diary page as intended but the date from the database is not showing. I checked tinker and the data is being stored and when I used ddd it seems that no data is being sent to the view so I suspect it is something to do with how I am passing data into the view
I currently have 2 controllers, one to handle get requests so as to control user authorisation (and post requests for log in and register) and the other for post requests not related to log in and registration.
The relationship between users and the diary is that a user can have many diary entries, while a diary can only have one user
this is what shows at the bottom of ddd()
snip of bottom of ddd
routes (web.php)
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthorisationController;
use App\Http\Controllers\EntryController;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
return view('welcome');
});
Route::get('diary', [AuthorisationController::class, 'diary'])->name('diary');
Route::get('loginpage', [AuthorisationController::class, 'loginPage'])->name('loggingin');
Route::post('computeLogin', [AuthorisationController::class, 'completeLogin'])->name('login.custom');
Route::get('register', [AuthorisationController::class, 'registerPage'])->name('registerUser');
Route::post('computeRegister', [AuthorisationController::class, 'computeRegistration'])->name('register.compute');
Route::get('signout', [AuthorisationController::class, 'logOut'])->name('logout');
Route::get('/addDiary', [AuthorisationController::class, 'addDiary'])->name('addDiary');
Route::post('/addDiary/entry', [EntryController::class, 'addDiaryEntry'])->name('addDiaryEntry');
User model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'username',
'password',
];
public $timestamps = false;
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password'
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
];
public function diaries()
{
return $this->hasMany(Diary::class);
}
}
Diary model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Diary extends Model
{
use HasFactory;
protected $fillable = [
'date',
'user_id',
'stress',
'low_water_intake',
'chocolate',
'cheese',
'yeast_goods',
'yoghurt',
'fruit',
'nuts',
'olives',
'tomato',
'soy',
'vinegar',
'medication',
'comment'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
Authorisation Controller
<?php
/*
need to customise look
check for other bugs
*/
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use App\Models\User;
use App\Models\Diary;
use Illuminate\Support\Facades\Auth;
class AuthorisationController extends Controller
{
# index
public function loginPage()
{
return view('auth.loginpage');
}
# customLogin
public function completeLogin(Request $request)
{
$request->validate([
'username' => 'required',
'password' => 'required',
]);
$successful = 'Welcome User!';
$failedLogin = 'Error! Entered details are not valid, please try again or register an account!';
# diary
$verifications = $request->only('username', 'password');
if (Auth::attempt($verifications)) {
return redirect('diary')->with('success', $successful);
}
return redirect('loginpage')->with('failed', $failedLogin);
}
# registration
public function registerPage()
{
return view('auth.registerpage');
}
public function computeRegistration(Request $request)
{
$request->validate([
'username' => 'required|unique:users',
'password' => 'required|min:6',
'password1' => 'required|min:6',
]);
$info = $request->all();
if($info['password'] == $info['password1']){
User::create([
'username' => $info['username'],
'password' => Hash::make($info['password'])
]);
$successRegistration = 'You have created an account!';
$verifications = $request->only('username', 'password');
if (Auth::attempt($verifications)) {
return redirect('diary')->with('successReg', $successRegistration);
}
} else {
$notMatching = 'Passwords do not match';
return redirect('register')->with('notMatching', $notMatching);
}
}
public function diary(User $user){
if(Auth::check()){
ddd('wont show data', $user->diaries);
$data = $user->diaries->all();
return view('diary', [
'diaries' => $data,
]);
}
$noAccess = 'You are not signed in, either sign in or register!';
return redirect('loginpage')->with('noAccess', $noAccess);
}
public function addDiary()
{
if(Auth::check()){
return view('addDiary');
}
$noAccess = 'You are not signed in, either sign in or register!';
return redirect('loginpage')->with('noAccess', $noAccess);
}
public function logOut(){
Session::flush();
Auth::logout();
$loggedOut = 'You have logged out, want to log back in?';
return redirect('loginpage')->with('loggedOut', $loggedOut);
}
}
Entry Controller (this controls posts not related to log in and register)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Diary;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class EntryController extends Controller
{
public function addDiaryEntry(Request $request)
{
$rules = [
'date' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails())
{
return redirect()->back();
}
$data = $request->all();
$diaryEntry = new Diary();
$diaryEntry->user_id = Auth::user()->id;
$diaryEntry->date = $data['date'];
$diaryEntry->stress = $data['stress'];
$diaryEntry->low_water_intake = $data['dehydrated'];
$diaryEntry->chocolate = $data['chocolate'];
$diaryEntry->cheese = $data['cheese'];
$diaryEntry->yeast_goods = $data['yeast'];
$diaryEntry->yoghurt = $data['yoghurt'];
$diaryEntry->fruit = $data['fruit'];
$diaryEntry->nuts = $data['nuts'];
$diaryEntry->olives = $data['olives'];
$diaryEntry->tomato = $data['tomato'];
$diaryEntry->soy = $data['soy'];
$diaryEntry->vinegar = $data['vinegar'];
$diaryEntry->medication = $data['takenMeds'];
$diaryEntry->comment = $data['comment'];
if (!$diaryEntry->save())
{
return redirect()->back();
}
$diaryEntry->save();
return redirect('diary');
}
}
dairy.blade.php
#extends('layout')
#section('maincontent')
<main>
#foreach ($diaries as $diary)
<div class="container">
<h4>
Date
</h4>
<p>
{{ $diary->date->toDateString() }}
</p>
</div>
#endforeach
<p>
Welcome {{ auth()->user()->username }}!
</p>
<p>
Welcome user with id {{ auth()->user()->id }}!
</p>
#if (session('success'))
<small>
{{ session('success') }}
</small>
#elseif (session('successReg'))
<small>
{{ session('successReg') }}
</small>
#endif
<p style="margin:1em;">
Success.
</p>
<button>
Add Diary Entry
</button>
</main>
#endsection
addDiary.blade.php
#extends('layout')
#section('maincontent')
<main>
<div class="container">
<form method="POST" action="{{ route('addDiaryEntry') }}">
#csrf
<div class="form-group row">
<label for="text" class="col-4 col-form-label">Date</label>
<div class="col-8">
<input id="date" name="date" type="date" class="form-control" required="required">
</div>
</div>
<div class="form-group row">
<label class="col-4">Stressed</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="stress" id="stress" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Dehydrated</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="dehydrated" id="dehydrated" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Chocolate</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="chocolate" id="chocolate" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Cheese</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="cheese" id="cheese" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Yeast Products</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="yeast" id="yeast" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Yoghurt</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="yoghurt" id="yoghurt" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Citrus Fruits</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="fruit" id="fruit" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Nuts</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="nuts" id="nuts" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Olives</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="olives" id="olives" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Tomato</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="tomato" id="tomato" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Soy</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="soy" id="soy" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-4">Vinegar</label>
<div class="col-8">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="vinegar" id="vinegar" type="checkbox" class="custom-control-input" value="1">
</div>
</div>
</div>
<div class="form-group row">
<label for="takenMeds" class="col-4 col-form-label">Medication Taken</label>
<div class="col-8">
<textarea id="takenMeds" name="takenMeds" cols="40" rows="5" class="form-control"></textarea>
</div>
</div>
<div class="form-group row">
<label for="comments" class="col-4 col-form-label">Comment</label>
<div class="col-8">
<textarea id="comments" name="comment" cols="40" rows="5" class="form-control"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-4 col-8">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</main>
#endsection

Related

How to give a more specific role, like read, create, update, and delete? here I use laravel 5.8

For now the role that I created has been running properly, but when I add read, create, update and delete I have difficulty. this is what I expect:
my expectations
This is my roles table:
roles table
This is my user_role table:
user_role
This is my User Model:
public function roles() {
// return $this->belongsToMany('App\Role');
//test
return $this->belongsToMany('App\Role')->withPivot([
'rd',
'cr',
'up',
'dl'
]);
}
public function hasAnyRoles($roles) {
return null !== $this->roles()->whereIn('kd_role', $roles)->first();
}
public function hasAnyRole($role) {
return null !== $this->roles()->where('kd_role', $role)->first();
}
public function karyawan()
{
return $this->hasOne('App\Karyawan', 'nik', 'nik');
}
public function roleUser() {
return $this->hasMany('App\RoleUser');
}
This is my User Controller
public function edit($id)
{
$id = Crypt::decrypt($id);
//Auth user
$authUser = Auth::user()->id;
$authAdmin = Auth::user()->is_admin;
if ($authUser == $id && $authAdmin == false) {
return redirect('/users')->with('warning', 'Kamu Tidak Dapat Mengubah Data Dirimu Sendiri.');
}
return view('layouts.user.edit')->with(['user' => User::with('roles')->find($id), 'roles' => Role::all()]);
// Test
// $user = User::with('roles')->find($id);
// return json_encode($user);
}
And this is my view:
<div class="form-group row">
<label for="role"
class="col-sm-2 col-form-label col-form-label-sm">Role</label>
<!-- Input text validasi -->
<div class="col-sm-10">
#if ($roles->count())
#foreach($roles as $role)
<div class="custom-control custom-checkbox mb-3">
<div class="row">
<div class="col-sm-2">
<input name="roleUser[]" value="{{$role->id}}" {{ $user->hasAnyRole($role->kd_role)?'checked':'' }} id="customCheck{{$role->id}}" class="custom-control-input" type="checkbox">
<label class="custom-control-label" for="customCheck{{$role->id}}">{{$role->nm_role}}</label>
</div>
<div class="col-sm-10">
{{-- Testing --}}
<div class="col d-inline mr-3">
<input name="create" value="" id="customCheck111" class="custom-control-input" type="checkbox">
<label class="custom-control-label">Read</label>
</div>
<div class="col d-inline mr-3">
<input name="create" value="" id="customCheck111" class="custom-control-input" type="checkbox">
<label class="custom-control-label">Create</label>
</div>
<div class="col d-inline mr-3">
<input name="update" value="" id="customCheck222" class="custom-control-input" type="checkbox">
<label class="custom-control-label">Update</label>
</div>
<div class="col d-inline mr-3">
<input name="delete" value="" id="customCheck333" class="custom-control-input" type="checkbox">
<label class="custom-control-label">Delete</label>
</div>
{{-- End Testing --}}
</div>
</div>
</div>
#endforeach
#endif
</div>
Thanks a lot.

submit form not storing data to database

So i was trying to make a posting form using ckeditor and post it to database, and then try to display it in the same view, but after i submit the form i don't see anything in my database table so clearly it's not even storing to database, is there any mistakes in my controller or view ?
this is my GuestbookController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Guestbook;
class GuestbookController extends Controller
{
public function index()
{
$guestbooks = Guestbook::get();
return view('post.post_textarea',[
'guestbooks' => $guestbooks,
]);
}
public function store(Request $request)
{
Guestbook::create([
'name' => $request->name,
'message' => $request->message
]);
return redirect()->back();
}
}
this is my routes
Route::get('/posting','GuestbookController#index')->name('guestbook');
Route::post('/posting','GuestbookController#store')->name('guestbook.store');
this is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Guestbook extends Model
{
protected $fillable = ['name', 'message'];
}
and this is my view
<section class="games-single-page">
<div class="container">
#foreach ($guestbooks as $guestbook)
<div class="card">
<div class="card-body">
<label>mike</label>
<h3>{{ $guestbok->name }}</h3>
{!! $guestbook->message !!}
</div>
</div>
#endforeach
<div class="card">
<div class="card-body">
<form action="/posting" method "POST">
<div class="form-group">
<label style="color: black;" >Title</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label style="color: black;" >Your Input</label>
<br>
<textarea class="form-control" name="message" id="" rows="10"></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value"Send">
</div>
</form>
</div>
</div>
</div>
</section>
You forgot an equal sign '=' and a csrf field. try the answer.
<form action="/posting" method="POST">
{{csrf_field()}}

PHP laravel object not creating in 5.8

I have a PHP Laravel CRUD application I made where I am using MVC style. I have controllers views and models. My database migration is made and my table in the database is made with php artisan migrate. I am using php 7.3 and laravel 5.8.
On my create view I go to create a single object in my database and my errors are thrown saying nothing in text box (no input) If I comment out the errors then just I click my submit button and nothing happens nothing is entered into my db. I have looked at many different crud examples and I am not sure why my object isn’t being created. Here is what I have
My env is setup correctly I just don’t get the not creating object.
//view create
#section('main')
<section id="section-content" class="text-center">
<div class="container contentdiv rounded">
<div class="row">
<div class="col-md-12">
<div class="pb-2 mt-4 mb-2 border-bottom clearfix">
<h2>Create Contact</h2>
</div>
<div >
<a class="btn btn-success" href="{{route('contacts.index')}}">Back</a>
</div>
</div>
<!-- <div class="col-md-10 mx-auto">
#if($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div><br />
#endif
</div> -->
<div class="row">
<div class="col-md-10 mx-auto mt-3">
<form method="POST" action="{{ route('contacts.store') }}">
#csrf
<div class="form-group row">
<label for="txtfn" class="col-sm-3"><b>First Name:</b></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="txtfn" id="txtfn"/>
</div>
</div>
<div class="form-group row">
<label for="txtln" class="col-sm-3"><b>Last Name:</b></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="txtln" id="txtln"/>
</div>
</div>
<div class="form-group row">
<label for="txtem" class="col-sm-3"><b>Email:</b></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="txtem" id="txtem"/>
</div>
</div>
<button type="submit" class="btn btn-primary">Create Contact</button>
</form>
</div>
</div>
</div>
</section>
//controller
namespace App\Http\Controllers;
use App\Contact;
use Illuminate\Http\Request;
class ContactController extends Controller
{
public function store(Request $request)
{
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required'
]);
$contact = new Contact([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'job_title' => $request->get('job_title'),
'city' => $request->get('city'),
'country' => $request->get('country')
]);
$contact->save();
return redirect('/contacts')->with('success', 'Contact saved!');
}
public function index()
{
$contacts = Contact::all();
return view('contacts.index', compact('contacts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('contacts.create');
}
// model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'city',
'country',
'job_title'
];
}
Your problem is that your input names do not correspond to the keys you are referencing in your store() method:
for example:
<input type="text" class="form-control" name="txtfn" id="txtfn"/>
here, your input name is txtfn, but in your store method, you are looking for first_name.
'first_name' => $request->get('first_name')
so, $request->get('first_name') returns null as if you didn't pass any value.
You must make your input names match with the keys you are using in your store method, either by changing input names, or by changing key names.
example:
<input type="text" class="form-control" name="first_name" />
<input type="text" class="form-control" name="last_name" />
<input type="text" class="form-control" name="email" />

Laravel not taking my Database Input

I'm trying to insert entries in database table but it's not working. It was working 2 weeks ago but I thing I have accidentally changed something.
my relevant model, migration and controllers are here
Model - Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
//
protected $table='profile';
protected $fillable=['user_id', 'Gender', 'Age', 'Address'];
}
Migration -
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfileTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::create('profile', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->char('Gender', 1);
$table->string('Age')->unique();
$table->string('Address');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
Controller - profileController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Profile;
use App\Http\Requests;
use Request;
use Carbon\Carbon;
//use App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
class profileController extends Controller
{
//
public function index(){
return view('pages.profile');
}
public function store(){
$uid=Auth::user()->id;
$input=Request::all();
$input['user_id']=$uid;
$profile = new Profile(array('user_id'=>$uid, 'gender'=>$input['gender'], 'age'=>$input['age'], 'address'=>$input['address']));
return view('welcome');
}
}
The page with form - pages/profile.blade.php
{!! Form::open(array('class' => 'form-horizontal col-xs-10 col-sm-6 col-md-4')) !!}
<!-- <form class="form-horizontal col-xs-10 col-sm-6 col-md-4 ">-->
<fieldset>
<!-- Form Name -->
<legend>User Profile</legend>
<!-- Multiple Radios -->
<div class="form-group">
<label class="col-md-4 control-label" for="gender">Gender</label>
<div class="col-md-4">
<div class="radio">
<label for="gender-0">
<input type="radio" name="gender" id="gender-0" value="1" checked="checked">
Male
</label>
</div>
<div class="radio">
<label for="gender-1">
<input type="radio" name="gender" id="gender-1" value="2">
Female
</label>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="age">Age</label>
<div class="col-md-2">
<input id="age" name="age" type="text" placeholder="Age" class="form-control input-md">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="address">Address</label>
<div class="col-md-8">
<textarea class="form-control" id="address" name="address">Address</textarea>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
<!--</form>-->
{!! Form::close() !!}
Also, just in case, my route.php -
Route::get('profile', 'profileController#index');
Route::post('profile', 'profileController#store');
In your migration, you use uppercase column names (i.e. "Gender"), whereas you use lowercase ("gender") when you try to fill your model. Also, you never save your model:
$profile = new Profile(array('user_id'=>$uid, 'Gender'=>$input['gender'], 'Age'=>$input['age'], 'Address'=>$input['address']));
$profile->save(); // <- You need to call save() to persist the model to your database.
return view('welcome');
Under: $profile = new Profile(array('user_id'=>$uid, 'gender'=>$input['gender'], 'age'=>$input['age'], 'address'=>$input['address']));
wrtite : $profile->save();
and the action? of {!! Form::open(array('class' => 'form-horizontal col-xs-10 col-sm-6 col-md-4')) !!}
read this http://laravelcollective.com/docs/5.1/html#form-model-binding

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