my question is about how to split this code. I have a registration form and it's saving function looks like this:
public function store(EntityRequestCreate $request)
{
$geoloc = new Geoloc;
$geoloc->lat = $request->input('lat');
$geoloc->lng = $request->input('lng');
$geoloc->slug = $request->input('name');
$geoloc->save();
$user_id = Auth::id();
$entity = new Entity;
$entity->name = $request->input('name');
$entity->type = $request->input('type');
$entity->email = $request->input('email');
$entity->tags = $request->input('tags');
$entity->_geoloc()->associate($geoloc);
$entity->save();
$entity_id = $entity->id;
$address = new Address;
$address->building_name = $request->input('building_name');
$address->address = $request->input('address');
$address->town = $request->input('town');
$address->postcode = $request->input('postcode');
$address->telephone = $request->input('telephone');
$address->entity_id = $entity_id;
$address->save();
$role = User::find($user_id);
$role->role = "2";
$role->save();
DB::table('entity_user')->insert(array('entity_id' => $entity_id, 'user_id' => $user_id));
$result = $geoloc->save();
$result2 = $entity->save();
$result3 = $address->save();
$result4 = $role->save();
if ($result && $result2 && $result3 && $result4) {
$data = $entity_id;
}
else {
$data = 'error';
}
return redirect('profile/entity');
}
As you see, it has a custom request and it is saving to 3 models, that way my controller code is far too long (having many other functions etc) Instead I want to move this code to a model, as my model so far has only relationships defined in it. However I don't exactly know how to call a model from controller, do I have to call it or it will do it automatically? Any other ideas on how to split the code?
You could use the models create method to make this code shorter and more readable.
For example:
$geoloc = Geoloc::create(
$request->only(['lat', 'lng', 'name'])
);
$entity = Entity::create(
$request->only(['name', 'type', 'email', 'tags])
);
$entity->_geoloc()->associate($geoloc);
$address = Address::create([
array_merge(
['entity_id' => $entity->id],
$request->only(['building_address', 'address', 'town'])
)
])
...
The create method will create an object from a given associated array. The only method on the request object will return an associated array with only the fields for the given keys.
Related
Just a quick question guys really thankful for everyone who can help.
How do I foreach loop inside create eloquent in laravel
Here is my code. I'm trying to get and match the answers for their respective survey questions
public function answer_survey(Request $request, $id)
{
$userId = Auth::user()->id;
$user = User::where('id', $userId)->first();
$userNectarPoint = UserNectarPoint::where('user_id', $userId)->first();
$survey = Survey::find($id);
$survey_questions = SurveyQuestion::where('survey_id', $survey->id)->get();
$current_nectarpt_value = $userNectarPoint->nectar_points;
$questionIds = $request->id;
$questions = $request->question;
$answers = $request->answer;
foreach ($answers as $answer) {
}
foreach ($survey_questions as $survey_question) {
$userAnsweredSurvey = new UserAnsweredSurvey;
$userAnsweredSurvey->user_id = $userId;
$userAnsweredSurvey->user_fullname = $user->first_name . ' ' . $user->middle_initial . ' ' . $user->family_name;
$userAnsweredSurvey->survey_id = $survey->id;
$userAnsweredSurvey->survey_title = $survey->title;
$userAnsweredSurvey->survey_question_id = $survey_question->id;
$userAnsweredSurvey->survey_question = $survey_question->question;
$userAnsweredSurvey->answer = $answer;
$userAnsweredSurvey->save();
}
$result_nectarpt = $current_nectarpt_value + $survey->reward_points;
$userNectarPoint->nectar_points = $result_nectarpt;
$userNectarPoint->save();
return back()->with('status', 'survey_done');
}
I'm trying to update an array with objects inside something like this, with the current code I have it only saves the first one, I know that's the problem but I don't know how to fix it
array (
0 =>
array (
'option' => 'new',
),
1 =>
array (
'option' => 'ewrwer',
),
),
This is my current code, the line in question is
$option = SurveyQuestionOption::where('survey_question_id', $preg->id)->first();
How do I fix this so it cycles through all in the array questionOptions instead of just the first one? I tried ->get() but then the ->save() doesn't work.
public function update(Request $request, $id)
{
DB::beginTransaction();
$preg = SurveyQuestion::findOrFail($id);
$preg->question = $request->question;
$preg->survey_section_id = $request->survey_section_id;
$preg->response_type_id = $request->response_type_id;
$preg->optional = $request->optional;
$preg->save();
$ids = [];
if ($request->get('questionOptions')) {
foreach ($request->get('questionOptions') as $item) {
$option = SurveyQuestionOption::where('survey_question_id', $preg->id)->first();
if (empty($option)) {
$option = new SurveyQuestionOption();
$option->survey_question_id = $preg->id;
}
$option->option = $item['option'];
$option->save();
}
}
if (count($ids) > 0) {
SurveyQuestionOption::whereNotIn('id', $ids)->where('survey_question_id', $preg->id)->delete();
}
DB::commit();
return back();
}
Basically, when you use get, you get a collection, so you can't really use save on it. you need to do a foreach loop, and save in that. i.e; like this;
$options = SurveyQuestionOption::where('survey_question_id', $preg->id)->get();
foreach($options as $option){
if (empty($option)) {
$option = new SurveyQuestionOption();
$option->survey_question_id = $preg->id;
}
$option->option = $item['option'];
$option->save();
}
Note that you can't save $options if you don't use a foreach loop, as you're not specifying which instance of the collection to save it in.
I have a little problem about update avatar pic of my user.
I have a polymorph relation table for Image and when i update info of my user profile and upload new avatar in my DB he create a new entry and not updated the current id of my table Images.
Table Images Id|path|Imageable_id|imageable_type|created_at
My UsersController method update
public function update($id){
$rules =[
/*'lastname' => 'min:3|string',
'firstname' => 'min:3|string',
'username'=> 'min:4|unique:users',
'mail' => ' email|unique:users',
'birthday' => 'date_format:d-m-Y|before:today',
'country'=>'min:3',
'type_street'=>'min:3',
'number'=>'min:1|numeric',
'street'=>'min:4|string',
'complementary_street'=>'min:2|string',
'town'=>'min:2|string',
'zip'=>'min:4|numeric',
'phone_home'=>'min:10|numeric',
'phone_mobile'=>'min:10|numeric',
'image_path'=>'image|max:1000|mimes:jpeg,jpg,png',*/
];
$validator = Validator::make(Input::all(),$rules);
if($validator->fails()){
return Redirect::to('/profil/'.$id)
->with('alert_error','Merci de corriger les erreurs');
}else{
$user = User::find($id);
$user->lastname = Input::get('lastname');
$user->firstname = Input::get('firstname');
$user->username = Input::get('username');
$user->mail = Input::get('mail');
$user->birthday = Input::get('birthday');
$user->adresse->type_street = Input::get('type_street');
$user->adresse->number = Input::get('number');
$user->adresse->street = Input::get('street');
$user->adresse->complementary_street = Input::get('complementary_street');
$user->adresse->town = Input::get('town');
$user->adresse->zip = Input::get('zip');
$user->adresse->country = Input::get('country');
$user->adresse->phone_home = Input::get('phone_home');
$user->adresse->phone_mobile = Input::get('phone_mobile');
if(Input::hasFile('avatar')){
$avatar = Image::find($id);
$file = Input::file('avatar');
$name = time().'-'.$file->getClientOriginalName();
$file = $file->move('img/avatar/', $name);
$input['path'] = 'img/avatar/'.$name;
$input['imageable_id'] = $user->id;
$input['imageable_type'] = 'User';
$avatar = new Image($input);
$avatar->save();
}
$user->adresse->save();
return Redirect::to('/profil/'.$id)
->with('alert_success','Modification sauvegardé avec succès');
}
}
Can you help me for this feature i don't understand why no updated of current id of my entry and create new One .
Thank's
You're overwriting your find $avatar = Image::find($id); with a new instance $avatar = new Image($input);
I have inserted a row in db using laravel eloquent method. See the code below,
public function store() {
$language = new languages;
$language -> languages = Input::get('languages');
$language -> created_by = Auth::user()->id;
$language -> updated_by = Auth::user()->id;
if( $language -> save() ) {
$returnData = languages::where("id","=",$language -> id) -> get();
$data = array ("message" => 'Language added successfully',"data" => $returnData );
$response = Response::json($data,200);
return $response;
}
}
I want the last inserted row from the table, but my response contains empty data. Please guide the right method of getting the data?
Almost there: you would need to call first() to get just one row. But, since you're using eloquent, you can call the find() method:
public function store() {
$language = new languages;
$language->languages = Input::get('languages');
$language->created_by = Auth::user()->id;
$language->updated_by = Auth::user()->id;
if($language->save()) {
$returnData = $language->find($language->id);
$data = array ("message" => 'Language added successfully',"data" => $returnData );
$response = Response::json($data,200);
return $response;
}
}
I'm stuck with the following problem:
I have a class CartItem. I want to store array of objects of CartItem in session (actually i'm implementing a shopping cart).
class CartItem extends AppModel{
var $name = "CartItem";
var $useTable = false;
}
I tried this:
function addToCart(){
$this->loadModel("Cart");
$this->layout = false;
$this->render(false);
$cart = array();
$tempcart = unserialize($this->Session->read("cart"));
if(isset($tempcart)){
$cart = $tempcart;
}
$productId = $this->request->data("id");
if(!$this->existsInCart($cart, $productId)){
$cartItem = new Cart();
$cartItem->productId = $productId;
$cartItem->createdAt = date();
$cart[] = $cartItem;
$this->Session->write("cart", serialize($cart));
echo "added";
}
else
echo "duplicate";
}
I think I'm writing these lines wrong:
$tempcart = unserialize($this->Session->read("cart"));
$this->Session->write("cart", serialize($cart));
as I'm not getting data from the session.
You are trying to add the whole Cart object to the session.
You should just add an array, like
$cart[] = array(
'productId' => $productId,
'createdAt' => date('Y-m-d H:i:s')
);
If you need to add an object to a session, you can use __sleep and __wakeup magic functions but I think in this case it's better to just add only the product id and date to the session.