Laravel 4 Route Group - laravel-4

I have two different users and I am trying to group my routes so that other user can not redirect to other user page. Example when I login as a guest, I can redirect to the reports page although only admin can view the reports page.
I did the following, but now, I don't have access to the grouping routes only those outside grouping.
The following is my code:
=>Filters
Route::filter('admin', function(){
$user = Auth::user();
if($user->type == "admin"){
return true;
}
if (Request::ajax()){
return Response::make('Unauthorized', 404);
}
return View::make('404_auth');
});
Route::filter('guest', function(){
$user = Auth::user();
if($user->type == "guest"){
return true;
}
if (Request::ajax()){
return Response::make('Unauthorized', 404);
}
return View::make('404_auth');
});
=>Routes
Route::get('/', function() {
return View::make('home');
});
Route::get('home', function() {
return View::make('home');
});
Route::get('login', function() {
return View::make('login');
});
Route::get('register', function() {
return View::make('register');
});
Route::post('register', 'HomeController#register');
Route::post('login', 'HomeController#login');
Route::get('logout', 'HomeController#logout');
Route::post('/', 'HomeController#postChangeLanguage');
Route::group(['before' => 'admin'], function() {
Route::get('reports', function() {
$data = DB::table('application')->get();
$exam_id = Apply::where('user_id', Auth::user()->id)->pluck('exam_id');
$exam = Exam::where('id', $exam_id)->get();
return View::make('admin/admin_side', compact('data', 'exam'));
});
Route::post('reports', 'AdminController#search');
});
Route::group(['before' => 'guest'], function() {
Route::get('apply', function() {
$city = Session::get('city');
return View::make('apply', compact('city', $city));
});
Route::get('location', function() {
return View::make('location');
});
Route::get('completed', function() {
return View::make('getpdf');
});
Route::post('location', 'HomeController#location');
Route::post('apply', 'HomeController#apply');
Route::post('completed', 'PdfController#getpdf');
});

I think in the filter, you just return the situation you do not want to proceed
=>Filters
Route::filter('admin', function(){
$user = Auth::user();
if($user->type != "admin"){
return View::make('404_auth');
}
if (Request::ajax()){
return Response::make('Unauthorized', 404);
}
});
Route::filter('guest', function(){
$user = Auth::user();
if($user->type != "guest"){
return View::make('404_auth');
}
if (Request::ajax()){
return Response::make('Unauthorized', 404);
}
});
laravel 4.2 route doc.
And if it still not working, please provide more information so everyone can have more ideas to help.

Related

On vue how to make a Edit function

Im doing my first CRUD with Vue - Laravel, i did a Add function that works fine but my Edit button is doing another Add function.
(I get the alert from updateDespesa alert("Usuário Alterado!");)
My Frontend:
async updateDespesa(despesa) {
const response = await axios
.put("api/despesas/" + despesa, {
des: this.despesa.des,
valr: this.despesa.valr,
vencc: this.despesa.vencc,
stt: this.despesa.stt,
emiss: this.despesa.emiss,
})
.then((response) => {
this.despesa.id = "";
this.despesa.valr = "";
this.despesa.stt = "";
this.despesa.vencc = "";
this.despesa.emiss = "";
this.getDespesa();
if(despesa){
alert("Usuário Alterado!");
}
})
.catch((err) => {
console.log(err);
});
},
My Backend:
public function update(Request $request, $id) {
if ($id == 0) {
$despesa = new Despesa;
$despesa->create($request->all());
}
else {
$despesa = Despesa::findOrFail($id);
$despesa->fill($request->all())->save();
}
//$despesa->update($request->all());
return response()->json('Sucess');
}
In your backend, try update this and see
public function update(Request $request, $id) {
if ($id == 0) {
$despesa = new Despesa;
$despesa->create($request->all());
}
else {
$despesa = Despesa::findOrFail($id);
$despesa->fill($request->all())->save();
}
//$despesa->update($request->all());
return response()->json('Sucess');
}
and also please check the Despesa Model has declared the input fields in protected $fillable
async updateDespesa(despesa) {
const response = await axios
.put("api/despesas/" + despesa, {
...
})
.then((response) => {
// add this line, to check only alert when id is not null
// so that it only alert when update
if(despesa){
alert("Usuário Alterado!");
}
....
})
.catch((err) => {
console.log(err);
});
},

Check if record exists Before Insertion using laravel

I want to check record is_featured is a column name if any product is is_featured 1 is already exist error message should be shown Trying to assign an already assigned featured
how can i do that please help me thanks.
https://ibb.co/1Zv2KBW
controller
public function featured(Request $request)
{
if ($request->id) {
$featured = $request->input('is_featured');
$assignFeature = Product::where('is_featured', '=', $featured)->first();
if ($assignFeature) {
abort(405, 'Trying to assign an already assigned featured');
}
} else {
$response['is_featured'] = false;
$response['message'] = 'Oops! Something went wrong.';
$id = $request->input('id');
$featured = $request->input('is_featured');
$featureditem = Product::find($id);
if ($featureditem->update(['is_featured' => $featured])) {
// form helpers.php
logAction($request);
$response['is_featured'] = true;
$response['message'] = 'product featured updated successfully.';
return response()->json($response, 200);
}
return response()->json($response, 409);
}
}
ajax script
$('.postfeatured').change(function () {
var $this = $(this);
var id = $this.val();
var is_featured = this.checked;
if (is_featured) {
is_featured = 1;
} else {
is_featured = 0;
}
axios
.post('{{route("product.featured")}}', {
_token: '{{csrf_token()}}',
_method: 'patch',
id: id,
is_featured: is_featured,
})
.then(function (responsive) {
console.log(responsive);
})
.catch(function (error) {
console.log(error);
});
});
remove this abort()
if ($assignFeature) {
//abort(405, 'Trying to assign an already assigned featured'); //remove this
$response['is_featured'] = false;
$response['message'] = 'Trying to assign an already assigned featured.';
return response()->json($response, 200);
}
Try this:
$product_created_status = $product->wasRecentlyCreated ? 1 : 0 ;
if product is already created it returns 0, else returns 1

Ajax submission triggers Error = True by default even at success

Laravel ajax submission.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : '{{URL::to('expense_bill/store2')}}',
method: 'POST',
data: $("#expense_create").serialize(),
success:function(data){
console.log(data)
if(data['success'] = true){
}
if(data['error'] = true){
//Clear Valdiation Errors
console.log('hi');
}
},
error: function (xhr) {
$('#validation-errors').html('');
$.each(xhr.responseJSON.errors, function(key,value) {
$('#validation-errors').append('<div class="alert alert-danger">'+value+'</div');
});
},
});
});
Controller:
public function store2(Request $request)
{
if($request->ajax()){
//return response()->json($request);
$validator = Validator::make($request->all(), [
'supplier' => 'required',
]);
if ($validator->fails()) {
$returnArray['error']=true;
$returnArray['err_msg']=json_decode(json_encode($validator->errors()), true);
return $returnArray;
}
if ($validator->passes()) {
$request->merge(['total' => $request->total*100]);
$request->merge(['tax_value' => $request->tax_value*100]);
$expensebillheader = ExpenseBillHeader::create($request->all());
$expense_bill_no = $expensebillheader->id;
$count = $request->input('count');
for ($i = 0; $i <= $count; $i++){
//checks if input with this name exists (incase if any middle row was deleted)
if (isset($request->input('amount')[$i]))
{
$line = new ExpenseBillBody;
$line->bill_no = $expense_bill_no;
$line->description = $request->input('description')[$i];
$line->amount = $request->input('amount')[$i];
$line->account = $request->input('account')[$i];
$line->save();
}
};
$successArray = ['success'=>'true','msg'=>"Expnese No".$expense_bill_no." Created"];
return response()->json($successArray);
}
}
}
When validator fails, it's all fine. When validator passes it is supposed to give success=" true" message. But along with that it also gives error="true" as well. Not sure what am I doing wrong. See in the screenshot, the highlighted portion should not come.
Larave returns correct response. You have error here
success:function(data){
console.log(data)
if(data['success'] = true){
}
if(data['error'] = true){
//Clear Valdiation Errors
console.log('hi');
}
}
...
if(data['success'] = true) and if(data['success'] = true) isn't comparasion, these are assigning values
Try to write comparasion operators ==
success:function(data){
console.log(data)
if(data['success'] === true){
}
if(data['error'] === true){
//Clear Valdiation Errors
console.log('hi');
}
}
...

Codeigniter 3 validation error not showing along with callback function

I want to validate login form with ajax. I am using form valiation with a callback function that check username in database. When I am using callback with set_message, form validation errors are not working, only that callback error message is shown. If username is empty then form validation error like "Username is required" should be shown first and then if user enter wrong username then callback function error like "Username is not correct" should be shown
Following are the functions in my controller
public function validate_form()
{
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('username', 'Username', 'required|trim|xss_clean|callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required|trim|xss_clean|callback_password_check');
$this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');
if ($this->form_validation->run()) {
$data['success'] = true;
$this->session->set_userdata('admin_username', $this->input->post('username'));
} else {
foreach ($_POST as $key => $value) {
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
public function username_check()
{
$username = $this->input->post("username");
if ($this->admin_model->usernameDB()) {
return true;
} else {
$this->form_validation->set_message('username_check', 'The {field} is not correct');
return false;
}
}
public function password_check()
{
$password = $this->input->post("password");
if ($this->admin_model->passwordDB($password)) {
return true;
} else {
$this->form_validation->set_message('password_check', 'The {field} is not correct');
return false;
}
}
Following are the function in my model
public function usernameDB() {
$this->db->where('username', $this->input->post('username'));
$query = $this->db->get('adminuser');
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
public function passwordDB() {
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('adminuser');
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
Following is the ajax that i am using
$("#admin_login_form").submit(function(e) {
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax ({
url: "validate_form",
type: "post",
data: me.serialize(),
dataType: "json",
success: function(response) {
if (response.success == true) {
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
window.location = "member";
} else {
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value);
});
}
}
});
});
I want proper validation errors order like if username or password is empty then first their relevant errors should be shown like username or password is required and then wrong or correct username or password errors should be shown.
You can try below. You can use single callback function to check whether user is exists or not.
First, remove the callback functions public function username_check() and public function password_check() from your controller and replace with the updated functions below.
In addition to this created new model function login inside admin_model which will check whether user is exists or not. Also you can delete both usernameDB and passwordDB from your admin_model.
Controller function:
public function validate_form()
{
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('username', 'Username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|trim|xss_clean|is_user_exists');
$this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');
if ($this->form_validation->run()) {
$data['success'] = true;
$this->session->set_userdata('admin_username', $this->input->post('username'));
} else {
foreach ($_POST as $key => $value) {
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
public function is_user_exists()
{
if ($this->admin_model->login($this->input->post('username', TRUE), $this->input->post('password', TRUE))) {
return true;
} else {
$this->form_validation->set_message('is_user_exists', 'Login failed. Username or password is incorrect');
return false;
}
}
Model function:
public function login($username, $password)
{
$this->db->where('username', $username);
$this->db->where('password', md5($password));
$query = $this->db->get('adminuser');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
Note: Using md5 for encrypt password is not good. See Alex's comment for more details.

Laravel Redirect to previous dynamic page after login

I wonder how I can redirect a user after login?
Lets say that I am on the page "www.mysite.com/users/2"
Then I try to edit a blog post without being logged in and get sent to the login page, efter login I wish to return to "www.mysite.com/users/2"
I have tried this so far:
if (Auth::attempt($credentials,$remember)) {
return redirect()->back();
} else {
return redirect()->back()->withErrors([trans('api.couldnotlogin')]);
}
But return redirect()->back(); will only redirect me to "www.mysite.com/"
Update
I got it working using this:
public function showLoginForm()
{
$previous_url = Session::get('_previous.url');
$ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$ref = rtrim($ref, '/');
if ($previous_url != url('login')) {
Session::put('referrer', $ref);
if ($previous_url == $ref) {
Session::put('url.intended', $ref);
}
}
return view('auth.login');
}
public function loginUser(ApiAuthUserPassRequest $request)
{
if ($request->has('rememberme')) {
$remember = $request->input('rememberme');
} else {
$remember = false;
}
$credentials = ['email' => $request->input('email'), 'password' => $request->input('password')];
if (Auth::attempt($credentials,$remember)) {
if (Session::has('referrer')) {
return redirect()->intended(Session::pull('referrer'));
} else {
return redirect('/account');
}
} else {
return redirect()->back()->withErrors([trans('api.couldnotlogin')]);
}
}
Laravel 5.1 have trait Illuminate/Foundation/Validation/ValidatesRequests.php with method
protected function getRedirectUrl()
{
return app(UrlGenerator::class)->previous();
}
where UrlGenerator is Illuminate/Routing/UrlGenerator.php. You can try use previous() method.

Resources