Updating Item from Pivot Table Fields - laravel

I have item_color and item_size pivot tables, and would like to update my size and color fields using their field values, and an not exactly sure where to start. Here's what I have so far.
ItemSize.php
<?php
class ItemSize extends \Eloquent
{
protected $table = 'item_size';
protected $fillable = [];
public function item() {
return $this->belongsTo('Item');
}
}
ItemColor.php
<?php
class ItemColor extends \Eloquent
{
protected $table = 'item_color';
protected $fillable = [];
public function item() {
return $this->belongsTo('Item');
}
}
VendorController
public function postVendorUpdateItems ($id)
{
$input = Input::all();
$items = Item::find($id);
$validator = Validator::make($input,
[ 'item_name' => 'max:50',
'item_id' => 'max:50',
'normalprice' => 'numeric',
'karmaprice' => 'numeric',
'asin' => 'max:50',
]);
if($validator->passes())
{
$items->name = $input['item_name'];
$items->normalprice = $input['normalprice'];
$items->karmaprice = $input['karmaprice'];
$items->asin = $input['asin'];
$items->id = $input['item_id'];
$items->save();
return Redirect::route('account-vendor-index')
->with('global', 'You have updated your item.');
}
return Redirect::route('account-vendor-index')
->withErrors($validator)
->with('global', 'Your item could not be updated.');
}
View
<form class="form-horizontal" role="form" method="post" action="{{url('account/vendor/update/items')}}/{{$item->id}}">
<input type="hidden" id="brand_id" placeholder="brand_id" value="{{$brand->id}}" name="brand_id">
<input type="hidden" id="item_id" placeholder="item_id" value="{{$item->id}}" name="item_id">
<div class="form-group">
<label for="colors" class="col-xs-3 control-label">Colors</label>
<div class="col-xs-6">
<input type="text" class="form-control input-sm" id="colors" name="colors" placeholder="#foreach($item->colors as $color){{$color->color}}#endforeach" value="">
</div>
<button type="" class="btn btn-primary btn-sm">Add color</button>
<div class="clear"></div>
<div class="col-xs-offset-3 showColors">
#foreach($item->colors as $color)
{{$color->color}}
#endforeach
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Sizes</label>
<div class="col-xs-9">
<select id="selectSizes" multiple="multiple" class="form-control selectSizes" name="sizes">
<option value="XS (0-2)">XS (0-2)</option>
<option value="S (4-6)">S (4-6)</option>
<option value="M (8-10)">M (8-10)</option>
<option value="L (12-14)">L (12-14)</option>
<option value="XL (16-18)">XL (16-18)</option>
<option value="XXL (20-22)">XXL (20-22)</option>
</select>
</div>
</div>
<div class="form-group bot-0">
<div class="col-xs-offset-3 col-xs-9">
<button type="submit" class="btn btn-main btn-sm">Save changes</button>
</div>
</div>
</form>

item_size and item_color are not pivot tables. They are in fact a one to one relationship with your schema. If want you truly want are pivot tables, you need to define a color and a size table, then create a many-to-many relationship. See here: https://laravel.com/docs/master/eloquent-relationships
Then to update related models, you'll use the attach, sync, detach, etc. methods.
Also, what version of Laravel are you running? If you're running 5.1+ look into form request validation. See here: https://laravel.com/docs/master/validation#form-request-validation
That will remove all the validation logic from your controller.

Related

Laravel Update DB with array from views

i'm doing a simple project but having some difficulties with updating my database with values that I get from a form. The project is having a list of movies and when you click on one it would take you to a page with more details. Theres a button which you can update the details of that movie. I'm trying save whatever details are made to the relevant index of the table using the id. I can't seem to get it to work though. I did something similar when creating a new entry but having some difficulty updating the values of a specific movie/page. Thanks for any help!
Route:
Route::get('catalog', 'App\Http\Controllers\CatalogController#getIndex');
Route::get('catalog/show/{id}', 'App\Http\Controllers\CatalogController#getShow');
Route::get('catalog/create', 'App\Http\Controllers\CatalogController#getCreate');
Route::get('catalog/edit/{id}', 'App\Http\Controllers\CatalogController#getEdit');
Route::post('catalog/create', 'App\Http\Controllers\CatalogController#postCreate');
Route::put('catalog/edit/{id}','App\Http\Controllers\CatalogController#putEdit');
Controller:
public function getEdit($id)
{
return view('catalog.edit', ['arrayPeliculas' => Movie::all()]);
}
public function getCreate()
{
return view('catalog.create');
}
public function postCreate(Request $request)
{
$Movie = new Movie;
$Movie->title = $request->title;
$Movie->year = $request->year;
$Movie->director = $request->director;
$Movie->poster = $request->poster;
$Movie->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
public function putEdit(Request $request, $id)
{
$Movie = new Movie;
$Movie[$id]->title = $request->title;
$Movie[$id]->year = $request->year;
$Movie[$id]->director = $request->director;
$Movie[$id]->poster = $request->poster;
$Movie[$id]->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
Edit page:
<form method="PUT">
{{ method_field('PUT') }}
{{-- TODO: Protección contra CSRF --}}
{{ csrf_field() }}
<div class="form-group">
<label for="modificar">Modificar Pelicula</label>
<input type="text" name="title" id="title" class="form-control" value="{{ $arrayPeliculas[$id]->title }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el año --}}
<label for="Año">Año</label>
<input type="text" name="year" id="year" class="form-control" value="{{ $arrayPeliculas[$id]->year }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el director --}}
<label for="Director">Director</label>
<input type="text" name="director" id="directo" class="form-control" value="{{ $arrayPeliculas[$id]->director }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el poster --}}
<label for="Poster">Poster</label>
<input type="text" name="poster" id="poster" class="form-control" value="{{ $arrayPeliculas[$id]->poster }}">
</div>
<div class="form-group">
<label for="synopsis">Resumen</label>
<textarea name="synopsis" id="synopsis" class="form-control" rows="3" >{{ $arrayPeliculas[$id]->synopsis }}"</textarea>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary" style="padding:8px 100px;margin-top:25px;">
Añadir película
</button>
</div>
</form>
I tried a few other things like->update but I can't seem to get it to work properly.
To update an existing model, first find() it.
public function putEdit(Request $request, $id)
{
$Movie = Movie::find($id);
$Movie->title = $request->title;
$Movie->year = $request->year;
$Movie->director = $request->director;
$Movie->poster = $request->poster;
$Movie->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
Using the update function should also work then:
public function putEdit(Request $request, $id)
{
$Movie = Movie::find($id);
$Movie->update([
'title' => $request->title,
'year' => $request->year,
'director' => $request->director,
'poster' => $request->poster,
'synopsis' => $request->synopsis,
]);
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
You could really simplify it with some Laravel magic like Route Model Binding...
Route::put('catalog/edit/{movie}','App\Http\Controllers\CatalogController#putEdit');
...
public function putEdit(Request $request, Movie $movie)
{
$movie->update($request->all());
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}

Laravel - How to Make Lesson aggregate score not more than course max score

I am developing a web application on Student Course Management using Laravel-5.8
Models
class Lesson extends Model
{
protected $table = 'Lessons';
protected $fillable = [
'lesson_name',
'course_id',
'student_id',
'score_obtained',
];
public function gradelevel()
{
return $this->belongsTo('App\Models\Course','course_id');
}
public function student()
{
return $this->belongsTo('App\Models\Student','student_id');
}
}
class Course extends Model
{
protected $table = 'courses';
protected $fillable = [
'course_code',
'course_name',
'max_score',
];
}
Controller
class LessonController extends Controller
{
public function create()
{
$courses = Course::all();
$students = Student::all();
return view('lessons.create')->with('courses', $courses)->with('students', $students);
}
public function store(StoreLessonRequest $request)
{
try {
$lesson = Lesson::create([
'lesson_name' => $request->lesson_name,
'course_id' => $request->course_id,
'lesson_id' => $request->lesson_id,
'score_obtained' => $request->score_obtained,
]);
Session::flash('success', 'Lesson is created successfully');
return redirect()->route('lessons.index');
} catch (Exception $exception) {
Session::flash('danger', 'Lesson creation failed!');
return redirect()->route('lessons.index');
}
}
}
create.blade
<form action="{{route('lessons.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Course</label>
<select class="form-control select2bs4" data-placeholder="Choose Course" tabindex="1" name="course_id" style="width: 100%;">>
<option value="">Select Course</option>
#if($courses->count() > 0)
#foreach($courses as $course)
<option value="{{$course->id}}">{{$course->course_name}}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Student</label>
<select class="form-control select2bs4" data-placeholder="Choose Course" tabindex="1" name="student_id" style="width: 100%;">>
<option value="">Select Student</option>
#if($students->count() > 0)
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->student_name}}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Lesson<span style="color:red;">*</span></label>
<input type="text" name="lesson_name" placeholder="Enter lesson here" class="form-control" value="{{old('lesson_name')}}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Obtained Score<span style="color:red;">*</span></label>
<input type="text" name="score_obtained" placeholder="Enter score obtained here" class="form-control" value="{{old('score_obtained')}}">
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" id="submit_create" class="btn btn-primary">Score</button>
</div>
</form>
Each core have maximum score allocated and this is done at the setting. For each course, students have lesson and scores are obtained for each lesson.
What I want to achieve is that on the lesson create form, what student score_obtained are being entered the application should sum up all the scores (from the lesson table and the just entered one) the student obtained for that particular course including the one in the textbox, if its more that what is in the max_score in the courses table for that particular course the application should display a message and shouldn't allow the user to submit.
How do I achieve this?
Thank you.
In store method, you can write below code:
$maxScore = Course::find($request->course_id)->max_score;
$scoresObtained = Lession::where('course_id' , $request->course_id)->sum('score_obtained');
$totalScore = intval($scoresObtained) + intval($request->score_obtained);
if($totalScore > $maxScore)
{
return redirect()->back()->withErrors([__('Total score exceeds max score for selected course')]);
}
You can use floatval() in place of intval() in case your scores are in decimals

"Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)"

When I am editing my post then I am prompted with the following error message
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'content' => 'required',
'category_id' => 'required'
]);
$post = Post::find($id);
if($request->hasFile('featured'))
{
$featured = $request->featured;
$featured_new_name = time() . $featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$post->featured = 'uploads/posts/'.$featured_new_name;
}
$post->title = $request->title;
$post->content = $request->content;
$post->category_id = $request->category_id;
$post->save();
Session::flash('success', 'Post updated successfully.');
return redirect()->route('posts');
}
and blade code
<div class="form-group">
Select a Category
#foreach($categories as $category)
id}}"
#if($post->$category->id == $category->name)
selected
#endif
{{$category->name}}
#endforeach
List item
My Post method for post and category
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories'; // here set table's name
protected $primaryKey = 'id'; // here set table's primary Key field name
protected $fillable = ['id']; // here set all table's fields name
public function posts()
{
return $this->hasMany('App\Post');
}
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
public function category()
{
return $this->belongsTo('App/Category');
}
public function getFeaturedAttribute($featured)
{
return asset($featured);
}
use SoftDeletes;
protected $dates=['deleted_at'];
protected $fillable=['title','content','category_id','featured','slug'];
}
}
Edit.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header bg-info">
<div class="text-center">
<h4 class="m-b-0 text-white">
<div class="panel panel-default">
<div class="panel-heading">
Edit Post:{{$post->title}}
</div>
<div class="panel-body">
<form action="{{route('post.update', ['id'=>$post->id])}} " method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for ="title">Title</label>
<input type="text" name="title" class="form-control" value="{{$post->title}}">
</div>
<div class="form-group">
<label for ="featured">Featured image</label> <input type="file" name="featured" class="form-control">
</div>
<div class="form-group">
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for ="content">Content</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$post->content}}</textarea>
</div>
<div class="form-group">
<div class="text-center">
<button class="btn btn-success" type="submit"> Update Post</button>
</div>
</div>
</form>
</div>
</div>
</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Row -->
#stop
Controller...
public function store(Request $request)
{
$this->validate($request, [
'title' =>'required',
'featured'=>'required|mimes:jpeg,pdf,docx,png:5000',
'file'=>'required|mimes:jpeg,pdf,docx,png:5000',
'content'=>'required',
'category_id'=>'required',
]);
$featured= $request->featured;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$file=$request->file;
$file_name=time().$file->getClientOriginalName();
$file->move('uploads/posts', $file_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'featured'=>'uploads/posts/'. $featured_new_name,
'file'=>'uploads/posts'. $file_name,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
]);
Session::flash('success', 'New Blog has been Published on Website for Particular Menu');
return redirect()->back();
}
This the area in your blade where you are getting the issue:
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
Where are you fetching and providing $categories to this blade template? I mean the controller method which loads the edit blade?
Can you post that code as well?
And please update your question instead of posting answers.

Laravel 4 - Update many to many

I am currently trying to amend an update page which features a many to many relationship. It updates to my database perfectly, however all I'm trying to achieve now is to actually show the already selected items in my multiple select list in my view.
It currently just shows the entire list of oilgas jobs, just not the currently selected ones which should come from the query in some way.
So, it currently looks like this:
I need it to look like this, if Instrument Technician was previously chosen.
The associated files are as follows:
MODELS
OilGasJob.php
<?php
class OilGasJob extends \Eloquent {
protected $table = 'oilgasjobs';
public function industryjobs()
{
return $this->belongsToMany('IndustryJob');
}
}
IndustryJob.php
<?php
class IndustryJob extends \Eloquent {
protected $table = 'industryjobs';
public function oilgasjobs()
{
return $this->belongsToMany('OilGasJob');
}
}
CONTROLLER (CREATE PAGE AND STORE)
public function edit($id)
{
$industryjob = IndustryJob::find($id);
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This division job is not valid');
}
View::share('page_title', 'Edit Division Job');
return View::make('admin/industry-jobs/edit')->with('industryjob',$industryjob);
}
public function update($id)
{
$rules = array(
'job_title' => 'Required|Min:3|Max:80'
);
$validation = Validator::make(Input::all(), $rules);
If ($validation->fails())
{
return Redirect::back()->withErrors($validation);
} else {
$industryjob = IndustryJob::find($id);
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This divison job is not valid');
}
View::share('page_title', 'Edit Division Job');
$industryjob->job_title = Input::get('job_title');
$industryjob->slug = Str::slug(Input::get('job_title'));
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
$industryjob->save();
$industryjob->oilgasjobs()->sync(Input::get('oilgasjobs'));
return Redirect::to('/admin/industry-jobs')->with('message', 'Division Job updated successfully');
}
}
VIEW
{{ Form::open(array('url' => URL::to('admin/industry-jobs/edit/'.$industryjob->id), 'class'=>'form-horizontal', 'method' => 'POST')) }}
<div class="form-group">
<label class="col-md-2 control-label" for="industry_name">Job Title (*)</label>
<div class="col-md-10">
<input class="form-control" type="text" name="job_title" id="job_title" value="{{ $industryjob->job_title }}" />
</div>
</div>
<!-- Industry Type -->
<div class="form-group">
<label class="col-md-2 control-label" for="body">Related Jobs in Oil & Gas</label>
<div class="col-md-10">
<select name="oilgasjobs[]" id="oilgasjobs[]" size="6" class="form-control" multiple>
#foreach(OilGasJob::orderBy('job_title', 'ASC')->get() as $oilgasjob)
<option value="{{ $oilgasjob->id }}" >{{ $oilgasjob->job_title }}</option>
#endforeach
</select>
</div>
</div>
<!-- ./ Industry Type -->
<!-- Form Actions -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-success">Update Job</button>
</div>
</div>
<!-- ./ form actions -->
{{ Form::close() }}
In edit method add this code:
// ...
$linkedOilgasjob = DB::table('oilgasjob_industryjob')->lists('oilgasjob_id');
return View::make('admin/industry-jobs/edit'
,compact('industryjob')
,compact('linkedOilgasjob'));
Then in your view
<option value="{{ $oilgasjob->id }}" {{ in_array($oilgasjob->id,linkedOilgasjob) ? "selected='selected'" : "" }} >
{{ $oilgasjob->job_title }}
</option>
CONTROLLER
public function edit($id)
{
$data['industryjob'] = IndustryJob::find($id);
$data['oilgasjobs'] = DB::table('industry_job_oil_gas_job')->where('industry_job_id','=',$id)->lists('oil_gas_job_id');
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This division job is not valid');
}
View::share('page_title', 'Edit Division Job');
return View::make('admin/industry-jobs/edit', $data);
}
VIEW
<select name="oilgasjobs[]" id="oilgasjobs[]" size="6" class="form-control" multiple>
#foreach(OilGasJob::orderBy('job_title', 'ASC')->get() as $oilgasjob)
<?php
$selected = "";
if(in_array($oilgasjob->id, $oilgasjobs))
$selected = "selected";
?>
<option value="{{ $oilgasjob->id }}" <?php echo $selected; ?>>{{ $oilgasjob->job_title }}</option>
#endforeach
</select>

Eloquent create not working in laravel

I am new to laravel, so I face a problem in creating a post.
Here is my route:
Route::post('savepost', 'PostsController#savepost');
Here are my createpost.blade.php
#include('header')
<div class="container">
<!-- Main component for a primary marketing message or call to action -->
<div class="jumbotron">
<h3>Create New Post</h3>
<form action="savepost" class="form-horizontal" method="post" role="form">
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label">Post Title</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="title" id="inputEmail3" placeholder="Enter New Title">
</div>
#if($errors->has('title'))
<p class="alert alert-danger"><strong>oopps! </strong>{{ $errors->first('title') }} </p>
#endif
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-4 control-label">Post Description</label>
<div class="col-sm-8">
<textarea name="description"></textarea>
</div>
#if($errors->has('description'))
<p class="alert alert-danger"><strong>oopps! </strong>{{ $errors->first('description') }} </p>
#endif
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<input type="submit" class="btn btn-default" value="Save Post">
</div>
</div>
</form>
</div>
</div> <!-- /container -->
#include('footer')
Here are my PostsController
class PostsController extends BaseController{
public function createpost(){
return View::make('createpost');
}
public function savepost(){
$input = Input::all();
$validation = Validator::make($input, Posts::$rules);
if ($validation->passes())
{
Posts::create(array(
'title'=>Input::get('title'),
'description'=>Input::get('description')
));
}
else{
return Redirect::route('createpost')->withErrors($validation);
}
}
}
Here are my Model:
class Posts extends Eloquent {
protected $guarded = array();
protected $fillable = array('name', 'description');
protected $table = 'posts';
public static $rules = array(
'title' => 'required|min:5',
'description' => 'required'
);
}
and here are my posts database
id title description url date
please help me
Your posts table is missing the default laravel timestamps. Either turn them off in your model by doing:
public $timestamps = false;
Or add them to your posts table:
alter table posts add created_at datetime NOT NULL
alter table posts add updated_at datetime
Or create your own timestamps in your model. I see you have a date column, so you can do something like:
const CREATED_AT = 'date';
You can't use both fillable and guarded.
Of course, you should use either $fillable or $guarded - not both.
https://laravel.com/docs/5.3/eloquent#mass-assignment

Resources