How to insert this array of mySbjects in a database? - laravel

I've been trying to insert this into the database and I don't have any idea how to store this information into the database... The relationship between user and grade is many-to-many and between grade and mySubject is One-to-many.
<div class="row">
#foreach($grades as $grade)
<div class="card shadow mx-2 my-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold">
<div class="custom-control custom-checkbox">
<input class="custom-control-input #error('grade') is-invalid #enderror" type="checkbox" id="{{$grade->id}}" name="grade[]" value="{{ $grade->id }}"/>
<label class="custom-control-label pt-1" for="{{$grade->id}}">{{$grade->name}}</label>
</div>
</h6>
</div>
<div class="card-body">
#foreach($grade->subjects as $subject)
<div class="custom-control custom-checkbox mb-2">
<input class="custom-control-input" type="checkbox" id="{{$grade->id}}{{$subject->id}}" name="mySubjects[{{$grade->id}}][]" value="{{ $subject->name }}"/>
<label class="custom-control-label" for="{{$grade->id}}{{$subject->id}}">
{{$subject->name}}
</label>
</div>
#endforeach
</div>
</div>
#endforeach
</div>
The store function
public function store(Request $request)
{
$user->grades()->sync($request->grade);
if($request->mySubjects){
//. . . .
}
}
}

Try below code:
public function store(Request $request)
{
$user->grades()->sync($request->grade);
if($request->mySubjects){
$mySubjects = $request-> mySubjects;
$data = [];
foreach($mySubjects as $subject){
array_push($data,
'your database field name'=> $subject,
'created_at' => now()->toDateTimeString(),
'updated_at' => now()->toDateTimeString(),
}
YourModelName::insert($data);
}
}
}

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

ReflectionException (-1) Class App\Http\Controllers\AnswersController does not exist

I want to save data in a database using the form
I tried to use a form with input text, radios ... and controller to save data in a database with post method
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\Survey;
use App\Answer;
use App\Http\Requests;
class Answerscontroller extends Controller
{
public function store(Request $request, Survey $survey)
{
$request->validate([
'answer'=>'required'
]);
$answers = new Answer([
'answer' => $request->get('answer'),
'commentaire' => $request->get('commentaire'),
'user_id' => auth()->id(),
'last_ip' => request()->ip(),
'survey_id' => $survey->id
]);
$answers->save();
return redirect('/survey')->with('success', 'Stock has been added');
}
}
View:
{!! Form::open(array('action'=>array('AnswersController#store', $survey->id))) !!}
#forelse ($survey->questions as $key=>$question)
<p class="flow-text">Question {{ $key+1 }} - {{ $question->title }}</p>
#if($question->question_type === 'text')
<div class="form-group">
<div class="input-field col s12">
<input id="answer" type="text" name="{{ $question->id }}[answer]">
<label for="answer">Answer</label>
</div>
</div>
#elseif($question->question_type === 'textarea')
<div class="form-group">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
#if($value === 'else')
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{$value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
<div id="textboxes" style="display: none">
<br>
<textarea class="form-control" name="commentaire" id="exampleFormControlTextarea1" rows="3" placeholder="Write a large text here ..."></textarea>
</div>
</div>
#else
<p style="margin:0px; padding:0px;">
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{ $value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
</div>
</p>
#endif
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<div class="form-group">
<input type="checkbox" id="{{ $value }}" name="answer" value="{{$value}}"/>
<label for="{{$value}}">{{ $value }}</label>
</div>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#empty
<span class='flow-text center-align'>Nothing to show</span>
#endempty
<div class="form-group">
{{ Form::submit('Submit Survey', array('class'=>'btn btn-success mt-4')) }}
</div>
{!! Form::close() !!}
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Answer extends Model
{
protected $fillable = ['answer','commentaire','user_id','survey_id','last_ip'];
protected $table = 'Answer';
public function survey() {
return $this->belongsTo(\App\Survey::class);
}
public function question() {
return $this->belongsTo(\App\Question::class);
}
public function user() {
return $this->belongsTo('App\User');
}
}
Error:
ReflectionException (-1) Class App\Http\Controllers\AnswersController
does not exist
Please could you help me to fix that
ps: in the router, I put post method and controller
The problem is about naming. Your controller is Answerscontroller but the Laravel Looks fo AnswersController with capital C. So, check your controller name that should be AnswersController.php and the class name (inside the file AnswersController.php) that sould be AnswersController.

Add [title] to fillable property to allow mass assignment on [App\Profile]

I am trying to create edit profile, but when I click on edit profile button I'm getting below error:
Illuminate \ Database \ Eloquent \ MassAssignmentException Add [title]
to fillable property to allow mass assignment on [App\Profile]
show.blade.php :
<#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-4">
<img src="https://scontent-cdt1-1.cdninstagram.com/vp/dcca3b442819fc8b9b63f09b2ebde320/5DA9E3CB/t51.2885-19/s150x150/40101184_290824334847414_1758201800999043072_n.jpg?_nc_ht=scontent-cdt1-1.cdninstagram.com" class="rounded-circle">
</div>
<div class="col-8">
<div class="d-flex align-items-baseline">
<div class="h4 mr-3 pt-2">{{ $user->username }}</div>
<button class="btn btn-primary">S'abonner</button>
</div>
<div class="d-flex">
<div class="mr-3">{{ $user->posts->count() }} article(s) en vente
</div>
Modifier Profile
<div class="mt-3">
<div class="font-weight-bold">
{{ $user->profile->title }}
</div>
<div class="font-weight-bold">
{{ $user->profile->description }}
</div>
</div>
</div>
</div>
<div class="row mt-5">
#foreach ($user->posts as $post)
<div class="col-4">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100">
</div>
#endforeach
</div>
</div>
#endsection
ProfileController :
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function show(User $user)
{
return view('profile.show', compact('user'));
}
public function edit(User $user)
{
return view('profile.edit', compact('user'));
}
public function update(User $user)
{
$data = request()->validate([
'title' => 'required',
'description' => 'required'
]);
$user->profile->update($data);
return redirect()->route('profile.show', ['user' => $user]);
}
}
edit.blade.php :
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Modifier profile</div>
<div class="card-body">
<form method="POST" action="{{ route('profile.update', ['user' => $user]) }}" enctype="multipart/form-data">
#csrf
#method('PATCH')
<div class="form-group">
<label for="title">Titre</label>
<div class="col-md-6">
<input id="title" type="text" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') ?? $user->profile->title }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label for="description">Description</label>
<div class="col-md-6">
<textarea id="description" type="text" class="form-control #error('description') is-invalid #enderror" name="description" autocomplete="description" autofocus>{{ old('description') ?? $user->profile->description }}</textarea>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<div class="custom-file">
<input type="file" name="image" class="custom-file-input #error('image') is-invalid #enderror" id="validatedCustomFile" >
<label class="custom-file-label" for="validatedCustomFile">Choisir une image</label>
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Modifier profile
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarder = [];
public function user()
{
return $this->belongsTo('App\User');
}
}
What am I doing wrong here and how can I get rid of this error?
You have a spelling error, instead of $guarder add this in your model:
protected $guarded = [];
I won't advise using empty guarded but use $fillable instead.
In the same controller model, free access to database fields with
protected $guarded = [];
or
protected $fillable = [];

Laravel : no errors and no update on database happens after saving the edit

I have two tables, user and technicien, with a one to one relation. After editing technicien information through edit form and saving, no update happens on database and no errors as well.
Here is my code:
controllers
public function edit($id)
{
$technicien=technicien::find($id);
$user = $technicien->user;
return view('technicien.edit',['technicien'=>$technicien])->with('user',$user);
}
public function update(Request $request, $id)
{
// do some request validation
$technicien=technicien::find($id);
$technicien->update($request->all());
$technicien->user->update($request->get('user'));
$user->nom = $request->update('nom');
return redirect('/technicien');
}
View
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Technicien</h1>
<form action="{{ route('technicien.update', $technicien->technicien ) }}" method="update">
{{csrf_field()}}
{{ method_field('PATCH') }}
<div class="form-group">
<label for="nom">Nom</label>
<input id="nom" type="text" class="form-control" name="user[nom]" value="{{$user->nom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control" name="user[prenom]" value="{{$user->prenom}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form-control" name="user[email]" value="{{$user->email}}" >
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name="moyenne_avis" class="form-control" value ="{{$technicien->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name="actif" class="form-control" value ="{{$technicien->actif}}" >
</div>
<div class="form-group">
<input type="submit" value="enregistrer" class="form-control btn btn-primary">
</div>
</div>
</form>
</div>
</div>
#endsection
route.php
Route::get('/technicien/{id}/edit', 'TechnicienController#edit');
Route::patch('/technicien/{id}', 'TechnicienController#update')-
>name('technicien.update');
You just need to pass parameters to update function.
Read docs
public function update(Request $request, $id)
{
$technicien=technicien::find($id);
$technicien->update($request->all());
$technicien->user->update([
'nom' => $request->nom,
'premon' => $request->premon,
'email' => $request->email
]);
return redirect('/technicien');
}
Also from the docs
You should define which model attributes you want
to make mass assignable. You may do this using the $fillable property
on the model.

How to insert values to table 'users' in laravel 5.2?

I want to insert employee details username,area to the table 'users'.
I have the following codes of CreateEmployeeController and
createemployee.blade.php view file.
When I click on the menu Create Employee is will shows the following error
QueryException in Connection.php line 662:
SQLSTATE[42000]: Syntax error or access violation: 1066 Table/alias: 'users' non unique (SQL: select * from users inner join users on users.id = users.users_id where users.deleted_at is null)
Controller file :
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Controllers\AdminController;
use App\CreateEmployee;
use App\Employee;
use App\Users;
class CreateEmployeeController extends AdminController
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
public function addemployee()
{
$employee = CreateEmployee::all();
$employee =CreateEmployee::join('users','users.id','=','users.users_id')->get();
return view('app.admin.employee.employee',compact('employee','users'));
}
public function employeesave(Request $request)
{
$title = 'Add Employee';
$employee = new Employee();
$employee->name=$request->employee_name;
$employee ->area = $request->area;
$employee->save();
Session::flash('flash_notification', array('level' => 'success', 'message' => 'employee created successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee');
}
public function updateemployee(Request $request)
{
Employee::where('id',$request->id)->update(array('name'=>$request->employee_name,'area'=>$request->area));
Session::flash('flash_notification', array('level' => 'success', 'message' => 'shop details updated successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee',array('id' => $request->id));
}
public function editemployee($id)
{
$employee = Employee::where('id',$id)->get();
return view('app.admin.employee.editemployee',compact('employee'));
}
public function deleteemployee($id)
{
$employee = Employee::where('id',$id)->get();
return view('app.admin.employee.delete',compact('employee'));
}
public function deleteconfirms($id)
{
$employee = Employee::where('id',$id)->delete();
Session::flash('flash_notification', array('level' => 'success', 'message' => 'customer deleted successfully'));
return Redirect::action('Admin\CreateEmployeeController#addemployee');
}
public function destroy($id)
{
//
}
}
//view file
#extends('app.admin.layouts.default')
{{-- Web site Title --}}
#section('title') {{{ trans('site/user.register') }}} :: #parent #stop
#section ('styles')
#parent
<style type="text/css">
</style>
#stop
{{-- Content --}}
#section('main')
#include('utils.vendor.flash.message')
<div class="row">
<div class="page-header">
<h2>Add Employee</h2>
</div>
</div>
<div class="container-fluid">
<div class="row">
#include('utils.errors.list')
<form class="form-horizontal" role="form" method="POST" action="{{ URL::to('admin/addemployee') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label">Employee Name</label>
<div class="col-md-2">
<input type="text" class="form-control" name="employee_name"
required>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label" for="religion">Password</label>
<div class="col-md-2">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" data-parsley-trigger="change" data-parsley-required="true" data-parsley-minlength="6" data-parsley-maxlength="14" required>
{!! $errors->first('cpassword', '<label class="control-label" for="cpassword">:message</label>')!!}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label" for="caste">Confirm Password</label>
<div class="col-md-2">
<input type="password" class="form-control" placeholder="Confirm Password" name="password_confirmation" id="password_confirmation" data-parsley-trigger="change" data-parsley-required="true" data-parsley-equalto="#password" data-parsley-minlength="6" data-parsley-maxlength="14" required>
{!! $errors->first('password_confirmation', '<label class="control-label" for="password_confirmation">:message</label>')!!}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="col-md-2 control-label">Area</label>
<div class="col-md-2">
<input type="text" class="form-control" name="area"
required placeholder="Area">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-2 col-md-offset-2">
<button type="submit" class="btn btn-primary">
Add
</button>
</div>
</div>
</form>
</div>
</div>
<div class="invoice-content">
<div class="table-responsive">
<div class="col-md-offset-2">
<table class="table table-invoice">
<thead>
<tr>
<th>Employee Name</th>
<th>Area</th>
</tr>
</thead>
</div>
</div>
<tbody>
#foreach($addemployee as $employee)
<tr>
<td>{{$employee->employee_name}}</td>
<td>{{$employee->area}}</td>
<td>
Edit
<a onclick="return confirm('Are you Sure you want to do this Action!'); style.backgroundColor='#84DFC1'; " href="employee/delete/{{$employee->id}}">delete</a>
</td>
</tr>
#endforeach
#if(!count($employee))
<tr><td>NO data found </td></tr>
#endif
</tbody>
</tbody>
</table>
{{--</div>--}}
{{--</div>--}}
{{--</div>--}}
</div>
</div>
#endsection
I can't get the full idea about your problem, but as upto me I understand that - You are using same table/column names in your join statement, you can do this as:
$employee = CreateEmployee::join('users', 'create_employees.id','=', 'users.employee_id')->get();
Hope this helps!

Resources