How to convert to laravel from express js? - php

I have a few lines of code which is written in express js, I want to convert into the laravel code,
app.get('/*', function(req, res) {
var jsonResponse = [];
jsonResponse.push({ "text": "Hi. 3 is a lucky number..." });
res.send(jsonResponse);
});
Is there anyway? Please guide me.
Here is my tried , don't know correct or not.
public function json_test(){
$message =["text" => "Hi. is a lucky number..."];
return $message;
}

Long story short
I think everything is correct. You just have to change your return value to be a json response.
A bit more detailed
You must first define a route in api.php:
Route::get('/some/url', 'ExampleController#jsonTest');
Next you must define a controller and inside the controller the functions that you need:
<?php
namespace App\Http\Controllers;
class ExampleController extends Controller
{
public function jsonTest(){
$message =["text" => "Hi. is a lucky number..."];
return response()->json($message);
}
}
In case you don't need an entire controller for this you can simply place the functionality in the api.php file like so:
Route::get('/some/url', function () {
$message =["text" => "Hi. is a lucky number..."];
return response()->json($message);
});
Hope this helps.

Related

OctoberCMS Routing Plugin Unresolvable dependency resolving

I'm currently working with OctoberCMS and am creating a plugin which has a custom page with a widget which shows a grid
As you can see in this image this grid can be managed and can be saved with the "Save changes" button. This will send a POST request to the server, but I have problems with "listening" for this POST request. Since the documentation of octoberCMS is not very good I'm trying to do this the way it would be done in Laravel. But even that doesn't work like it should.
Unresolvable dependency resolving [Parameter #0 [ <required> $app ]] in class Illuminate\Support\ServiceProvider
ftsf/grid/routes.php
<?php
Route::post('/backend/ftsf/grid', 'Ftsf\Grid\Widgets\GridManager#saveGrid');
ftsf/grid/widgets/GridManager.php
<?php namespace Ftsf\Grid\Widgets;
use App;
use Backend\Classes\WidgetBase;
use Cms\Classes\Content;
use Cms\Classes\Controller;
use Cms\Classes\Theme;
use Cms\Twig\Extension;
use Ftsf\Grid\Models\PatternOrder;
use Illuminate\Http\Request;
use System\Twig\Engine as TwigEngine;
class GridManager extends WidgetBase {
protected $defaultAlias = 'ftsf_grid_manager';
public function init() {
}
public function render() {
$env = App::make('twig.environment');
$env->addExtension(new Extension(new Controller(Theme::getActiveTheme())));
return (new TwigEngine($env))->get($this->getViewPath('_gridmanager.htm'),
['patterns' => PatternOrder::orderBy('order')->with('pages')->get(),
'contents' => Content::all()]);
}
public function loadAssets() {
$this->addCss('css/gridmanager.css', 'Ftsf.Grid');
$this->addJs('js/gridmanager.js', 'Ftsf.Grid');
}
public function saveGrid(Request $request){
return dd($request);
}
}
If more information is needed just tell me what.
You should use the Octobers native AJAX handlers. The documentation is quite good for that in my opinion.
In that case the handler should look like this:
public function onSaveGrid(){
return dd(post());
}
You can make the request like this:
$.request('onSaveGrid', {
success: function() {
console.log('Finished!');
}
})
Of course you could also use the data-attributes API or call the handler on a DOM element. The documentation covers all these cases.

I can't create a view in Laravel

I'm new in Laravel and I'm trying to create a View in Acelle (app based on Laravel). I read a lot of tutorials, but I've not been luck with this problem.
I created the view "lol.blade.php" on /resources/views folder with this code:
HELLO (just hello)
The Route:
Route::get('lol', function()
{
if (view()->exists('lol')) {
//return 'helloooo'; <--- it works
return view('lol');
} else {
return 'not exists';
}
});
The code knows the view exists, but the url (localhost/acelle/public/lol) prints this message:
"Whoops, looks like something went wrong."
I can't solve the problem with tutorials. I followed all the steps about creating views in Laravel, but I don't know why the view prints that message.
Please help!
PS: Laravel version: 5.2.45
EDIT:
In console [network] shows Error 500. and laravel.log prints 59 lines. but the first line show:
[2017-07-14 14:08:20] production.ERROR: ErrorException: Undefined index:controller in /home/acelle/public_html/acelle/app/Providers/AppServiceProv‌​ider.php:20
You posted this in the comments:
app('view')->composer('*', function ($view) {
$action = app('request')->route()->getAction();
$controller = class_basename($action['controller']);
list($controller, $action) = explode('#', $controller);
$view->with(compact('controller', 'action'));
});
Your issue is that this route uses a closure, and has no controller:
Route::get('lol', function() {});
Therefore, $action['controller'] doesn't exist and throws a warning as a result. You'll want to check isset($action['controller']) before doing the rest of your code that uses the controller variable.
Already solved!!
SOLUTION:
creating a controller : MiwebController.php
<?
namespace Acelle\Http\Controllers;
class MiwebController extends Controller
{
public function __construct()
{
parent::__construct();
$this->middleware('auth');
}
public function index()
{
return view('lol');
}
}
?>
routes.php:
Route::get('lol', 'MiwebController#index');
It works fine. Thank you!

Can't "get" data in get ajax request using laravel

I just can't retrieve the data in my query string section.
I've used AJAX request throughout my website to implement a wide variety of tasks asynchronously and didn't had an issue of this kind.
Route
Route::get('/mensagem/enviar_mensagem', [ 'as' => 'mensagem.enviar_mensagem', 'uses' => 'MensagemController#enviar_mensagem']);
the testing url:
http://mydomain.com.br/mensagem/enviar_mensagem?para=email#bol.com.br
my action method:
public function enviar_mensagem(Request $request)
{
$para = $request->get('para');
//$para = $_GET['para']; I get an undefined index error
echo $para; //always empty string!
}
You need to use input. Like so:
Also, for testing, return versus echo.
public function enviar_mensagem(Request $request)
{
$para = $request->input('para');
return $para;
}
And to spark my curiosity, what does return $request->all() return?
Well, the provided code seems to be correct. Make sure you use \Illuminate\Http\Request. This code
Route::get('/mensagem/enviar_mensagem', function(\Illuminate\Http\Request $request) {
return $request->para;
// return $request->get('para'); // also works
});
returns email#bol.com.br by request http://your-site.app/mensagem/enviar_mensagem?para=email#bol.com.br
I copy pasted your code and both works:
$para = $request->get('para');
$para = $_GET['para'];
//$para = $_GET['para']; I get an undefined index error
Did you make sure the webserver is properly handling the HTTP request?
https://laravel.com/docs/5.4#web-server-configuration
You can try with below code :
use Request;
class xyzController {
public function enviar_mensagem()
{
$para = Request::all();
echo $para['para'];
}
}
First you will need to change the route to add also this
Route::get('/mensagem/enviar_mensagem/{para}',
[ 'as' => 'mensagem.enviar_mensagem', 'uses' =>
'MensagemController#enviar_mensagem']);
And after that in controller
public function enviar_mensagem($para){
return var_dump($para);
}
Use the route method on the request object to access GET parameters
public function enviar_mensagem(Request $request)
{
$para = $request->route('para');
echo $para;
}

Laravel 5.4: Custom view for route-model-binding not finding the ID

As I'm beggining with Laravel, this should be a simple one:
How can I define a custom view to be rendered when my route model binding just can't find the given ID?
Here's my route:
Route::get('/empresa/edit/{empresa}', 'EmpresaController#edit');
Here's my controller's method:
public function edit(Empresa $empresa)
{
if ((!isset($empresa)) || ($empresa == null)):
//I get that this won't work...
return 'Empresa não encontrada';
endif;
return view('Empresa.dadosEmpresa')->with('empresa', $empresa)->with('action', URL::route('empresa_update', ['id', $empresa->id]))->with('method', 'PATCH');
}
Here's my "attempt" to use an error handler:
public function render($request, Exception $exception)
{
if ($e instanceof ModelNotFoundException)
{
//this is just giving me a completely blank response page
return 'Empresa não encontrada';
}
return parent::render($request, $exception);
}
How is this really done?
1. The formal way (but would it be really needed to customize in this way?)
First of all, what Laravel does is, if there is not Model Row in DB with the given id, it sends 404 response, automatically.
If a matching model instance is not found in the database, a 404 HTTP response will be automatically generated.
So if you wanna show your customized view, you need to customize error handling.
So in RouteServiceProvider file, make sure it throws custom exception using 3rd param like follwoing:
public function boot()
{
parent::boot();
Route::model('empresa', App\Empresa::class, function () {
throw new NotFoundEmpresaModelException;
});
}
And then do same thing in the render function as you tried before.
2. The casual way - Pretty easy to go
I d rather suggest that you do not use model injection ability, but handle the request yourself.
So take the empresa id value as it is, and then try to find the right data, and if not found, then make your custom logic. That should be pretty easy to go.
public function edit(Request $request, $empresa)
{
$empresaObj = Empresa::find($empresa);
if (!$empresa) {
return 'Empresa não encontrada';
}
return view('Empresa.dadosEmpresa')->with('empresa', $empresa)->with('action', URL::route('empresa_update', ['id', $empresa->id]))->with('method', 'PATCH');
}

How to communicate with the controller using AJAX in Laravel?

I'm using CodeIgniter for over a year now (and got pretty used to it) then found out that it is getting outdated and support has been taken off by ellislab. I want to try using Laravel as an alternative though CodeIgniter still works just fine but for Future purposes, I don't want to get left behind. Now, with Laravel's MVC framework it was easy for me to migrate some of my projects from CI. I'm having a problem with Laravel's routing though as I'm not able to communicate with my controller. Here's a bit of my code:
controller.php:
public function connect() {
$this->load->model('home_model');
if ($DBconnect=$this->home_model->checkConnection()) {
echo json_encode(array(
"success" => true,
"db_connect" => $DBconnect
));
} else {
echo json_encode(array(
"success" => false,
"db_connect" => $DBconnect
));
}
}
view.js:
$("#connection").click(function(e) {
e.preventDefault();
show_loading();
$.get('./home/connect', function(data) {
hide_loading();
Materialize.toast(data.db_connect, 4000, 'rounded green');
}, "json");
});
PS: Am I doing the Laravel way or I'm still very CI minded?
This is my way to connect with the controller
First set up the routes.php :
Route::controller('/','MyController');
On the controller app/controller/MyController.php (You need to create one) :
<?php
class MyController extends BaseController {
public function getJustASampleText(){
echo "Hello World";
}
public function getJustASampleSmile(){
echo ":D";
}
public function getConnect(){
$var_value = "Hello world";
return Response::json(array('var_name' => $var_value));
}
}
Then you can call that function like this
domain.com/just-a-sample-text or
domain.com/just-a-sample-smileor in you case
$.get(`http://127.0.0.1/laravel/public/connect`,function(data){
alert(data.var_name);
})
That how we use Route::controller approach.

Categories