I am able to save products into my groups using the group id using the save function
but now i want to do that using an excel file. I am having issues with how to do that. Any help will be appreciated. Thank you.
Controller
public function save($id, Request $request)
{
$group = Group::whereId($id)->firstorFail();
$product = new Product(array(
'name' => $request->get('name'),
'price' => $request->get('price'),
));
$group->products()->save($product);
}
public function import($id, Request $request)
{
$group = Group::whereId($id)->firstorFail();
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader)
{
})->get();
if(!empty($data) && $data->count())
{
foreach ($data->toArray() as $row)
{
if(!empty($row))
{
$dataArray[] =
[
'name' => $row['name'],
'price' => $row['price'],
];
}
}
if(!empty($dataArray))
{
Item::insert($dataArray);
}
}
}
}
Route
Route::post('import/{id?}', 'ItemController#import');
Model for Product
Product
public function groups()
{
return $this->belongsToMany('App\Group','group_product','product_id','group_id')
->withTimestamps();
}
Model for group
Group
public function products()
{
return $this->belongsToMany('App\Product','group_product','group_id','product_id')
}
You need saveMany
$dataArray[] =
new App\Product([
'name' => $row['name'],
'price' => $row['price'],
]);
$group->products()->saveMany($dataArray);
Related
I want to save array of data using polymorphic relation one to many.
I have the following Models.
schedule task model
class ScheduleTask extends Model
{
protected $guarded = [];
public function taskable()
{
return $this->morph To(__FUNCTION__, 'taskable_type', 'taskable_id');
}
}
prelimstest model
class PrelimsTest extends Model
{
public function tasks()
{
return $this->morph Many(Schedule Task::class, 'taskable');
}
}
maintest model
class MainsTest extends Model
{
public function tasks()
{
return $this->morphMany(ScheduleTask::class, 'taskable');
}
}
video model
class Video extends Model
{
public function tasks()
{
return $this->morphMany(ScheduleTask::class, 'taskable');
}
}
And my controller
class ScheduleController extends Controller
{
public function store(Request $request)
{
$data = array();
foreach ($prelims_id as $key => $value) {
$data[] = [
'course_id' => $prelims_course_id[$key],
'status' => 'incomplete',
'schedule_id' => 1
];
$prelims_save = PrelimsTest::find($value);
}
$prelims_save->tasks()->createMany($data);
$data2 = array();
foreach ($mains_id as $key2 => $value2) {
$data2[] = [
'course_id' => $mains_course_id[$key2],
'status' => 'incomplete',
'schedule_id' => 1
];
$mains_save = MainsTest::find($value2);
}
$mains_save->tasks()->createMany($data2);
$data3 = array();
foreach ($videos_id as $key3 => $value3) {
$data3[] = [
'course_id' => $videos_course_id[$key3],
'status' => 'incomplete',
'schedule_id' => 1
];
$videos_save = Video::find($value3);
}
$videos_save->tasks()->createMany($data3);
}
}
My problem is while i'm saving taskable_id enters last value of array.
Does anyone know how to solve this part, that I can save the polymorphic relation?
Thanks in advance.
I want to use unique validation in Lavavel 8 but the problem is that it doesn't allow me to update when I don't change the name field
my update code on my TemplateController
public function updateTemplate($templateId, TemplateRequest $templateRequest)
{
$thumbnailUrl = $this->templateService->updateThumbnail($templateRequest);
$this->templateRepository->updateTemplateInfo($templateRequest, $templateId, $thumbnailUrl);
return redirect()->route('templates.list.show', [$templateId])
->with(["message" => __('templates.edit.success')]);
}
this is my UpdateTemplateInfo at TemplateRepository
public function updateTemplateInfo($request, $templateId, $thumbnail)
{
$template = $this->getTemplate($templateId);
$template->name = $request->name;
$template->thumbnail = $thumbnail;
$template->business_type_id = $request->business_type;
$template->update();
}
and this is my TemplateRequest
public function rules()
{
return [
'name' => 'required|unique:templates',
'business_type' => 'required'
];
}
this is the method in web.php
Route::patch('/list/{templateId}/update', 'TemplateController#updateTemplate')->name('templates.list.update');
When I try to update without change the name field, the validator fails
If you don't want to create a separate request for post and put you can do something like this...
public function rules() {
$rules = [
'name' => 'required|unique:templates,name',
'business_type' => 'required'
];
if ($this->method() === 'PUT') {
$rules['name'] .= ',' . $this->route('templateId');
}
return $rules;
}
you should create a new request class for the update case
public function rules()
{
return [
'name' => "required|unique:templates,name,{$this->name}",
'business_type' => 'required'
];
}
or you can edit the current request class to this:
public function rules()
{
$rules = [
'business_type' => 'required'
];
if (request()->method == 'PUT') {
$rules['name'] = "required|unique:templates,name,{$this->name}";
} else {
$rules['name'] = 'required|unique:templates';
}
return $rules;
}
Respected Sir/Ma'am
I have record in below format and want to save this into
database,the property of this particular object is not similar often, It's changeable,
Sometime it could be more and sometime it could be less
the property of this object is changeable,Sometime it could be
more and sometime it could be less
{
"name":"nabnit jha",
"email":"028nabnit#gmail.com",
"password":"123456",
"c_password":"123456",
"imgUrl":"sonujha.jpg"
}
Simply i will do this if object property is not dynamic
public function insert($data, $modelName)
{
$modelName->name = $data->name;
$modelName->email = $data->email;
$modelName->password = $data->password;
$modelName->img_url = $data->imgUrl;
$modelName->save();
return response()->json([
'message' => "Record Inserted Successfully"
]);
}
what I DO In dynamic case, I use this but not work please help me
public function insert($data, $modelName)
{
foreach ($data as $key => $value) {
$modelName->$key = $value;
}
$modelName->save();
return response()->json([
'message' => "Record Inserted Successfully"
]);
}
data must be array
public function insert($data, $modelName)
{
$modelName->fill($data)->save(); // or use forceFill()
return response()->json([
'message' => "Record Inserted Successfully"
]);
}
If someone has same issue then take $data = $request->input() and use foreach loop
For more detail follow bellow step
Step 1
class SignUp extends Controller
{
//
protected $users;
public function __construct(Crud $crud)
{
$this->users = $crud;
$this->Model = new RegisterSignUp;
}
public function singleUpload(Request $request)
{
$validatedData = Validator::make(
$request->all(),
[
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password'
]
);
if ($validatedData->fails()) {
return response()->json([
'message' => "Validation Error"
]);
}
$model_name = $this->getModel();
$result = $this->users->insert($request->input(), $model_name);
return $result;
return response()->json([
'message' => "Record Inserted Successfully"
]);
}
public function getModel()
{
return $this->Model;
}
}
Step 2
public function insert($data, $modelName)
{
foreach ($data as $key => $value) {
if ($key != 'c_password') {
$modelName->$key = $value;
}
}
$modelName->save();
return response()->json([
'message' => "Record Inserted Successfully"
]);
}
Can someone help me with this Laravel problem?
I get Error Call to a member function update() on boolean, when I edit and update Image for an ad.
So when I create a new Ad the image will store but when updating the Ad with a new image the old image stays and I get this error for this line in storeImage.
private function storeImage($ad){
if (request()->has('image')) {
$ad->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/' . $ad->image))->fit(300, 300, null, 'top-left');
$image->save();
}
}
This is my AdsController
public function edit($id)
{
$ad = Ad::find($id);
return view('ads.edit_ad', compact('ad', 'id'));
}
public function update(Request $request, $id)
{
$ad = Ad::find($id);
$user_id = Auth::user()->id;
$rules = [
'ad_title' => 'required',
'ad_description' => 'required',
'purpose' => 'required',
'image' => 'sometimes|file|image|max:5000',
];
$this->validate($request, $rules);
$title = $request->ad_title;
$is_negotialble = $request->negotiable ? $request->negotiable : 0;
$data = [
'title' => $request->ad_title,
'description' => $request->ad_description,
'type' => $request->type,
'price' => $request->price,
'purpose' => $request->purpose,
'address' => $request->address,
'user_id' => $user_id,
];
$updated_ad = $ad->update($data);
if ($updated_ad){
$this->storeImage($updated_ad);
}
return redirect()->back()->with('success','Ad Updated');
}
public function destroy(Ad $ad)
{
$ad->delete();
return redirect()->back()->with('success','Ad Deleted');
}
/**
* Listing
*/
public function listing(Request $request){
$ads = Ad::all();
$roles = Role::all();
return view('listing', compact('ads'));
}
public function myAds(){
$user = Auth::user();
$ads = $user->ads()->orderBy('id', 'desc')->paginate(20);
return view('ads.my_ads', compact('ads'));
}
private function storeImage($ad){
if (request()->has('image')) {
$ad->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/' . $ad->image))->fit(300, 300, null, 'top-left');
$image->save();
}
}
At the bottom of your update() function, try to change this:
if ($updated_ad){
$this->storeImage($updated_ad);
}
to this:
if ($updated_ad){
$this->storeImage($ad);
}
The Eloquent models update() function returns a boolean of whether the update completed successfully. After running the update() function on the $ad variable, it is mutated and contains the updated data, and you can use it as an argument in your storeImage() function.
In my model I have return below function for get record id
function getLastInserted()
{
$query = $this->db->select("MAX(`UserID`)+1 as userid")->get("registeration");
return $query->result();
}
Now I want to pass that ID to mycontroller for record insertion
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
Now I want to access model function in controller and pass record id in data function How I do ??
set return in model and in controller write
$insert_id=$this->db->insert_id();
In Controller load your model first using
$this->load->model('model_name');
Then call to model's getLastInserted() function.
$ID = $this->model_name->getLastInserted();//you will get id here
In model return $query->row()->userid; insead return of $query->result().
Then modify the controller:
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $this->model_name->getLastInserted(),
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
hi i worked out the solution on last inserted id dear here the code:
controller:
function sample() {
$sid=$this->adminmodel->getLastInserted();
$this->adminmodel->newregistration( $sid);
}
model:
function getLastInserted()
{
$query = $query = $this->db->select('id')->order_by('id','desc')->limit(1)->get('employee_outs')->row('id');
return $query;
}
model:
public function newregistration($sid)
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $sid,
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}