Creating view if not found in laravel 5 - laravel-5

I have a controller where I check if the view exists, like so
if (view()->exists($moduleName.$getCategoryNameToLowerCase))
{
//if exist return the view
return view($moduleName.$getCategoryNameToLowerCase);
}
else{
//else create a view and return it;
return View::make($moduleName.$getCategoryNameToLowerCase);
}
But this is not creating a view and return it. Am I using it in the right way?

Related

return view($viewVariable) from a trait in laravel 8

I have a trait that is being called by several controllers in laravel 8.
Every controller gives the name of the return view allong with function on the trait.
If I do a dd($viewVariable); in the trait then I see the correct refrence to the view. But the trait refuses to return the view. It just gives me a blank screen. First I thought it was a problem with "no quotes", "singel quote" or dubbel quotes" but I tried every variation but without any succes.
I've tried setting the view the normal way but it even refused to render that. I've checked the other functions and variables with the dd($var); and everything is working correct till it's time to return the view.
ChartTrait.php
public function setViewOptionsForChartGeneration($viewVariable)
{
// Check which role the user has in the application
if (Auth::user()->hasRole('admin')) {
$recorderCollection = $this->getRecorderCollectionWhenAdmin();
return view($viewVariable)->withRecorderCollection($recorderCollection);
} elseif (Auth::user()->hasRole('employee|user')) {
// Get all the valid timeslots that belongs to the authenticated user
$userTimeslotCollection = $this->getUserTimeslot();
// Get all the corresponding recorders from the valid timeslots that belongs to the authenticated user
$recorderCollection = $this->onlyCollectRecordersBasedOnValidTimeslot($userTimeslotCollection);
// return the view with all the possibility's the authenticated user has.
return view($viewVariable)
->withRecorderCollection($recorderCollection->flatten())
->withUserTimeslotCollection($userTimeslotCollection);
}
}
There nothing wrong with the function in ChartTrait.php. The Problem was in the controllers. You need to return the function you call to render the view.
Correct way of calling the trait
public function index()
{
$view = "".'content.export.export'."";
return $this->setViewOptionsForChartGeneration($view);
}
Wrong way of calling the trait
public function index()
{
$view = "".'content.export.export'."";
$this->setViewOptionsForChartGeneration($view);
}

Changes in Controller not reflecting showing previous return value

O make change in Controller but it is not effecting it is returning previous changed value not new.
I make many different kind but it is showing same first value which was returned.
I want to return new value from controller
//------------Logout---------------
public function logoutme() {
if (Session::has('RedPachUID')) {
Session::forget('RedPachUID');
return "yes";
}
}
New Function
//------------Logout---------------
public function logoutme() {
if (Session::has('RedPachUID')) {
Session::forget('RedPachUID');
return "No";
}
}
it was happening because I was using anchor tag when i used form to logout it helps me
here is complete solution logout function not invalidating session

Yii2 validation on controller action

I am developing a Yii 2.0 application in which users can create orders then send the orders to review and after that it follows a number of stages in the workflow.
Everything is ok until yesterday that the customer ask for the possibility that before sending the orders to review the order are considered as draft. Which means I have to turn off validations on create and validate them when users clicks Send To Review button. I know Yii 2.0 supports scenarios but maybe scenarios doesn't apply to this because the Send To Review button is shown in a readonly view. This forces me to do validation inside the controller action because there is no send_to_review view. How can this be done (I mean model validation inside controller action)?
Here is the controller action code
public function actionSendToReview($id)
{
if (Yii::$app->user->can('Salesperson'))
{
$model = $this->findModel($id);
if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id)
{
$model->orden_stage_id = 2;
$model->date_modified = date('Y-m-d h:m:s');
$model->modified_by = Yii::$app->user->identity->username;
//TODO: Validation logic if is not valid show validation errors
//for example "For sending to review this values are required:
//list of attributes in bullets"
//A preferred way would be to auto redirect to update action but
//showing the validation error and setting scenario to
//"send_to_review".
$model->save();
$this::insertStageHistory($model->order_id, 2);
return $this->redirect(['index']);
}
else
{
throw new ForbiddenHttpException();
}
}
else
{
throw new ForbiddenHttpException();
}
}
What I need to solve is the TODO.
Option 1: Showing validation errors in the same view and the user has to clic Update button change the requested values save and then try to Send To Review again.
Option 2: Redirecting automatically to update view already setting scenario and validation errors found in the controller.
Thanks,
Best Regards
You can use $model ->validate()for validation in controller.
public function actionSendToReview($id)
{
if (Yii::$app->user->can('Salesperson'))
{
$model = $this->findModel($id);
if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id)
{
$model->orden_stage_id = 2;
$model->date_modified = date('Y-m-d h:m:s');
$model->modified_by = Yii::$app->user->identity->username;
//TODO: Validation logic if is not valid show validation errors
//for example "For sending to review this values are required:
//list of attributes in bullets"
//A preferred way would be to auto redirect to update action but
//showing the validation error and setting scenario to
//"send_to_review".
//optional
$model->scenario=//put here the scenario for validation;
//if everything is validated as per scenario
if($model ->validate())
{
$model->save();
$this::insertStageHistory($model->order_id, 2);
return $this->redirect(['index']);
}
else
{
return $this->render('update', [
'model' => $model,
]);
}
}
else
{
throw new ForbiddenHttpException();
}
}
else
{
throw new ForbiddenHttpException();
}
}
If you don't need validation in actionCreate().Create a scenario for not validating any field and apply there.

laravel, recall resource route inside closure on routes.php

I already implement this code and it works,
function to return/generate html from view file, i add the view() method to the controller
//i'm ok with this and did works
Route::get('/page/{name}', function($name){
if(class_exists("App\Http\Controllers\\".$name."Ctrl")){
return App::make("App\Http\Controllers\\".$name."Ctrl")->view();
}
else{
return "Page tidak ditemukan";
}
});
Now i want to implement this on resource route, but cannot find technic/method to function the same way as above
Route::resource('/data/{name}', function($name){
//check first if controller exists
if(class_exists("App\Http\Controllers\\".$name."Ctrl")){
//need some Kind Of method or hack i presume
// so the request is processed as defined by the standar resource route
//
//NEED HELP ON THIS FUNCTIONALITY
//
}
else{
return "Page tidak ditemukan";
}
});

Best way to handle a validations before a delete?

I need to be to perform validations during the Delete Action in my controller. Does ASP.net MVC3 have anything to assist with this type of validation? I know you can use the Attributes to handle edit validations but what about deletion?
For example i need to check the state of the entity object and if a certain condition is met they are not allowed to delete. What's the best way to check and display an error
You can have your delete action to be like the following, you can check for your condition by making a call like in the example below the method CanThiBeDeleted() does, if not then you can add an error to the Model State and send it back to the view, where this error message will be displayed.
public ActionResult Delete(string id)
{
if(!_service.CanThisBeDeleted(id))
{
ModelState.AddModelError("", "Sorry this cannot be deleted !");
return View();
}
bool isItemDeleted = false;
isItemDeleted = _service.DeleteItem(id);
if(isItemDeleted)
{
// if deleted send where you want user to go.
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Delete operation failed.");
return View();
}
}
your view can have use #Html.ValidationSummary to display the errors/warnings you want to display.

Resources