Laravel Update a div class from Controller - php

Is it possible to use a controller to update a div class? I'm still learning Laravel here and could use some help. I have a controller with the following code:
public function update()
{
if (Auth::check() || Auth::attempt()) {
$auth_id = Auth::user()->rcid;
} else {
$auth_id = '00000';
}
$finalize = DB::table('AdminOperations.gen_ed_assessment.responses_data_record')
->where('fkey_instructor_id' , $auth_id)
->update(['locked' => 1]);
return Redirect::to('/');
}
When I redirect back to the default or homepage I'd like to be able to update a a menu button from list-group-item to list-group-item disabled.
My button code below:
Enter Your Assessments<span class="badge"><?php echo $totalrecordstofillout;?></span>
How would I parse the code in the controller to make this disabled when its redirected.
Can you use the controller to change the div class and if so how would you go about that in the controller?
Sorry if this is an elementary question for those php/laravel pros.
Thanks in advance.

You can use session flash, example:
public function update()
{
if (Auth::check() || Auth::attempt()) {
$auth_id = Auth::user()->rcid;
} else {
$auth_id = '00000';
}
$finalize = DB::table('AdminOperations.gen_ed_assessment.responses_data_record')
->where('fkey_instructor_id' , $auth_id)
->update(['locked' => 1]);
if ($someCondition === true) {
Session::flash('is_disabled', true);
}
return Redirect::to('/');
}
on your view:
Enter Your Assessments<span class="badge"><?php echo $totalrecordstofillout;?></span>
Edit:
I noticed that you are using Laravel 4, so I've edited my answer.

Related

Laravel running function from button in blade

I am having an issue getting a button in a blade file to properly run a function in a controller, when i click the button i get a methodnotallowedexception and have not been able to figure out what is not setup correctly
To my knowledge this is written like another button i have for a different blade and controller, unless i am overlooking something, which is why i am here. if you need other code let me know.
first my routes:
Route::post('/viewPatient/{user}/discharge', 'PatientController#discharge')->name('patients.discharge');
Route::post('/viewPatient/{user}/reAdmitt', 'PatientController#reAdmitt')->name('patients.reAdmitt');
Route::post('/viewPatient/{user}/reAdmitted', 'PatientController#reAdmitted')->name('patients.reAdmitted');
next the controller functions
public function discharge(User $user)
{
$user->discharged = true;
$user->discharged_date = now();
$user->current_facility_id = null;
$user->save();
// find all the users documents that are not historical
$documents = Document::where('user_id', $user->id)->where('historical', false)->get();
// mark them all as historical
foreach($documents as $document){
$document->historical = true;
$document->save();
}
return $this->index();
}
public function reAdmitt(User $user)
{
$user->discharged = false;
$user->readmitting = true;
$user->reAdmission_start = now();
$user->save();
return $this->index();
}
public function reAdmitted(User $user)
{
$user->discharged = false;
$user->readmitting = false;
$user->reAdmitted_on = now();
$user->save();
return $this->index();
}
and finally the buttons themselves
<button>Readmitt Patient</button>
<button>Patient Signed reAdmission</button>
<button>Discharge Patient</button>
the expected result is that it should run the function and update the database, i know the function to discharge works because i accidentally changed the route to a get and it ran when the page loaded and marked one of the patients as discharged.
You are not submitting any form. So you don't need to use post routes. <a> tag is for get routes. So change your routes as
Route::get('/viewPatient/{user}/discharge', 'PatientController#discharge')->name('patients.discharge');
Route::get('/viewPatient/{user}/reAdmitt', 'PatientController#reAdmitt')->name('patients.reAdmitt');
Route::get('/viewPatient/{user}/reAdmitted', 'PatientController#reAdmitted')->name('patients.reAdmitted')
;

Submitting like using Ajax within Laravel application

So i've modified some code to add a Like function to a table called sources, this sources have the relation "hasMany" with the table likes.
It doesn't work and I don't get any errors, neither Javascript or PHP errors.
When I like the page it seems like the Ajax don't get called because the page reload to /public/view#, so nothing get submitted to the database.
I don't know how to sort this out.
View:
#foreach($post->sources as $source)
<a>{{$source['link']}}</a>
<div class="interaction" data-sourceid=" {{ $source['id'] }} ">
{{ Auth::user()->likes()->where('source_id', $source['id'])->first() ? Auth::user()->likes()->where('source_id', $source['id'])->first()->like == 1 ? 'You like this source' : 'Like' : 'Like' }} |
{{ Auth::user()->likes()->where('source_id', $source['id'])->first() ? Auth::user()->likes()->where('source_id', $source['id'])->first()->like == -1 ? 'You don\'t like this source' : 'Dislike' : 'Dislike' }}
</div>
<br>
#endforeach
<script>
var token = '{{ csrf_token() }}';
var urlLikeSource = '{{ route('likesource') }}';
</script>
app.js:
$('.like-source').on('click', function(event){
event.preventDefault();
sourceId = event.target.parentNode.dataset['sourceid'];
var isLike = event.target.previousElementSibling == null; //Checks if it's a like or dislike.
$.ajax({
method: 'POST',
url: urlLikeSource,
data: {isLike: isLike, souceId: sourceId, _token: token}
})
.done(function(){
//Change the page when .ajax has been executed.
event.target.innerText = isLike ? event.target.innerText == 'Like' ? 'You like this source' : 'Like' : event.target.innerText == 'Dislike' ? 'You don\'t like this source' : 'Dislike';
//Make sure you can't dislike and like at the same time.
if(isLike){
event.target.nextElementSibling.innerText = 'Dislike';
} else {
event.target.previousElementSibling.innerText = 'Like';
}
});
});
routes:
Route::post('/likesource', [
'uses' => 'SourceController#sourceLikeSource',
'as' => 'likesource'
]);
SourceController.php:
<?php
namespace App\Http\Controllers;
use App\Comment;
use App\Post;
use App\Like;
use App\Source;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class SourceController extends Controller{
public function sourceLikeSource(Request $request)
{
$source_id = $request['sourceId'];
$is_like = $request['isLike'] === 'true'; //Get's passed as string in request, changed to boolean.
$update = false;
//REDO WITH SMARTER SOLUTION
if($is_like == 0){
$is_like = -1;
}
$source = Source::find($source_id);
if(!$source){
return null;
}
$user = Auth::user();
$like = $user->likes()->where('source_id', $source_id)->first(); //First has to be specified
if($like){
$already_like = $like->like;
$update = true;
//Deletes if it already exists.
if($already_like == $is_like){
$like->delete();
return null;
}
} else {
$like = new Like(); //Creates new row for Like in table
}
$like->like = $is_like; //Set's whatever $like->like to whatever $request['isLike'] passed.
$like->user_id = $user->id;
$like->source_id = $source_id;
if($update){
$like->update();
}else{
$like->save();
}
return null;
}
}
Like.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Like extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function post()
{
return $this->belongsTo('App\Post');
}
public function source()
{
return $this->belongsTo('App\Source');
}
public function comment()
{
return $this->belongsTo('App\Comment');
}
}
Source.php model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Source extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
public function likes()
{
return $this->hasMany('App\Like');
}
}
Edit:
Rookie mistake by me, I cleared the browser cache. The browser used an old app.js file. Now the ajax seemed to get called correctly, however there's still no new rows in the likes table.
Edit 2:
I gave the data within the Ajax call sourceId: 1 and isLike: 2. There were still no new rows being created in the table likes.
So the problem seems to be in the routes, controller or any of the models.
Edit 3:
I changed the route to a route I knew works properly, I added a csfr_token exception to make sure the token wasn't screwing anything up. I made sure everything in the models were right and I finally made sure everything in the controller was being called correctly.
I truly can't find any problem.
The only thing I can think about is that the likes table "belongsTo" a lot of tables. I made the post_id, comment_id and source_id nullable when I created the table migration.
Should I use some other relationship in the models?

Laravel Access Control with Model Objects

I need to restrict the access to some parts of the application depending on the user logged in. I mean for example to let a user edit only its own posts on a blog application.
Is there a better approach than in every function of the controller, if the user is not the owner of the required post, redirect to some error page?
For example if my routes are /post/{post_id}/edit, /post/{post_id}/preview, /post/{post_id}/delete, can I somehow declare a general function in the PostController like:
if(Post::find($post_id)->user_id != Auth::user()->id){
return View::make('access-error');
}
Thanks!
In your controller you can do something like this:
public $check = ['edit', 'preview', 'delete'];
public function callAction($method, $parameters) {
if(in_array($method, $this->check, true) &&
$post_id = $parameters['post_id'] &&
Post::find($post_id)->user_id != Auth::user()->id) {
return View::make('access-error');
}
return parent::callAction($method, $parameters);
}
You could throw a 401 error and catch it elsewhere to display a custom page
App::abort(401);
http://laravel.com/docs/4.2/errors#handling-404-errors

Yii calling controller function from another controller

In my web application the work flow demands that I should call one controller function from another function
Should I do add extra code or some configuration to proceed ? Right now This is how I implemented .But When I click "save" button nothing is happening values are just getting empty from the form .
My code .I want to create an object of model "BookVegetable" inside "ProducerOfferController" .
My code inside producerOffer controller
public function actionCreate()
{
//$book_vegetable=new BookVegetable;
$model=new BookVegetable;
if(isset($_POST['BookVegetable']))
{
$model->attributes=$_POST['BookVegetable'];
$model->booked_by = Yii::app()->user->id;
$model->save();
if ($model->hasErrors() === false)
{
$this->redirect(Yii::app()->user->returnUrl);
}
}
else
{
Yii::app()->user->setReturnUrl($_GET['returnUrl']);
}
$this->render('book',array('model'=>$model,));
}
My code for from view
<div style='padding-left:50px'>
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array('id'=>'non-ajax_form','enableAjaxValidation'=>false,)); ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<?php echo "<br>" ?>
<?php echo CHtml::textField("booked_quantity",$model->booked_quantity); ?>
My scenario
public function actionBookvegetable($id){
$BookVegetable=new BookVegetable;
$model=$this->loadModel($id);
if(isset($_POST['ProducerOffer'],$_POST['BookVegetable']))
{
$model->attributes=$_POST['ProducerOffer'];
$BookVegetable->attributes=$_POST['BookVegetable'];
$BookVegetable->booked_by=Yii::app()->user->id;
$BookVegetable->producer_offer_id=$model->id;
$model->save();
$BookVegetable->save();
if (($model->hasErrors() === false)||($BookVegetable->hasErrors()=== false))
{
$this->redirect(Yii::app()->user->returnUrl);
}
}
else
{
Yii::app()->user->setReturnUrl($_GET['returnUrl']);
}
$this->render('book',array('model'=>$model,'BookVegetable'=>$BookVegetable));
}
<div class="form-actions">
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'primary', 'label'=> 'Save',)); ?>
How should I resolve this ? Is it essential to add anything extra to use one controller action inside another controller
The url before saving and its the same after I press save also
http://localhost/xxx/producerOffer/bookvegetable/20?returnUrl=%xxx%2FproducerOffer%2Fmanage
One way to do this in Yii2
Background
In SiteController action index method get the records of all objects from another model called voyzes.
In SiteController
Include the other model ex. Voyzes
Now in the SiteController action index method, implement the code to access the model/SQL/NoSQL or anything and set it in a array and return it to the view. For ex.
Now in the index view you should have your data from another model.
According to your information provided.. when you go here,
http://xxx.yyy.zzz/xxxx/producerOffer/create
Actually it should show you the form of book and when you click the save button there and go to returnUrl.
$this->redirect(Yii::app()->user->returnUrl);
I suggest you to write the following as,
$model->save();
$BookVegetable->save();
if (($model->hasErrors() === false)||($BookVegetable->hasErrors()=== false))
{
$this->redirect(Yii::app()->user->returnUrl);
}
To
if($model->save() && $BookVegetable->save())
$this->redirect('yourAction'); //if params needed, $this->redirect(array('yourAction', 'id' => $model->id));
When you go here, http://xxx.yyy.zzz/xxxx/producerOffer/bookvegetable
What ever the code you have written under ActionBookvegetable will trigger.
To make sure your values submitted properly please change this code
$model->save();
if ($model->hasErrors() === false)
{
$this->redirect(Yii::app()->user->returnUrl);
}
To
if($model->save())
$this->redirect('yourAction');
else
print_r(getErrors());
This will print any errors thats preventing from saving the model. let me know after you try this.
In my work , I have a lot of logic around the "loadModel" routine in controllers to make sure the user logged in has access to the particular model. I found this to work from another controller when I need to access the model, without moving or re-copying the loadmodel routine:
$caseviewController = Yii::app()->createController('Caseview');
//use this method from caseview controller to securley load case view model
$caseview = $caseviewController[0]->loadModel($caseviewid);

Laravel : Variable layout for a single view

I wanted to know if there's a way to use variable layout for a single view in laravel.
I have a view of the login section. I want to show the login view in a lightbox by calling it via AJAX. I was thinking of using a different layout for the login view when it is called through ajax.
Something like this :
if($_GET["from"] == "ajaxLink") {
// use layout1
} else {
// use layout2
}
This obviously doesnt work. :)
Is there any way i can do this??
Thanks.
2 ways.
1. Blade layout
Controller:
$layout = Request::ajax() ? 'layout1' : 'layout2';
$data = array('layout' => $layout);
return View::make('index', $data);
View:
#layout($layout)
//rest of the code....
2. Controller layout
public function action_index()
{
$this->layout = Request::ajax() ? 'layout1' :'layout2';
$this->layout->nest('content', 'index');
}

Categories