Laravel simple form not setting errors and session variables - laravel-5

I am new to Laravel and I am trying to create a simple form that adds a record into a database table (that has 2 fields: ID and name).
Here is the code I have so far:
routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/banks/add', 'BanksController#add');
Route::post('/banks/add', 'BanksController#store');
});
BanksController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\BankFormRequest;
use App\Bank;
class BanksController extends Controller
{
public function add() {
return view('banks.add');
}
public function store(BankFormRequest $request) {
$bank = new Bank(array(
'name' => $request->get('name'),
));
$bank->save();
return redirect('/banks/add')->with('status', 'Your bank has been created! Its name is: '.$request->get('name'));
}
}
BankFormRequest.php
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class BankFormRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|unique:banks|max:255',
];
}
}
Bank.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Bank extends Model
{
public $timestamps = false;
protected $guarded = ['id'];
}
banks/add.php
<form id="registerForm" role="form" method="post">
<pre><?=var_dump($errors)?></pre>
<pre>
<?php if (session()->has('status')): ?>
<?=session('status')?>
<?php endif; ?>
</pre>
<?php if (isset($errors) && $errors->any()): ?>
<?php foreach ($errors->all() as $error): ?>
<p class="alert alert-danger"><?=$erorr?></p>
<?php endforeach; ?>
<?php endif; ?>
<input type="hidden" name="_token" value="<?=csrf_token()?>">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Bank name" name="name">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
banks table
CREATE TABLE `banks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
In the banks/add view I have the form and 2 var_dumps of the $errors and session('status') variables, but they are always NULL. Otherwise, the form validator works well and it inserts my input into the database if it passes the rules I defined.
Anyone knows what causes my errors to not be shown?

in your banks/add.php
<p class="alert alert-danger"><?=$erorr?></p>
$erorr is wrong

If you are using laravel 5.2 try to remove web middleware on the route group this will fix your problem. why? because the RouteServiceProvider class will add it for you.
line 53 - 60 as of this writing.
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}

Related

Method Illuminate\Database\Eloquent\Collection::paginate does not exist using relations tales

I created a page using the pagination feature, when I opened the blog page everything went well, but when I opened the blog page based on the username from the user table there was an error Method Illuminate\Database\Eloquent\Collection::paginate does not exist. BTW it uses the same view.
blog.blade.php
#extends('layouts.main')
#section('container')
<main class="mt-20 mb-5 w-[800px] mx-auto">
#foreach ($blogs as $blog)
<article class="mb-5">
{{-- judul --}}
<h2 class="text-blue-600 text-2xl mb-2 font-semibold">{{ $blog->title }}</h2>
{{-- penulis category --}}
<p>Author : {{ $blog->user->name }} | Category : {{ $blog->category->name }}</p>
<p class="mt-2 pb-2 border-b border-grey-500">{{ Str::limit($blog->body, 100) }}</p>
</article>
#endforeach
{{ $blogs->links() }}
</main>
#endsection
BlogController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Blog;
class BlogController extends Controller
{
public function index() {
return view('blog', [
'title' => 'All Blog',
'blogs' => Blog::latest()->paginate(5)
]);
}
public function show(Blog $blog) {
return view('show_blog.index', [
'title' => $blog->title,
'blog' => $blog
]);
}
}
UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function blogFromUser(User $user) {
return view('blog', [
'title' => $user->name,
'blogs' => $user->blog->paginate(5)
]);
}
}
Blog.php *relate to user (belongsTo)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
use HasFactory;
public function category() {
return $this->belongsTo(Category::class);
}
public function user() {
return $this->belongsTo(User::class);
}
}
)*
User.php *related to Blog (hasMany)
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
public function Blog() {
return $this->hasMany(Blog::class);
}
}
)*
When you do :
$user->blog
it will execute the query and retrieve the results, so $user->blog will be a collection.
If you want to paginate it, you need to call paginate on the query/relation, not the result, so you need to do something like :
$user->blog()->paginate(5)
then to access other pages, you will have to append ?page=xy to the page url
be aware that if you have multiple paginations within the same page you will need to change the name of the parameter to avoid conflict like so :
$user->blog()->paginate(5, '*', 'blog')

Call to undefined method App\Models\Catogry::firstItem()

I'm trying to create a CMS project but I got this error when I create the URL & Controller for the edit button (Call to undefined method App\Models\Catogry::firstItem()).
here is the web.php page
<?php
use App\Http\Controllers\CategoryController;
use App\Models\User;
use Illuminate\Support\Facades\DB;
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('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
// $users = User::all();
$users = DB::table('users')->get();
return view('dashboard', compact('users'));
})->name('dashboard');
//category controller
Route::get('/category/all', [CategoryController::class, 'index'])->name('index.category');
Route::post('/category/add', [CategoryController::class, 'store'])->name('store.category');
Route::get('/category/edit/{id}', [CategoryController::class, 'edit']);
here Is the CategoryController >>
<?php
namespace App\Http\Controllers;
use App\Models\Catogry;
use Carbon\Carbon;
use Illuminate\Auth\Events\Validated;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class CategoryController extends Controller
{
public function index()
{
$categories = Catogry::latest()->paginate(5);
return response()->view('Admin.category.index', compact('categories'));
}
public function store(Request $request)
{
$validated = $request->validate([
'category_name' => 'required|unique:catogries|max:25|min:4',
]);
//insert with three ways *****
// Catogry::insert([
// 'category_name' => $request->category_name,
// // 'user_id' => Auth::user()->id,
// 'created_at' => Carbon::now()
// ]);
$categories = new Catogry;
$categories->category_name = $request->category_name;
$categories->user_id = Auth::user()->id;
$categories->save();
// $date = array();
// $data['category_name'] = $request->category_name;
// $data['user_id'] = Auth::user()->id;
// DB::table('catogries')->insert($data);
return redirect()->back()->with('success', 'Category Inserted Successfully');
}
public function Edit($id)
{
// return 'edit page';
$categories = Catogry::findOrFail($id);
return response()->view('Admin.category.edit', compact('categories'));
}
}
here is the edit.blade.php page >>
<form action=" " method="POST">
#csrf
<div class="card-body">
<div class="form-group">
<label for="category_name">Edit Your Category Name</label>
<input type="text" class="form-control" id="category_name" name="category_name" placeholder="Enter category name"
value="{{ $categories->category_name }}">
</div>
<div class="card-footer">
<button type="submit" class="btn btn-info">Update Category</button><br>
#error('category_name')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<!-- /.card-footer -->
</form>

Laravel Import Excel into DB: ErrorException Undefined array key "name"

I am trying to use the Maatwebsite\Excel package to let users import a csv or excel file and it get imported into the DB.
I am new to laravel, so I am not quite sure how to troubleshoot this issue.
I keep getting the error:
ErrorException Undefined array key "FIRST"
http://127.0.0.1:8000/import-form
CSV Sample Data
FIRST,LAST,EMAIL,PHONE,DEPARTMENT,LOCATION
test name 1,teast last 1,test#mail.com,123-123-1231,test department,test location
Routes:
Route::post('/import-form', [ImportPatientController::class, 'importForm'])->name('import.file');
ImportPatientController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\ImportPatientModel;
use Excel;
use App\Imports\PatientImport;
use App\Http\Controllers\Controller;
class ImportPatientController extends Controller
{
public function importUploadForm()
{
return view('import-form');
}
public function importForm(Request $request)
{
Excel::import(new PatientImport,$request->file2);
return "Record are imported successfully!";
}
}
PatientImport.php (Imports Folder)
<?php
namespace App\Imports;
use App\Models\ImportPatientModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class PatientImport implements ToModel, WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new ImportPatientModel([
'firstName'=>$row['FIRST'],
'lastName' => $row['LAST'],
'email' => $row['EMAIL'],
'phone' => $row['PHONE'],
'department' => $row['DEPARTMENT'],
'location' => $row['LOCATION'],
]);
}
}
ImportPatientModel.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class ImportPatientModel extends Model
{
use HasFactory;
protected $table = "imported_patients";
protected $fillable = ['firstName', 'lastName', 'email', 'phone', 'department', 'location'];
}
import-form.blade.php
<form action="" method="post" enctype="multipart/form-data" action="{{route('import.file')}}">
<img class="flowhealthlogoform" src="{{ url('images/flowhealthlogo.png')}}" />
<h1> BACKUP LIS </h1>
<!-- CROSS Site Request Forgery Protection -->
#csrf
<div class="form-group">
<label>Upload Excel Sheet</label>
<input type="file" class="form-control {{ $errors->has('file') ? 'error' : '' }}" name="file2" id="file">
<!-- Error -->
#if ($errors->has('file'))
<div class="error">
{{ $errors->first('file') }}
</div>
#endif
</div>
<input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">
</form>```
Array keys in PHP are case sensitive.
I think if you change $row['FIRST'] to $row['first'] the issue will be solved!

Yii2 client validation does not work

I have clean yii2-advanced template installed. I created a table in DB with id and test fields. In my Model I wrote rule:
public function rules()
{
return [
[['test'], 'required'],
];
}
Also I specified an unique id for my form.
But validation does not work. After typing smth to control and focus out I have an error in console: Uncaught TypeError: Cannot read property 'required' of undefined. What can be a reason of this?
EDIT:
Model:
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
class ContactForm extends Model
{
public $name;
public function rules()
{
return [
[['name'], 'required'],
];
}
}
View:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<div class="site-contact">
<div class="row">
<div class="col-lg-6">
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= $form->field($model, 'name')->textInput() ?>
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
Controller action:
use backend\models\ContactForm;
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post())) {
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
When you use Rules(), you must type the attribute (or array of attributes) first, and then the type of rule (that can be also a custom function by the way):
[['name'], 'required'] // setting the attribute "name" as required
you can read more about validation and rules here
if you have applied unique id for your form field, try removing it, Yii2 generates id by itself and applies validation message accordingly.

Codeigniter: Not inserting data in table

Update: It is solved ..
For some reason, the data is not getting inserted into the table. It is however being posted from the form as I could see with var dump, but further than that, won't do. So, here are the 3 modules. It is a very simple test scheme: Just a form with two fields, you press Submit and should be inserted. (I can do all that in ordinary PHP with one page, but, the MVC frameworks are a nightmare in this regard, you write about 30 times more code than you would need in procedural.
<?php
class Inserting_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Inserting_model');
}
public function index ()
{
$this->load->view('inserting_view');
}
// Controller
public function insert()
{
$data = array(
'username' => $this->input->post('username', TRUE),
'password' => sha1($this->input->post('password', TRUE)
));
var_dump($data); // We do get the data posted
exit;
$this->Inserting_model->insertdata($data); // this should forward them to the Model
}
}
?>
==============
MODEL
<?php
class Inserting_model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database();
}
public function insertdata($data)
{
$this->db->insert('users', $data);
}
}
?>
========
VIEW
<div id="inserting_form">
<?php echo form_open('index.php/Inserting_controller/insert/'); ?>
<ul>
<li>
<label>Username</label>
<div><?php echo form_input(array('id' => 'username', 'name' => 'username')); ?></div>
</li>
<li>
<label>Password</label>
<div><?php echo form_password(array('id' => 'password', 'name' => 'password')); ?></div>
</li>
<li><?php echo validation_errors();?></li>
<li><?php echo form_submit(array('name' =>'submit'),'Insert');?> </li>
</ul>
<?php echo form_close(); ?>
</div>
Blushing :/
On writing the debugging code, I forgot to delete the exit; thus, the program exited right after that ....

Resources