Using middleware in laravel5.4 - laravel-5.4

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 () {....}

Related

How to load JSON file into Laravel (controller and route)

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”]);

How to call a controller directly using ajax

Let say I have 2 project ClientSide and ServerSide. I need to call a function in a controller of ServerSide from ClientSide. Can it be done directly using Ajax?
This is my Ajax code (it will work if the controller is put in the same project):
var url = 'api/values/insert';
$.ajax({
type: method,
url: url,
data: JSON.stringify(data),
contentType: 'application/json',
success: function (data) {
window.location.href = "/index";
}
});
The local host for my ClientSide is https://localhost:44356, and the one for my ServerSide is https://localhost:44329. I have tried adding the local host into the url but it's still not working.
var url = 'https://localhost:44329/api/values/insert';
Is there any other method could help me solve this problem? I am appreciated for all the suggestion and answers.
For more specific information if needed, I am using .NET 2.1
UPDATE:
This is my controller code in ServerSide. If I put the controller in ClientSide, it works without any modification needed, so I believe the problem is about the connection between Ajax and the controller.
namespace RazorAPI.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
public class ValuesController : Controller
{
private readonly IDataService _dataService;
public ValuesController(IDataService dataService)
{
_dataService = dataService;
}
// POST: api/values/insert
[HttpPost]
[Route("[action]")]
public void Insert([FromBody]Data data)
{
//This call another function in ServerSide
_dataService.Create(data);
}
}
After working around with it, I found out the problem is because of CORS issue. This is how I fix it.
In Startup.cs file of ServerSide project, add the following code to Configure method:
app.UseCors("AllowAllHeaders");
Add the following code to ConfigureService method:
services.AddCors(options =>
{
options.AddPolicy("AllowAllHeaders",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Now use the url include local host to ServerSide:
var url = 'https://localhost:44329/api/values/insert';
This works for me but it will allow acess from any domain. If you need it to be only accessed by specific origin, change the code in Configure into:
app.UseCors("AllowSpecificOrigin");
And for the code in ConfigureService:
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
{
builder.WithOrigins("localhost")
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Thank you for all the help!

Cake PHP 3.5 route

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

Getting correct ID without sharing URL

I have an Angular 4 application where I am trying to fetch a single row (using ID) from a MySQL database. I am using NodeJS with ExpressJS. However, I am struggling finding a way to get the ID from the URL without sharing the exact URL-path, as that would lead to the website only rendering the JSON-object, and not the components.
server.js
app.get('api/books/:id', (req, res) => {
console.log(req.params.id);
});
If the URL is localhost:3000/books/3, the console will log :id. localhost:3000/api/books/3 will however log the correct ID to the console. The issue is that using the latter as my URL in my Angular routing will result in a shared path, which will not work.
Here's an example of how I use Angular's HttpModule to send a GET-request to the server:
this.http.get('api/books/:id')
.map(res => res.json())
.subscribe(data => {
this.bookDetail = data;
});
Here is my path from the routing using Angular's RouterModule:
{ path: 'books/:id', component: BookDetailComponent }
How would I go about solving this issue?
You need to create a function that on the init of that component, the angular app triggers the HTTP request to the server. for example, I have a blog application.
{ path: 'blogs/:id', component: BlogComponent },
ngOnInit() {
this.route.params.subscribe(params => this.blog = params.id);
this.getBlog(this.blog);}
getBlog(blog) {
this.blogService.getBlog(blog).subscribe(
data => { this.foundBlog = data;
if (data.comments) {
this.comments = data.comments;
}
getBlog(blog): Observable<any> {
return this.http.get(`http://localhost:3000/api/blogs/${blog}`).map(res => res.json());
}
the first is my route, the second is the init function on my blog component
the third is the get blog function on the blog component
the last is the get blog function on my blogservice, that send the HTTP request
hopefully that helps.

Laravel 5.1 consuming soap wsdl service using controller and model

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