I'm new to Laravel and trying to load a JSON file into my project (which will then be used for a search function).
NEW EDIT *** It is giving me an error of "undefined constant "data""
For my Controller.php I have:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
public function index() {
$results = file_get_contents("http://ftp.ebi.ac.uk/pub/databases/genenames/hgnc/json/locus_groups/protein-coding_gene.json");
$data = json_decode($results, true);
dd($data);
}
}
And for my new edited route per response below web.php I have: (still has the laravel given code in here as well).
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Controller;
Route::get('/', function () {
return view('welcome');
});
Route::get(“data”, [SiteController::class, “index”]);
In your web.php you need import your controller file:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Controller;
// in laravel 8 and 9 your need to do this with all your controllers
use App\Http\Controllers\SiteController;
Route::get('/', function () {
return view('welcome');
});
Route::get(“data”, [SiteController::class, “index”]);
Related
I have a controller, ShareController, and a method, view:
class ShareController extends AppController
{
public function beforeFilter(Event $event)
{
}
public function index()
{
}
public function view($id)
{
die('here');
}
}
And I have a route:
Router::defaultRouteClass(DashedRoute::class);
Router::extensions(['json', 'xml']);
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/forsale/:id', ['controller' => 'Share', 'action' => 'view'])
->setPatterns(['id' => '\d+'])
->setPass(['id']);;
$routes->fallbacks(DashedRoute::class);
});
Router::prefix('sitecontrol', function ($routes) {
$routes->connect('/', ['controller' => 'Admins', 'action' => 'login']);
$routes->connect('/dashboard', ['controller'=>'Admins','action'=>'dashboard']);
$routes->connect('/logout', ['controller'=>'Admins','action'=>'logout']);
$routes->fallbacks('InflectedRoute');
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
When I visit http://thewebsite/forsale/197 I get redirected to: http://thewebsite/users/login?redirect=%2Fforsale%2F197
What could be causing this redirect? I am expecting to see "here".
Thanks
You are redirected to login page because of Authentication module. As you have not allowed view action for non logged in user, you need to bypass auth for view action. Please modify beforefilter function as following:
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow('view');
}
Actually, i'm new to laravel. I'm trying to make Authenticating Users manually I have a problem that there's no middleware work anyone know what's the problem
it should redirect to the homepage but it doesn't ...
here's for login
public function __construct(){
$this->middleware('auth')->except(['index','show' ]);
}
and that for posts
public function __constructor(){
$this->middleware('guest')->except(['destroy' ]);
}
You should add your middleware in app/Http/Kernel.php and this file have examples,then add the middleware in route like this Route::group(['middleware' => 'your middleware's name'], function () {....}
I have created an ajax.php file on my server and send id to the file using ajax with jquery.
I want to run db queries in that ajax.php file to get the result.
I am unable to do this.
Can you please help me.
Jquery Code:
$('.invitebyemail').click(function(){
var email = $('#add-members-event-email').val();
var eventid = $('.eventid').val();
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
var APP_URL = {!! json_encode(url('/')) !!};
alert(APP_URL);
alert(url);
$.ajax({
url: APP_URL+'/ajax.php',
type: 'POST',
data: { id: eventid },
success: function (data) {
alert(data);
},
error: function () {
alert('error');
}
});
return false;
});
Ajax File Code:
use DB;
$eventid = $_POST['id'];
echo $eventid;
$users = DB::table('users')->get();
print_r($users);
Thanks
If you're using laravel I don't belive that using .php files like that would be the correct way of doing it... it's not really following the MVC patterns.
I recomend creating a controler php artisan make:controller MyController
creating a function as this on the controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Session;
use Auth;
use Response;
use DB;
use App\User;
class MyController extends Controller{
public function getUsers(Request $request){
$users = DB::table('users')->get();
// If you need access to request parameters use this ( $request->id ) being id the parameter name
return response()->json(["users" =>$users]);
}
}
creating a route in ProjectFolder/routes/web.php like this
Route::post('/getUsersAjax',[
'uses'=>'MyController#getUsers',
'as'=>'getUsers'
]);
And in your jquery dont forget to add the _token to your data data: { id: eventid , _token : token},
(if you need this token you can in a .blade.php file, your view, make this
<script>
var token = "{{Session::token()}}";
var urlRequest = "{{route('getUsers')}}";
</script>
)
https://laravel.com/docs/5.4/controllers
https://laravel.com/docs/5.4/routing
Currently I'm using php and nusoap and wanted to convert it to Laravel.
When creating the soap calls I use data out of a mysql database.
So I think I would need a model (to get my data) and a controller (to create request).
EDIT:
<?php
namespace App\Http\Controllers;
use Artisaninweb\SoapWrapper\Facades\SoapWrapper;
class SoapController extends Controller {
public function demo()
{
// Add a new service to the wrapper
SoapWrapper::add(function ($service) {
$service
->name('currency')
->wsdl('path/to/wsdl')
->trace(true);
->options(['user' => 'username', 'pass' => 'password']);
});
// Using the added service
SoapWrapper::service('currency', function ($service) {
var_dump($service->getFunctions());
var_dump($service->call('Otherfunction'));
});
}
}
from laravel-soap I couldn't find a tutorial on how to send login parameters prior to any other request. In the example 'using the added service' I see the login credentials but it doesn't work.
This is how I got soap to work in Laravel 5.1
clean install laravel 5.1
install artisaninweb/laravel-soap
create a controller SoapController.php
<?php
namespace App\Http\Controllers;
use Artisaninweb\SoapWrapper\Facades\SoapWrapper;
class SoapController extends Controller {
public function demo()
{
// Add a new service to the wrapper
SoapWrapper::add(function ($service) {
$service
->name('currency')
->wsdl('path/to/wsdl')
->trace(true);
});
$data = [
'user' => 'username',
'pass' => 'password',
];
// Using the added service
SoapWrapper::service('currency', function ($service) use ($data) {
var_dump($service->call('Login', [$data]));
var_dump($service->call('Otherfunction'));
});
}
}
Create a route in your routes.php
Route::get('/demo', ['as' => 'demo', 'uses' => 'SoapController#demo']);
If requered you can also use the model extension as described here
Here's my javascript snipet
<script type="text/javascript">
$(document).ready(function() {
$('form#FormId button.btn').click(function(event){
$.ajax({
type: "POST",
url: "/controller/edit",
data: $("#FormId").serialize(),
success: function(response) {
alert(response.message);
alert(response['message']);
}
});
});
});
Here's my controller action
public function edit() {
$this->autoRender = false; // We don't render a view in this example
$this->request->onlyAllow('ajax'); // No direct access via browser URL
echo json_encode(array('message'=>'Welcome','type'=>'success'));
exit;
}
Both alerts on the javascript are returning "undefined" how to handle?
So nobody is getting this correct.
You need to use the JSON view
See how to enable with this section
class PostsController extends AppController {
public $components = array('RequestHandler');
public function index() {
$this->request->onlyAllow('ajax');
$this->set(array(
'data' => array('message'=>'Welcome','type'=>'success'),
'_serialize' => 'data',
));
}
}
Cake will now automatically set the correct headers, serialize as JSON and not render the layout.
As a side note, your code alert(response.message); does not work beacuse response is a string. your header is text/html not application/json. Try console.log(response) and you will see it is just a string.
I get this to work using the following code in the controller
public function edit()
{
$this->RequestHandler->respondAs('json'); // Very important without this it will not work
$this->autoRender = false;
$data = array('message'=>'Welcome','type'=>'success');
return json_encode($data);
}
try add
dataType: 'json',
to your ajax method.
if it not work, try this:
add
$this->response->type('text/plain');
to your index method.
ie brower did not know json format text.
and what broswer did you used for this test? use F12 open the developer kit to check what the server response, is it a objct
From my experience echoing content doesn't work. You should instead return the json_encoded data.
This will make your edit() function look like this:
public function edit()
{
$this->autoRender = false;
$this->request->onlyAllow('ajax');
return json_encode(array('message' => 'Welcome', 'type' => 'success'));
}
To make sure it works; just alert the whole response object to see what is returned.