How to pass form value from model to controller in laravel - php

I have a modal form that passes value to the model, to controller which will finally run the code to insert to database, but my problem is I don't know how to pass the value from my form to model and to my controller. Here is my model code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class addbusiness extends Model
{
//fillable fields
protected $fillable = ['Fname', 'staffphn'];
}
and below is my controller code that insert into database
public function insert(Request $request){
//validate post data
$this->validate($request, [
'Fname' => 'required',
// 'content' => 'required'
]);
DB::table('business')->insert(
['owner_id' => 3, 'bus_name' => 'Fname' ,'address' => 'Fname' ,'phone' => 'Fname' ,'email' => 'Fname' ,'logo' => 'Fname','country' => 'Fname', 'createdon' => date('Y-m-d H:i:s' ), 'createdby' => 'Fname',]
);
As you can see i passed values straight to my database, and not from my form. the insert code works fine
here is my form
<input type="text" class="form-control" name="Fname" id="Fname" value="" placeholder="Business Name" required />
<span class="glyphicon glyphicon-briefcase form-control-feedback"></span>
My problem now is that I don't know how to pass the form value to my model and finally to my controller. Any help with proper documentation would be appreciated as am new to laravel.

Business::create([
'Fname' => $request->get('Fname'),
...
]);
Or you can use $request->all() if the form has all the correct name attributes:
Business::create($request->all());
Your Model should just be called Business for this to work.

Related

Laravel 9 php 8.1 enum validation

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!',
]);
}
}

Laravel 8: Multiple Select Option Sends Empty Request

I have two tables at db, one of them is named users which simply contains user information of website and the other one is tags which contains some hashtags that users can choose from them.
I also created a table named tag_user that can store the tag_id and user_id like this image:
(just like Stackoverflow that a user can select multiple tags such as php, javascript & etc)
So in order to make this relationship between these two, I added this to User model:
public function tags()
{
return $this->belongsToMany(Tag::class);
}
And also this one to Tag model:
public function users()
{
return $this->belongsToMany(User::class);
}
And here is the select option on blade, and users can select multiple tags from db:
<select class="form-control BSinaBold" name="skills[]" id="skills" multiple>
#foreach(\App\Models\Tag::all() as $tag)
<option value="{{ $tag->id }}" {{ in_array($tag->id , Auth::user()->tags->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $tag->name }}</option>
#endforeach
</select>
Then at the Controller, I added this in order to update data at tags table:
public function update(Request $request, $profile)
{
$validate_data = Validator::make($request->all(),[
'job' => 'nullable',
'stackoverflow' => 'nullable',
'github' => 'nullable',
'instagram' => 'nullable',
'linkedin' => 'nullable',
'website' => 'nullable',
'location' => 'nullable',
'skills' => 'array',
]);
$user = User::findOrFail($profile);
$user->update([
'job' => request('job'),
'stackoverflow' => request('stackoverflow'),
'github' => request('github'),
'instagram' => request('instagram'),
'linkedin' => request('linkedin'),
'website' => request('website'),
'location' => request('location'),
]);
$user->tags()->sync(request('skills'));
$user->save();
return view('profile');
}
And it works fine and perfect but the only problem is this line, that does not sync data at tags table:
$user->tags()->sync(request('skills'));
So I tried debugging and I found out that request('skills') is EMPTY!
So the question is, why it does not send any data to the Controller?
I would really appreciate any idea or suggestion from you guys...
Thanks in advance.
UPDATE #1:
If the skills array is not being posted correctly on the form submission, then there could just be a simple problem with the form. Are you posting normally or using an AJAX call? Do you have a conflicting field on the form called 'skills' like a hidden input? Is the skills field located within the <form> tag?
Otherwise, if the browser is in fact posting the skills correctly but just not being read correctly by the request (unlikely), how about you try to switch your request helper functions request() to use the $request object that was passed into your function. IDK, but maybe it will work differently by some chance since we can't see all your code.
Also note that the validation function isn't doing much of anything since nothing is required.
public function update(Request $request, $profile)
{
$user = User::findOrFail($profile);
$user->update([
'job' => $request->input('job', null),
'stackoverflow' => $request->input('stackoverflow', null),
'github' => $request->input('github', null),
'instagram' => $request->input('instagram', null),
'linkedin' => $request->input('linkedin', null),
'website' => $request->input('website', null),
'location' => $request->input('location', null),
]);
$user->tags()->sync($request->input('skills', []));
// I don't think you need this since update & sync trigger saving
// $user->save();
return view('profile');
}
If you want to see all the data getting posted you can just dump or log the data for debugging:
public function update(Request $request, $profile)
{
Log::debug($request->all());
dd($request->all());
...

Laravel Controller can't receive POST method. Is the "areas" reserved word by any chance?

[ErrorException Undefined index: available_areas] happens.
Somehow Other variables are ok.
I am not sure why available_areas isn't sent.
POST Data is sent to register function of RegistersUsers.
https://github.com/whitepotato/cleaning/blob/master/cleaning/resources/views/keeper_register.blade.php
https://github.com/whitepotato/cleaning/blob/master/cleaning/app/Http/Controllers/Auth/KeeperRegisterController.php
register.blade.php
<div>
<label for="areas">AVAILABLE AREAS</label>
<input type="checkbox" name="all_checked" > ALL<br/>
<p>
#foreach(config('ward') as $index => $name)
<input type="checkbox" name ="available_areas[]" value="{{ $index }}">{{$name}}
#endforeach
</p>
</div>
class StackRegisterController extends Controller
{
use RegistersUsers;
protected function create(array $data)
{
$areas = $data['available_areas'];
//omit
}
}
POST DATA SAMPLE
local.DEBUG: array (
'_token' => '2F5dbNfyyjf9mFtKCSVgAt5K2xXzNyRja3VVZB4X',
'name' => 'fgfgfgf',
'available_profiles' =>
array (
0 => '0',
1 => '1',
),
'profile' => '100',
'email' => 'sffftfdfdone#gmfail.com',
'adress' => '0',
'station' => 'fdfdfd',
'available_otto' =>
array (
0 => '3',
),
'password' => '12345678',
'password_confirmation' => '12345678',
)
use Request type hint.
use Illuminate\Http\Request;
public function create(Request $request)
{
$areas = $request->available_areas;
//$areas = $request->input('available_areas'); //another way to get
}
To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller method. The incoming request instance will automatically be injected by the service container:

condition in laravel validation

Please help me, I'm trying to validate each row of the row that was highlighted with red in the form using the validate([]). If a user filled one of the columns in a row, and try to submit it with the other fields left unfilled, then it will prompt the user that the remaining fields are required to be filled. I have come up with various conditions but sadly none on them worked out,
this is my store function
public function store(Request $request){
$currentStatus = 0;
$data = $request->validate([
'to' => 'required',
'date' => 'date',
'address' => 'required',
'reference' => 'required',
'attention' => 'required',
'area' => 'required',
'project' => 'required',
'salesman' => 'required',
'location' => 'required'
]);
\App\Contract::create($data + ['status' => $currentStatus]);
return redirect('contracts/pendings');
first u need to create a FormRequest php artisan make:request MyControllerNameRequest
Then in MyControllerNameRequest define your rules
public function rules(): array
{
return [
'firstField' => ['required', 'int'],
'secondField' => ['required', 'int'],
'thirdFied' => ['required', 'int'],
'fourthField' => ['required', 'int'],
];
}
after go in to your controller and add MyControllerNameRequest like attribute in action
public function store(MyControllerNameRequest $request)
{
$model = Model::create($request->validated());
return redirect()->route('route.name');
}
or in some_name.blade.php add required
<input type="text" name="name" value="{{ old('value') }}" required>
I'm assuming that the names in HTML look like this:
<form method="post" action="{{ route('test') }}">
#csrf
<input type="text" name="data[0][quantity]">
<input type="text" name="data[0][unit]">
<input type="text" name="data[1][quantity]">
<input type="text" name="data[1][unit]">
<input type="submit">
</form>
You could try something like this in your controller.
$this->validate($request, [
'data.*.quantity' => 'sometimes|required_with:data.*.unit',
'data.*.unit' => 'sometimes|required_with:data.*.quantity',
]);
The required_with params accept multiples fields separated per comma, so you may have to pass all your fields in the validation. The sometimes validates only when it's passed values, so this may do the trick.

Laravel how to add records with create function in controller?

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');
});

Categories