I have been learning the new enum class and been having a heck of a time getting it to pass validation. Its just a simple role enum.
The error I'm getting says "The selected role is invalid even though I'm seeing in console.log(employee) that it is a valid value for each selection.
The Enum
<?php
namespace App\Enums;
enum RoleEnum: string
{
case none = 'none'; //in case role has yet to be assigned
case employee = 'employee';
case manager = 'manager';
case admin = 'admin';
}
The model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Boss;
use App\Enums\RoleEnum;
class Employee extends Model
{
use HasFactory;
protected $fillable = [ 'id', 'name', 'boss_id','title' ];
protected $casts = [ 'role' => RoleEnum::class];
public function employees()
{
return $this->belongsTo('\App\Models\Boss');
}
}
The Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Models\Boss;
use App\Models\Employee;
use App\Enums\RoleEnum;
class EmployeeController extends Controller
{
public function store(Request $request)
{
$request->validate([
'name' =>'required|string|max:255',
'boss_id' =>'required|exists:bosses,id',
'title' =>'string|max:255',
'role' =>'required|in:RoleEnum',
]);
$employee = Employee::create([
'name' => $request->name,
'boss_id' => $request->boss_id,
'title' => $request->title,
'role' => $request->role,
]);
$bosses = Boss::get();
return redirect('/details')->with([
'employee' => $employee,
'bosses' => $bosses,
'success','User Created!',
]);
}
}
The Create blade input (I only included the code in question)
<div class="form-group">
<label for="role">Role</label>
<select
class="form-control"
id="role"
v-model="game.role"
required
>
<option class="form-check-input" type="radio" value='employee'>Employee</option>
<option class="form-check-input" type="radio" value='manager'>Manager</option>
<option class="form-check-input" type="radio" value='admin'>Admin</option>
</select>
</div>
Consol.log(employee)
name: "John Martin"
boss_id: "5"
title: "Trainer"
role: "employee"
This is all new territory for me so any help is greatly appreciated.
The in rule you are using is for a list of specific comma-separated values. You are passing it the name of an enum however in does not work like that.
Laravel has an enum validation rule you can use:
use Illuminate\Validation\Rules\Enum;
use App\Enums;
class EmployeeController extends Controller
{
public function store(Request $request)
{
$request->validate([
'name' =>'required|string|max:255',
'boss_id' =>'required|exists:bosses,id',
'title' =>'string|max:255',
'role' => [ 'required', new Enum(RoleEnum::class) ],
]);
$employee = Employee::create([
'name' => $request->name,
'boss_id' => $request->boss_id,
'title' => $request->title,
'role' => $request->role,
]);
$bosses = Boss::get();
return redirect('/details')->with([
'employee' => $employee,
'bosses' => $bosses,
'success','User Created!',
]);
}
}
Related
I have two model that are related.
Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Address extends Model
{
use HasFactory;
protected $fillable = [
'city',
'post_code',
'street',
'country'
];
protected $hidden = [
'created_at',
'updated_at',
'addressable_id',
'addressable_type'
];
public function addressable(): MorphTo
{
return $this->morphTo();
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Club extends Model
{
use HasFactory;
protected $fillable = [
'name',
'email',
'phone',
'description',
'user_id'
];
protected $hidden = [
'created_at',
'updated_at'
];
public function address()
{
return $this->morphMany(Address::class, 'addressable');
}
}
For that models i've got Request class with validator rules.
Requests
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreAddressRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'city' => 'required|string|max:125',
'post_code' => 'required|string',
'street' => 'required|string',
'country' => 'required|string| max:125'
];
}
}
<?php
namespace App\Http\Requests;
use App\Traits\FailedValidation;
use Illuminate\Foundation\Http\FormRequest;
class StoreClubRequest extends FormRequest
{
use FailedValidation;
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|string|max:125',
'description' => 'required|string',
'email' => 'email:dns',
'phone' => 'string|max:125',
// 'address' => (new StoreAddressRequest)->rules(), ???
'images' => 'required|image'
];
}
}
Trying to create new club with address.
I'm sending request to API like that:
[
"name":"dfsdf",
"dsfsdf":"sdfsdf",
"address": {
"city": "name",
"post_code":"46-454"
}
]
Address may be added standalone or from other model that are related too.
Now only fields from club request are validated.
How to validate club and address request?
The problem is i want to return back with the inputs when the validation is fails. Here I'm using a custom request class to validate user input.
Now my question is where i place this piece of code on Controller Or in Request class.
or is there another way to do it?
Here is the code i want to use:
return redirect()->back()->withInput();
Here is the Controller:
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Requests\Admin\counter\CreateCounterRequest;
use App\Models\Admin\Counter;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CounterController extends Controller
{
public function store(CreateCounterRequest $request)
{
Counter::create([
'title' => $request->title,
'ion_icon' => $request->ion_icon,
'counter_value' => $request->counter_value,
]);
session()->flash('success', 'Counters created successfully.');
return redirect(route('counter.index'));
}
}
Here is the Request Class:
<?php
namespace App\Http\Requests\Admin\counter;
use Illuminate\Foundation\Http\FormRequest;
class CreateCounterRequest extends FormRequest
{
public function rules()
{
return [
'ion_icon' => 'required',
'title' => 'required',
'counter_value' => 'required|numeric',
];
}
}
you can use a method from FormRequest class, that is failedValidation() method.
and example code is like this:
protected function failedValidation(Validator $validator)
{
return back()->withErrors($validator)->withInput();
}
you must add a argument from Illuminate\Contracts\Validation\Validator class to your method failedValidation and add Illuminate\Http\RedirectResponse class for get redirect method.
add Illuminate\Validation\ValidationException class, if not your method cant be read.
please check this
use Illuminate\Support\Facades\Validator;
protected function validator(array $data)
{
return Validator::make($data, [
'ion_icon' => 'required',
'title' => 'required',
'counter_value' => 'required',
]);
}
public function store(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
return redirect()->route('your_route')->withInput(['title' => $request->title, 'icon_icon' => $request->icon_icon,'counter_value' => $request->couter_value,'phone_number'=>$request->phone_number])->withErrors($validator, 'your_desire_name');
}
Counter::create([
'title' => $request->title,
'ion_icon' => $request->ion_icon,
'counter_value' => $request->counter_value,
]);
session()->flash('success', 'Counters created successfully.');
return redirect(route('counter.index'));
}
Want In Your Blade File Show this error message
<div >
<input type="text" name="title" class="form-control"
value="{{old('title')}}" required>
</div>
#if ($errors->your_desire_name->has('title'))
<span class="messages"><p
class="text-danger error">{{ $errors->your_desire_name->first('title') }}</p></span>
#endif
NewsController.php
This is the contoller and i use the create function to add record to the database but when i add all records will be empty
public function insertNews() {
$attribute = [
'Ntitle' => 'News Title',
'Ndesc' => 'News Description',
'Naddedby' => 'News Added By',
'Ncontent' => 'News Content',
'Nstatus' => 'News Status'
];
$data = $this->validate(request(), [
'Ntitle' => 'required',
'Ndesc' => 'required',
'Naddedby' => 'required',
'Ncontent' => 'required',
'Nstatus' => 'required'
], [], $attribute);
News::create($data);
return redirect('all/news');
}
and i use dd() to show the record and it will show with the token and all other values
dd(request()->all())
News.php
and this is the model file
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class News extends Model
{
use SoftDeletes;
protected $primaryKey = 'News_ID';
protected $date = ['delete_at'];
protected $fillable = ['News_Title', 'News_Descrption', 'News_Content', 'Added_By', 'News_Status'];
}
web.php
this is the web file (routes)
Route::post('insert/news', 'NewsController#insertNews');
news.blade.php
and this is the blade file that contain the form that i sent to the controller
<form action="{{ url('insert/news') }}" method="POST">
{{ csrf_field() }}
<input type="text" name="Ntitle" value="{{ old('Ntitle') }}" placeholder="News Title"><br />
<input type="text" name="Ndesc" value="{{ old('Ndesc') }}" placeholder="News Descrption"><br />
<input type="number" name="Naddedby" value="{{ old('Naddedby') }}" placeholder="News Added By"><br />
<textarea name="Ncontent" value="{{ old('Ncontent') }}" placeholder="News Content"></textarea><br />
<select name="Nstatus">
<option value="Active" {{ old('Nstatus') == 'Active' ? 'selected' : '' }}>Active</option>
<option value="Pending" {{ old('Nstatus') == 'Pending' ? 'selected' : '' }}>Pending</option>
<option value="Disabled" {{ old('Nstatus') == 'Disabled' ? 'selected' : '' }}>Disabled</option>
</select><br />
<input type="submit" value="Add News">
</form>
enter image description here
There are number of reasons for your code to not work:
In your case, you have incorrectly equated the $data to the validation object. You should use the $attribute (the key value array of data, not the validation object) in the create function instead of the $data.
Secondly the keys passed in the array of the create data should be exactly same to the fields name of the table that you are using for data insertion. I see that your code shows Ntitle, Ndesc etc being used for the validation and in the $attribute array, while the fillable protected $fillable has the different field names! So, please use the correct field names in the data that you are passing and in the $fillable in the model. I am writing the below code assuming that Ntitle, Ndesc, Naddedby, Ncontent, Nstatus are the field names of your table. As per that please refer to the below code!
public function insertNews() {
$attribute = [
'Ntitle' => 'News Title',
'Ndesc' => 'News Description',
'Naddedby' => 'News Added By',
'Ncontent' => 'News Content',
'Nstatus' => 'News Status'
];
$this->validate(request(), [
'Ntitle' => 'required',
'Ndesc' => 'required',
'Naddedby' => 'required',
'Ncontent' => 'required',
'Nstatus' => 'required'
], [], $attribute);
News::create($attribute);
return redirect('all/news');
}
Make sure that you have all the fields added to protected $fillable = []; in your model like this:
class News extends Model {
protected $fillable = [
'Ntitle', 'Ndesc', 'Naddedby', 'Ncontent', 'Nstatus'
];
You need to pass the value to the create() method.
//Passing the request to create method
News::create($request->all());
return redirect('all/news');
It will now store if you have added inputs name in the $fillable variable in the News model.
//News.php (Model)
protected $fillable = ['Ntitle', 'Ndesc', 'Naddedby', 'Ncontent', 'Nstatus'];
I prefer to use
//News.php (Model)
protected $guarded = [];
Can i have your web route?
so i can tell that what's the mistake,
i think your route should be
Route::namespace('your_Controller_Foldername')->group(function () {
Route::resource('insert/news', 'NewsController');
});
I'm getting little bit issue in laravel 5.2
When i submit data throgh post. data found in request but not save. pls help.
https://www.awesomescreenshot.com/image/3111642/0ec1946875e85f53eaec7970483ff5f0
Customer.php
<?php
namespace App\Http\Controllers;
enter code here
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class Customer extends Controller {
public function index() {
//$members = Customer::latest()->paginate(10);
return view('pages.admin.customers.customers', compact('customers'));
// ->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create() {
return view('pages.admin.customers.create');
}
public function store(Request $request) {
request()->validate([
'firstname' => 'required',
'lastname' => 'required',
]);
Customer::create($request->all());
return redirect()->route('customer.index');
}
}
Model file Customer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = [
'firstname', 'lastname'
];
protected $table = 'customers';
}
You have a mistake in validation, instead of:
request()->validate([
'firstname' => 'required',
'lastname' => 'required',
]);
You need use:
$this->validate($request, [
'firstname' => 'required',
'lastname' => 'required',
]);
There are other ways to validate which you can read about in official documentation Validation.
I'm supposed to display author details in bookformat method. But facing LogicException. Any suggestions thanks in advance. Im getting error like this LogicException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation. Any help that would be great for me. If I comment authors in bookFormat() everything works fine. But Idk why I'm unable to get author details in my bookformat().
#booksController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Models\Book;
use App\Models\Author;
class BooksController extends Controller
{
public function index()
{
$books = Book::all();
$results = [];
foreach ($books as $book) {
$results [] = $this->bookFormat($book);
}
return $results;
}
public function bookFormat($book){
return [
'Id' => $book->id,
'Title' => $book->title,
'Author' => [
'Id' => $book->author->id,
'First_name' => $book->author->first_name,
'Last_name' => $book->author->last_name
],
'Price' => $book->price,
'ISBN' => $book->isbn,
'Language' => $book->language,
'Year' => $book->year_of_publisher
];
}
}
//book.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
public $timestamps = TRUE;
protected $table = 'books';
//rules
public static $rules = [
'title' => 'required|max:255',
'isbn' => 'required|max:50',
'author_id' => 'required|max:255',
'language' => 'required|max:255',
'price' => 'required|max:255',
'year_of_publisher' => 'required'
];
//relationship
public function author() {
$this->belongsTo(Author::class);
}
}
Instead of:
public function author() {
$this->belongsTo(Author::class);
}
you should have:
public function author() {
return $this->belongsTo(Author::class);
}
Notice the return difference.