How to make a validation in 5.2? - laravel-5

Please can any one give a idea about this type validation.
public function joinclass()
{
if($class_code = $request->get('class_code');
$classroom = classroomModel::where('class_code',$class_code)->first();
{
$class = new joinclass();
$class -> user_id = Auth::user()->id;
$class -> class_code = $request['class_code'];
$class -> save();
}else if{
Flash::message('Your code is not found in databse');
}elseif($classroom = joinclass::where('class_code',$class_code)->first();){
Flash::message('You are already in this classroom');
}
}
What is the write formet for this code and this type condition.

You can use Validator class to validate the requests.
Here's how:
public function joinclass(Request $request)
{
//Create a Validator for your request
$validator = Validator::make($request->all(), [
'class_code' => 'required',// use exists validation to validate if an entry exists in the table with value provided "exists:table,column"
//other required validations
]);
//validate the request
if ($validator->fails()) {
//if validation fails return the error
return Redirect::back()
->withErrors($validator);
}
else{
//if validation passes
$classroom = classroomModel::where('class_code',$class_code)->first();
if($classroom = joinclass::where('class_code',$class_code)->first();){
Flash::message('You are already in this classroom');
}else{
$class = new joinclass();
$class -> user_id = Auth::user()->id;
$class -> class_code = $request['class_code'];
$class -> save();
}
}
}

Related

Laravel returns old model after update

When i store a new record, Laravel returns the new record. Everything works fine.
When i update a record, Laravel returns the old record. I like to return the updated record.
Controller
public function store(StoreProjectRequest $request)
{
$data = $this->repo->create( $request->all());
return response()->json(new ProjectResource($data));
}
public function update(UpdateProjectRequest $request, Project $project)
{
$data = $this->repo->update($project, $request->all());
return response()->json(new ProjectResource($data));
}
Repository
public function create( $data)
{
$this->model->name = $data['name'];
$this->model->description = $data['description'];
$this->model->sales_order_id = $data['sales_order_id'] ? $data['sales_order_id'] : NULL;
$this->model->project_leader_id = $data['project_leader_id'];
$this->model->project_type_id = $data['project_type_id'];
$this->model->project_status_id = $data['project_status_id'];
$this->model->creator_id = Auth()->id();
$this->model->save();
return $this->model;
}
public function update($model, $data)
{
$model->name = $data['name'];
$model->description = $data['description'];
$model->sales_order_id = $data['sales_order_id'];
$model->project_leader_id = $data['project_leader_id'];
$model->project_type_id = $data['project_type_id'];
$model->project_status_id = $data['project_status_id'];
$model->save();
return $model;
}
When i add $data = Project::find($project->id)i receive the updated model.
But is this the only way?
The reason the $data is returning as the old data is because it still stores the data from when the variable was created. When you call $data->fresh() it will go fetch the new data and return it. Does that make sense?

Not updating database and not throwing error in laravel

I have an issue while updating the user. When I try to update the user after clicking the save button then it redirect me to the same page and not throwing me any error but also its not updating anything in the database. Below is my code. I have no idea what's going on here. Help me :)
Controller
public function update(ReportRequest $request, $id)
{
$report = Report::findOrFail($id);
$input = $request->all();
if ($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file' => $name]);
$input['photo_id'] = $photo->id;
}
$report->update($input);
return redirect()->back();
}
Route
Route::resource('admin/reports', 'ReportController', ['names'=>[
'index'=>'admin.reports.index',
'create'=>'admin.reports.create',
'edit'=>'admin.reports.edit',
]]);
Models
class Report extends Model
{
protected $fillable = [
'student_id',
'student_name',
'class_id',
'subject',
'teacher_name',
'report_categories_id',
'total_marks',
'obtained_marks',
'percentage',
'position',
'photo_id',
];
public function photo() {
return $this->belongsTo('App\Photo');
}
public function studentsClass() {
return $this->belongsTo('App\StudentsClass', 'class_id');
}
public function student() {
return $this->belongsToMany('App\Student');
}
}
Make sure you have your $fillable properties in your Photo and Report models, otherwise the create() and update() methods won't work as expected.
Check the $fillable fields in the Model as above. If the error persists check your laravel log on storage/logs/laravel.log.
In controller:
public function update(ReportRequest $request, $id){
$report = Report::findOrFail($id);
$input = $request->all();
try{
if ($request->photo_id != '') {
$path = 'images/';
$file = $request->photo_id;
$name = time() . $file->getClientOriginalName();
$file->move($path, $name);
$photo = Photo::create(['file' => $name]);
$report->update(['photo_id' => $photo->id]);
}
return redirect()->back();
}catch(\Exception $e){
return redirect()->back()->with('error_message', $e->getMessage());
}
}

laravel Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::save() must be of the type array, object given

I have an entity and each entity has an address.
I have 2 tables with relationship such as:
Entity:
protected $table = 'entities';
public $timestamps = true;
use Searchable;
public function address()
{
return $this->hasOne('App\Address', 'entity_id');
}
Address:
protected $table = 'address';
public $timestamps = true;
public function entity()
{
return $this->belongsTo('App\Entity', 'id');
}
and my controller:
public function update(EntityRequestUpdate $request)
{
$id = $request->input('entity_id');
$entity = Entity::with('address')
->find($id);
$entity->name = $request->input('name');
$entity->type = $request->input('type');
$entity->email = $request->input('email');
$entity->twitter_entity = $request->input('twitter');
$entity->facebook_entity = $request->input('facebook');
$entity->instagram_entity = $request->input('instagram');
$entity->google_places = $request->input('google');
$entity->address->building_name = $request->input('address1');
$entity->address->street = $request->input('address2');
$entity->address->town = $request->input('town');
$entity->address->city = $request->input('city');
$entity->address->postcode = $request->input('postcode');
$entity->address->telephone = $request->input('telephone');
$entity->address->save($entity);
$entity->save();
$result = $entity->save();
if($result){
$message = 'success';
}else{
$message = 'error';
}
return redirect()->back()->withInput()->with('message', $message);
}
An error message is:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::save() must be of the type array, object given, called in C:\xampp\htdocs\laravel\app\Http\Controllers\EntityController.php on line 146
How can I solve this issue?
I think you just need to use save() method without any parameters. I have try it in php artisan tinker with same structure. And after I get same error, I try to remove the $entity parameter inside save() method:
// After update, you should only use save() not save($entity)
$entity->address->save();
I hope I give correct answer for your problem :-D

Laravel - update one to one field

I have an update post form, where I need to update the name of the post in posts table and the associated text within the text table. I can't seem to get it to work at all.
Model - Post.php
public function text()
{
return $this->hasOne('Text');
}
Model - Text.php
public function post()
{
return $this->belongsTo('Post');
}
Controller - PostController.php
public function updateQuestionForm($id)
{
$post = Post::find($id);
$input = Input::all();
$rules = array(
'text' => 'required',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::back()->withErrors($validation)->withInput();
} else {
$post->title = Input::get('title');
$post->save();
$text = $post->text();
$text->text = Input::get('text');
$post->text()->save($text);
$message = "Post updated";
return Redirect::to('question/'.$post->id.'/'.$post->slug.'/')->with('message', $message);
}
}

How to return the current inserted row data in Laravel?

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

Resources