My problem is that when I send a post from an rfid card via esp8266, the data is an rfid number, but the data can't appear because the code I gave has not been written into Laravel.
This PHP code :
<?php
if(isset($_POST['uid'])) {
$uid = $_POST["uid"];
$sql = mysqli_query($dbconnect, "INSERT INTO tb_entry VALUES ('$uid')");
}
?>
How can I write this code into Laravel controller?
it should be like this
if ($request->has('uid')) {
DB::table('tb_entry')->insert([
'uuid' => $request->uuid
]);
}
create a controller: php artisan make:controller MyController
add a method to the controller like public function test(Request $request) {}
rewrite your code a little bit and pasted in:
public function test(Request $request) {
if (null !== $request->post('uid')) {
$uid = $request->post('uid');
// Note: you can use Laravel model instead plain mysqli query
// ** Beware of SQL injection vulnerabilities! **
$sql = mysqli_query($dbconnect, "INSERT INTO tb_entry VALUES ('$uid')");
}
}
Related
I'm sending an URL hashed and when i get it i have to show a view on Laravel, so i have those functions on the controller and also some routes:
This are my routes:
Route::post('/sendLink', 'Payment\PaymentController#getPaymentLink');
Route::get('/payment?hash={link}', 'Payment\PaymentController#show');
And this are the functions i have on my controller:
public function getPaymentLink (Request $request){
$budgetId = $request['url.com/payment/payment?hash'];
$link = Crypt::decryptString($budgetId);
Log::debug($link);
//here to the show view i wanna send the link with the id hashed, thats why i dont call show($link)
$view = $this->show($budgetId);
}
public function show($link) {
$config = [
'base_uri' => config('payment.base_uri'), ];
$client = new Client($config);
$banking_entity = $client->get('url')->getBody()->getContents();
$array = json_decode($banking_entity, true);
return view('payment.payment-data')->with('banking_entity', $array);
}
And this is getting a "Page not found" message error.
What i want to to is that when i the client clicks on the link i send him that has this format "url.com/payment/payment?hash=fjadshkfjahsdkfhasdkjha", trigger the getPaymentLink function so i can get de decrypt from that hash and also show him the view .
there is no need to ?hash={link} in get route
it's query params and it will received with $request
like:
$request->hash
// or
$request->get('hash')
You need to define route like this:
Route::get('/payment/{hash}', 'Payment\PaymentController#show');
You can now simply use it in your Controller method like below:
<?php
public function getPaymentLink (Request $request,$hash){
$budgetId = $hash;
// further code goes here
}
I need to pass a variable on multiple views in order to perform an UPDATE on multiple views ( editScadenza and elaborazioneScadenza).
Or do you know another simpler solution?
ScadenzaController.php
public function edit($id)
{
$data['scadenzaRecuperata'] = \App\Scadenza::find($id);
return view('scadenze.editScadenza', $data);
}
UPDATE
public function update(Request $request, $id)
{
$this->validate($request,[
'titolo'=>'required',
'termine_stimato'=>'required',
'responsabile'=>'required',
'tipologia_id'=>'required',
'giorni_avviso'=>'required',
],
[
'titolo.required'=>'Il titolo é obbligatorio',
'termine_stimato.required' => 'Il termine stimato é obbligatoria',
'responsabile.required' => 'Il responsabile é obbligatorio',
'tipologia_id.required' => 'Il tipo é obbligatorio',
'giorni_avviso.required'=> 'I giorni di avviso sono obbligatori',
]);
$scadenza = \App\Scadenza::find($id);
$now = Carbon::now();
$end = Carbon::parse($scadenza->termine_stimato);
$length = $end->diffInDays($now);
$scadenza->titolo = $request->input('titolo');
$scadenza->termine_stimato = date_create($request->input('termine_stimato'))->format('Y-m-d H:i');
$scadenza->responsabile = $request->input('responsabile');
$scadenza->tipologia_id = $request->input('tipologia_id');
$scadenza->processo_id = $request->input('processo_id');
$scadenza->stato = $request->input('stato');
$scadenza->giorni_avviso = $request->input('giorni_avviso');
$scadenza->osservazioni = $request->input('osservazioni');
$scadenza->save();
return redirect('scadenza');
}
The best recommended solution is to share variables from the controller function. If you need it just for 2, 3 views and all comes under the same controller then share it as usual:
public function function_nameX($id)
{
..
return view('scadenze.viewNameX')->withData($data);
}
...
public function function_nameY()
{
..
return view('scadenze.viewNameY')->withData($data);
}
Do it even if you have views returned from multiple controllers. Because this is the most convenient way.
To share a variable with all views in your project, share it from AppServiceProvider's boot() function like:
public function boot()
{
$data['scadenzaRecuperata'] = \App\Scadenza::find($id);
View::share('data', $data);
}
View Composer also help to bind specific data to view in different
ways. You can directly bind variable to specific view or to all views.
For Example you can create your own directory to store your view
composer file according to requirement. and these view composer file
through Service provide interact with view.
Here is the doc.
To share data with views you can set a view Composer
in app/Providers/AppServiceProvider.php into boot() method
public function boot() {
view()->composer('scadenze.editScadenza', function($view) {
$data = \App\Scadenza::find(request()->id);
$view->with('data', $data);
});
}
For more date, see Laravel View Composers
if you need to share only with one: composer('VIEW_NAME', ...)
If you need to share the data with more than one: composer(['VIEW_NAME_1', 'VIEW_NAME_2'], ...)
If you need to share with all views: composer('*', ...)
I been trying to figure this out for some time now. Basically i got 2 models ' Recipe ', ' Ingredient ' and one Controller ' RecipeController ' .
I'm using Postman to test my API. When i go to my get route which uses RecipeController#getRecipe, the return value is as per the pic below:
Return for Get Route
If i want the return value of the get route to be in the FORMAT of the below pic, how do i achieve this? By this i mean i don't want to see for the recipes: the created_at column, updated_at column and for ingredients: the pivot information column, only want name and amount column information.
Return Value Format I Want
Recipe model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Recipe extends Model
{
protected $fillable = ['name', 'description'];
public function ingredients()
{
return $this->belongsToMany(Ingredient::class,
'ingredient_recipes')->select(array('name', 'amount'));
}
}
Ingredient Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ingredient extends Model
{
protected $fillable = ['name', 'amount'];
}
RecipeController
<?php
namespace App\Http\Controllers;
use App\Ingredient;
use App\Recipe;
use Illuminate\Http\Request;
class RecipeController extends Controller {
public function postRecipe(Request $request)
{
$recipe = new Recipe();
$recipe->name = $request->input('name');
$recipe->description = $request->input('description');
$recipe->save();
$array_ingredients = $request->input('ingredients');
foreach ($array_ingredients as $array_ingredient) {
$ingredient = new Ingredient();
$ingredient->name = $array_ingredient['ingredient_name'];
$ingredient->amount = $array_ingredient['ingredient_amount'];
$ingredient->save();
$recipe->ingredients()->attach($ingredient->id);
}
return response()->json(['recipe' => $recipe . $ingredient], 201);
}
public function getRecipe()
{
$recipes = Recipe::all();
foreach ($recipes as $recipe) {
$recipe = $recipe->ingredients;
}
$response = [
'recipes' => $recipes
];
return response()->json($response, 200);
}
API Routes:
Route::post('/recipe', 'RecipeController#postRecipe')->name('get_recipe');
Route::get('/recipe', 'RecipeController#getRecipe')->name('post_recipe');
Thanks Guys!
I think your best solution is using Transformer. Using your current implementation what I would recommend is fetching only the needed field in your loop, i.e:
foreach ($recipes as $recipe) {
$recipe = $recipe->ingredients->only(['ingredient_name', 'ingredient_amount']);
}
While the above might work, yet there is an issue with your current implementation because there will be tons of iteration/loop polling the database, I would recommend eager loading the relation instead.
But for the sake of this question, you only need Transformer.
Install transformer using composer composer require league/fractal Then you can create a directory called Transformers under the app directory.
Then create a class called RecipesTransformer, and initialize with:
namespace App\Transformers;
use App\Recipe;
use League\Fractal\TransformerAbstract;
class RecipesTransformer extends TransformerAbstract
{
public function transform(Recipe $recipe)
{
return [
'name' => $recipe->name,
'description' => $recipe->description,
'ingredients' =>
$recipe->ingredients->get(['ingredient_name', 'ingredient_amount'])->toArray()
];
}
}
Then you can use this transformer in your controller method like this:
use App\Transformers\RecipesTransformer;
......
public function getRecipe()
{
return $this->collection(Recipe::all(), new RecipesTransformer);
//or if you need to get one
return $this->item(Recipe::first(), new RecipesTransformer);
}
You can refer to a good tutorial like this for more inspiration, or simply go to Fractal's page for details.
Update
In order to get Fractal collection working since the example I gave would work if you have Dingo API in your project, you can manually create it this way:
public function getRecipe()
{
$fractal = app()->make('League\Fractal\Manager');
$resource = new \League\Fractal\Resource\Collection(Recipe::all(), new RecipesTransformer);
return response()->json(
$fractal->createData($resource)->toArray());
}
In case you want to make an Item instead of collection, then you can have new \League\Fractal\Resource\Item instead. I would recommend you either have Dingo API installed or you can follow this simple tutorial in order to have in more handled neatly without unnecessary repeatition
In my symfony 1.4 application i'm using doctrine data models.I'm new to symfony and doctrine.I generated doctrine models from command-line after defining database table information in the schema.yml file.Those generated successfully.Then i created a custom function inside Table.class.php file.Following is that.
class Table extends BaseTable
{
public function getuname()
{
$user=new Table();
$uname=$user->getUsername();
return $uname;
}
}
I want to know how to call this inside the controller ? I called it normal MVC application's way.But i don't know whether it's correct in symfony.In symfony 1.4 manual also i couldn't find a proper way to do this.
This is my controller.
class loginActions extends sfActions
{
public function executeIndex(sfWebRequest $request)
{
$this->userdata = User::getuname();
}
}
Then i tried to print this inside view.
<?php
echo $userdata;
?>
But view is showing an empty page.
Update with exception details--------------------------------
stack trace
at ()
in SF_SYMFONY_LIB_DIR\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Connection.php line 1082 ...
$message .= sprintf('. Failing Query: "%s"', $query);
}
$exc = new $name($message, (int) $e->getCode());
if ( ! isset($e->errorInfo) || ! is_array($e->errorInfo)) {
$e->errorInfo = array(null, null, null, null);
}
When using Doctrine you retrieve objects from the database using the ...Table classes (in your case it will be a TableTable class. You can use its' methods to fetch objects from DB (e.g. find($id)) and then access them. So in your case your classes should something like this:
class Table extends BaseTable
{
public function getuname()
{
return $this->getUsername();
}
}
Now it effectively becomes just an alias of getUsername().
Then in your action:
class loginActions extends sfActions
{
public function executeIndex(sfWebRequest $request)
{
$user = Doctrine_Core::getTable('Table')->find(123);
$this->userdata = $user->getuname();
}
}
This will print the username in your template (assuming of course that you have a user with id 123).
Codeigniter has its own Models path, where models extend from CI_Model. I'm using RedBean has a library in Codeigniter, loading it on a controller. After loading Rb, I try to use CI Loader to load a model that extends redbean_simplemodel (wish works, there's no error), but the events / methods inside the model have no effect when they're called on bean.
For example,
APPPATH/application/libraries/rb.php
class Rb {
function __construct()
{
// Include database configuration
include(APPPATH.'/config/database.php');
// Get Redbean
include(APPPATH.'/third_party/rb/rb.php');
// Database data
$host = $db[$active_group]['hostname'];
$user = $db[$active_group]['username'];
$pass = $db[$active_group]['password'];
$db = $db[$active_group]['database'];
// Setup DB connection
R::setup("mysql:host=$host;dbname=$db", $user, $pass);
} //end __contruct()
} //end Rb
And then on
APPPATH/application/models/model_song.php
class Model_song extends RedBean_SimpleModel {
public function store() {
if ( $this->title != 'test' ) {
throw new Exception("Illegal title, not equal «test»!");
}
}
}
while on
APPPATH/application/controllers/welcome.php
class Welcome extends CI_Controller {
public function index()
{
$this->load->library('rb');
$this->load->model('model_song');
$song = R::dispense('song');
$song->title = 'bluuuh';
$song->track = 4;
$id = R::store($song);
echo $id;
}
}
My question is, how to make RedBean (FUSE http://redbeanphp.com/#/Fuse) work on Codeigniter ?
Thanks for looking!
----- FOUND SOLUTION!
Actually, it's working! I was trying to place code under my model, method store(). That wont work! I tryed to place a new method called update() and it does work! Check the example below:
class Model_song extends RedBean_SimpleModel {
public function update() {
if ( $this->title != 'test' ) {
throw new Exception("Illegal title!");
}
}
}
The solution is the following:
"Assuming that you've already installed RedBean on Codeigniter"
1) Load the library for «redbean»
2) Using ci_loader, load the desired model (the model must extend redbean_simplemodel)
Thanks for looking! I hope this helps other people too.
The solution is the following:
"Assuming that you've already installed RedBean on Codeigniter"
Load the library for «redbean»
Using ci_loader, load the desired model (the model must extend redbean_simplemodel)