data isn't saving into db using eloquent relation - laravel

hi m trying to save data into db using Eloquent ORM one-to-one but it is not saving and not showing any error to fix it (m unable to find any solution about it because it is not showing any error),
public function store(Request $request)
{
$request->validate([
'owner_id' => 'required',
'phone_name' => 'required|unique:phones'
]);
$phone = new Phone;
$phone->owner_id = $request->owner_id;
$phone->phone_name = $request->phone_name;
$phone->save();
return redirect()->route('phone.index')->with('flash_messages_success', 'Phone has been added successfully');
}
protected $fillable = [
'pphone_name', 'owner_id'
];
public function owner()
{
return $this->belongsTo('App\Owner');
}
<form method="POST" action="{{ route('phone.store') }}">
#csrf
<div class="form-group">
<label for="">Phone Title</label>
<input type="text" name="phone_name" class="form-control" id="" placeholder="Phone Name">
</div>
<div class="form-group">
<label>Select Owner</label>
<select class="form-control" name="category_id">
<option selected="">Under Owner</option>
#foreach($owners as $owner)
<option value="{{ $owner->id }}">{{ $owner->owner_name }}</option>
#endforeach
</select>
</div>
<input type="submit" name="submit" class="btn btn-primary" value="submit">
</form>

The issue in select name you named category_id so the view should be:
<select class="form-control" name="owner_id">

Related

How To Update hasMany relationship data with multiple row at a time in Laravel?

I want to update SubCategory, which has a relationship with Category as a hasMany relationship. Now I want to update both category and subcategory at a time from one form. I want to update every subcategory which belongs to the category. But I can't do that.
Here is category model:
class Category extends Model
{
use HasFactory;
protected $guarded=[];
public function subcategory(){
return $this->hasMany('App\Models\SubCategory');
}
Here is subcategory model:
class SubCategory extends Model
{
use HasFactory;
protected $guarded=[];
public function category(){
return
$this>belongsTo('App\Models\Category','category_id','id');
}
here is update function in controller:
public function categoryUpdate(Request $request,$id){
if (is_null($this->user) || !$this->user->can('categories-update')) {
abort(403, 'Sorry !! You are Unauthorized !');
}
$request->validate([
'name' => 'required|max:191',
'status' => 'required',
]);
$Category=Category::findOrFail($id);
$Category->name = $request->name;
$Category->slug = Str::slug($request->name);
$Category->status = $request->status;
$Category->updated_by=Auth::user()->id;
$Category->update();
if($request->subcategory_name !=['']){
foreach($request->subcategory_name as $subcat){
if($subcat !=''){
SubCategory::create([
'name'=>json_encode($subcat),
'slug'=>Str::slug(json_encode($subcat)),
'category_id'=>$id,
'created_by' =>Auth::user()->id,
]);
}
}
}
Alert::success('Success','Category has been updated successfully!');
return redirect()->route('category.index');
}
I don't know the code to update multiple subcategories at a time.
Here is the Html form
<form action="{{ route('category.update', $data->id) }}" method="POST">
#csrf
<div class="form-group">
<label for="" class="mb-2">Category name</label>
<input name="name" class="form-control" value="{{ $data->name }}" type="text"
#error('name') is-invalid #enderror" placeholder="Name">
#error('name')
<div class="text-danger">* {{ $message }}</div>
#enderror
</div><br>
<div class="form-group">
<label for="" class="mb-2">SubCategory name</label>
#foreach ($subcat as $sub)
<div class="d-flex w-70 justify-content between mb-2">
<input name="subcategoryname[]" id="subcategoryname" class="form-control w-50" type="text" value="{{json_decode($sub->name)}}"></input>
<button onclick="deleteSubcategory({{$sub->id}})" id="delete_subcat" class="btn btn-danger btn-sm ms-2"><i
class="fa fa-trash text-dark" style="font-size:20px;color:white!important"
aria-hidden="true"></i></button>
</div>
#endforeach
</div><br>
<div class="form-group mt-2">
<label for="" class="mb-2">Add New SubCategory</label>
<div class="subcategory w-50">
<div class="d-flex mb-2">
<input name="subcategory_name[]" class="form-control" id="name" type="text"
placeholder="Name" multiple>
<span id="add" class="btn btn-dark ms-3">+</span>
</div>
</div>
<div class="form-group mt-2">
<label for="" class="mb-2">Status</label>
<br>
<select name="status" class="form-control" style="width:40%"
#error('status') is-invalid #enderror">
<option value="">--Select Status--</option>
<option value="Active" #if ($data->status == 'Active') selected #endif>Active
</option>
<option value="Inactive" #if ($data->status == 'Inactive') selected #endif>Inactive
</option>
</select>
#error('status')
<div class="text-danger">* {{ $message }}</div>
#enderror
</div>
<div class="form-group mt-4 d-flex justify-content-between">
<button type="button" class="btn btn-secondary btn-sm"
data-bs-dismiss="modal">Cancel</button>
<input class="btn btn-primary btn-sm"type="submit" value="Update">
</div>
</form>
The create method takes array of records you want to save. So you can build an array and pass that array to the create method on the SubCategory.
if($request->subcategory_name !=['']){
$subCategories = [];
foreach($request->subcategory_name as $subcat){
if($subcat !=''){
$subCategories[] = [
'name'=>json_encode($subcat),
'slug'=>Str::slug(json_encode($subcat)),
'category_id'=>$id,
'created_by' =>Auth::user()->id,
];
}
}
SubCategory::updateOrCreate(['name', 'slug'], $subCategories);
}

Failed to save value select option

what's wrong in my project.
I want to save with select option, but the filed doesn't save data select option. it just save input text.
the project is taken different table, and the form just get the project_name and project_id. project_id will save in in table spent_times.
and the select option will save task_category in table spent_times
this my model
protected $table = 'spent_times';
protected $fillable = [
'task_category',
'story/meeting_name',
'assign',
'estimated_time',
'user_story',
'spent_time',
'percentage',
'lateness',
'index',
'project_id'
];
public function users() {
return $this->hasMany(User::class);
}
public function project() {
return $this->belongsTo(Project::class);
}
my create.blade.php
<form action="{{route('store')}}" method="POST">
#csrf
<div class="box-body">
<div class="form-group">
<label for="">Project *</label>
<select class="form-control select2" style="width: 100%;">
<option>Select One</option>
#foreach($projects as $id => $project)
<option value="{{$id}}">{{$project}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">Story # Meeting Name *</label>
<input type="text" class="form-control" name="user_story">
</div>
<div class="form-group">
<label for="">Category *</label>
<select class="form-control select2" style="width: 100%;">
<option>Select One</option>
#foreach($task_categories as $category)
<option value="{{$category}}">{{$category}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">Estimated *</label>
<input type="text" class="form-control" name="estimated_time">
</div>
</div>
<div class="box-footer">
<a href="{{route('index')}}">
<button type="submit" class="btn btn-primary col-md-12" style="border-radius : 0px;">SAVE</button>
</a>
</div>
</form>
my controller
public function create()
{
$spentimes = new SpentTime;
$project = new Project;
$projects = Project::select('project_name', 'id')->get();
return view('Ongoings.index', compact ('projects', 'task_categories', 'spentimes', 'project'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
dd($request->all());
$spentime = SpentTime::create([
'project_name' => request('project_name'),
'user_stroy' => request ('user_story'),
'task_category' => request('task_category'),
'estimated_time' => request('estimated_time')
]);
$spentime->save();
return redirect()->route('index');
}
error like this
error in web browser
please help me
You are expecting those fields from request in controller.
project_id
meeting_name
task_category
estimated_time
But You are just sending estimated_time,
other 3 fields are not present in you create.blade.php
In create.blade.php, category select input don't have any name.
that's why task_category is getting null from request('task_category'). But task_category field is not nullable in your database table.
Send form input properly as you are expecting in your controller. You can use dd($request->all()) to check.
I believe this is your task_category select box.
so this select box doesn't have a name attribute. that's the error.
Possible solution.
<div class="form-group">
<label for="">Category *</label>
<select name="task_category" class="form-control select2" style="width: 100%;">
<option>Select One</option>
#foreach($task_categories as $category)
<option value="{{$category}}">{{$category}}</option>
#endforeach
</select>
</div>

Storing registration data in database using laravel 5.4

Have been trying to create a user registration/login page following laracast video.
But when I try to register a user, it return to the same page without given any error as to why. I also noticed that the supplied info is not stored in the database.
Am so confused I don't know what am doing wrong you help will be really appreciated
Here is my view:
<div class="col-md-offset-1 col-md-8">
<h1 class="text-center ">Register</h1>
<form method="POST" action="register" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" email="email" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" required>
</div>
<div class="form-group">
<label for="password_confirmation">Password Confirmation</label>
<input type="password" class="form-control" name="password_confirmation" required>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-reply"></i>Register</button>
</form>
</div>
This is my controller
public function create()
{
return view('registration.create');
}
public function store(Request $request)
{
//validate form
$this->validate(request(),[
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
//create and save user
$user = new User; //create new Post model object
$user->name = $request->name; //adding thing to the the Post object
$user->email = $request->email;
$user->password = $request->password;
//save user
$user->save(); //to save the new item into the DB
//$user = User::create(request(['name', 'email', 'password']));
//sign them in
auth()->login($user);
//redirect to the admin
return redirect('/admin');
}
While this is my route file:
Route::get('register', 'RegistrationController#create');
Route::post('register', 'RegistrationController#store');
Thanks a lot in advance
Check your form, there's an error in the email field. It says:
and should be:
<input type="email" class="form-control" name="email" required>
So, replace email="email" with name="email"
first you add this error block. so, you can find error easily.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Then, your mistake is in form action. please replace it to below code.
<form method="POST" action="{{ route('register') }}" enctype="multipart/form-data">

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code?

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code? I got it all for a default presentation but i still get an Undefined Variable request with this code - please your answer will be appreciated:
UserController:
public function account(&$data, $request){
User::get_user(self::$data,$request);
self::$data['title'] = self::$data['title'] . 'Edit Account';
return view('forms.account', self::$data);
}
public function postAccount(AccountRequest $request){
User::edit_user($request);
return redirect('');
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
Model:
static public function get_user(&$data,$request){
$sql = "SELECT * FROM users WHERE id = ". Session::get('user_id');
$data['users'] = DB::select($sql);
}
static public function edit_user(&$data,$request) {
$id = $data['id'];
$sql = "SELECT * FROM users WHERE id = ".$id;
$getVal = DB::select($sql);
if($data['name'] || $data['password'] || $data['email']){
if($data['name']){
DB::update("UPDATE users SET name = ? WHERE id = ?",[$data['name'],$id]);
session(['user_name' => $data['name']]);
}
if($data['password']){
DB::update("UPDATE users SET password = ? WHERE id = ?",[bcrypt($data['password']),$id]);
}
if($data['email']){
DB::update("UPDATE users SET email = ? WHERE id = ?",[$data['email'],$id]);
}
}
Session::flash('sm',$request['name'] . '`s Has Been Updated');
}
Web:
Route::get('user/account', 'UserController#account');
Route::post('user/account', 'UserController#postAccount');
HTML:
#extends('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h1>Edit Your Account -</h1>
</div>
<div class="row" style="margin-left:30%;">
<div class="col-md-6">
<form action="" method="post">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{ $user['id'] }}">
<div class="form-group">
<label for="name"></label>
<input value="{{ $user['name'] }}" type="text" name="name"
class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="email"></label>
<input value="{{ $user['email'] }}" type="text" name="email"
class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="editpassword"></label>
<input type="password" name="password" class="form-control"
id="editpassword" placeholder="Edit Password">
</div>
<div class="form-group">
<label for="editpasswordconf"></label>
<input type="password" name="password_confirmation" class="form-
control" id="editpasswordconf" placeholder="Confirm New Password">
</div>
<div class="form-group text-center">
<input type="submit" name="submit" value="Update Details" class="btn
btn-primary">
</div>
</form>
</div>
</div>
</div>
#endsection
Your AccountController should look like this:
public function edit($request, Account $account){
return view('forms.account', [
'account' => $account,
'title' => 'Edit Account'
]);
}
public function update(AccountRequest $request, Account $account){
$account->update($request->all());
Session::flash('sm', $account->name . ' Has Been Updated');
return redirect()->back();
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
That is about as much code as you need for this process... please read the documentation for Eloquent https://laravel.com/docs/5.4/eloquent

How to insert multiple rows in laravel 5?

I want to insert an array with an id :
create.blade :
{{ Form::open(array('route' => 'Charge.store','method'=>'POST')) }}
<select id="disabledSelect" class="form-control" name="Facture_id">
<option value="{{ $Facture->id }}" >{{ $Facture->Num }}</option>
</select>
<br/>
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Title]" placeholder="libelé"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Quantity]" placeholder="Quantité"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Price]" placeholder="Prix unitaire "/>
</div>
<div class="form-group">
<input type="button" class="btn btn-default" value="Ajouter" onclick="createNew()" />
</div>
<div id="mydiv"></div>
</div>
<br/>
<div class="form-group">
<input type="submit" value="Ajouter" class="btn btn-info">
Cancel
</div>
{{ Form::close() }}
<script>
var i = 2;
function createNew() {
$("#mydiv").append('<div class="form-group">'+'<input type="text" name="rows[' + i +'][Title]" class="form-control" placeholder="libelé"/>'+
'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Quantity]" class="form-control" placeholder="Quantité"/>'+'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Price]" class="form-control" placeholder="Prix unitaire "/>'+'</div>'+'<div class="form-group">'+
'<input type="button" name="" class="btn btn-default" value="Ajouter" onclick="createNew()" />'+
'</div><br/>');
i++;
}
</script>
here is my controller , when I tried to submit the form , it inject rows with value of 0.
What should I do ? I tried to use elequent bolk data , but the problem remain the same:
public function store(Request $request)
{
// validated input request
$this->validate($request, [
'Facture_id' => 'required',
]);
// create new task
$rows = $request->input('rows');
foreach ($rows as $row)
{
$Charges[] = new Charge(array(
'course_id'=>$request->input('Facture_id'),
'Title'=>$row['Title'],
'Quantity'=>$row['Quantity'],
'Price'=>$row['Price'],
));
}
Charge::create($Charges);
return redirect()->route('Charge.index')->with('success', 'Your task added successfully!');
}
You can use insert() method:
foreach ($rows as $row)
{
$charges[] = [
'course_id' => $request->input('Facture_id'),
'Title' => $row['Title'],
'Quantity' => $row['Quantity'],
'Price' => $row['Price'],
];
}
Charge::insert($charges);
Don't forget to add all column names you use to a $fillable array:
$fillable = ['course_id', 'Title', 'Quantity', 'Price'];

Resources