It's just since I started to discover slim and I ran into a problem, I do not know how to look for a solution because it is very strange.
Basically if I declare a function that is called from the route after another function is also called by a route, the first is not performed.
API group
// API group
$app->group('/api/:key', function () use ($app) {
//print all route
$app->get('/all',function () use($app){
echoRoutes();
});
// Library group
$app->group('/themer', function () use ($app) {
//get number of subscribed themer
$app->get('/count','allowed',function (){
echo "ciao";
});
//get information about the themer selected
$app->get('/:id','getThemer'); //AFTER THIS ROUTES /ciao AND /themes NOT WORK
$app->get('/ciao',function () use($app){
echoRoutes();
});
// Get book with ID
$app->get('/themes', function () use ($app) {
$articles = R::findAll('users');
$app->response()->header('Content-Type', 'application/json');
echo json_encode(R::exportAll($articles));
});
//get number of submitted theme by themer
//$app->get('/:id/themes','getSubmitedThemeById');
//get information about selected theme
//$app->get('/:id/themes/:theme','getThemeById');
$app->get('/themes/:id/', function ($id) {
$articles = R::find("users","id = ?",[$id]);
echo json_encode(R::exportAll($articles));
});
});
});
external file with function
//external file with function
function getThemer($key,$id) {
$themer = R::find("themers","id = ?",[$id]);
echo json_encode(R::exportAll($themer));
return true;
}
function countThemer(){
echo "count";
$count = R::exec( 'SELECT COUNT(id) FROM themers' );
echo $count;
}
function allowed($key){
$app = \Slim\Slim::getInstance();
$params = $app->router()->getCurrentRoute()->getParams();
if(!($params["key"]=="giulio"))
$app->redirect ("http://google.com");
}
after the route index.php/api/giulio/themer/1 that call getThemer and work the route index.php/api/giulio/themer/ciao and index.php/api/giulio/themer/themes not work
I thank you in advance for possible help
criticism or comments on the code in 'general appearance are welcome
Change the order of the routes:
// API group
$app->group('/api/:key', function () use ($app) {
//print all route
$app->get('/all',function () use($app){
echoRoutes();
});
// Library group
$app->group('/themer', function () use ($app) {
//get number of subscribed themer
$app->get('/count','allowed',function (){
echo "ciao";
});
$app->get('/ciao',function () use($app){
echoRoutes();
});
// Get book with ID
$app->get('/themes', function () use ($app) {
$articles = R::findAll('users');
$app->response()->header('Content-Type', 'application/json');
echo json_encode(R::exportAll($articles));
});
//get number of submitted theme by themer
//$app->get('/:id/themes','getSubmitedThemeById');
//get information about selected theme
//$app->get('/:id/themes/:theme','getThemeById');
$app->get('/themes/:id/', function ($id) {
$articles = R::find("users","id = ?",[$id]);
echo json_encode(R::exportAll($articles));
});
//get information about the themer selected
$app->get('/:id','getThemer');
});
});
Related
I have a controller that creates a new model then passes it to the view
public function fill_site_form($id, $step_id, $form_id){
$form = new FormEntry();
$form->site_id = $id;
$form->form_id = $form_id;
$form->step_id = $step_id;
$form->entry_json = Form::find($form_id)->form_json;
$form->save();
return view('sites.fill_site_form', ['form' => $form]);
}
I need it to only create one record in the db but it creates 2 records everytime I go to that route.
I have removed the ->save and then no records are inserted into the DB.
Any suggestions?
Edit:
Image of DB entries on the $form->save:
SCREENSHOT IMAGE LINK
The DB Schema:
Schema::create('form_entries', function (Blueprint $table) {
$table->increments('id');
$table->integer('site_id');
$table->integer('form_id');
$table->integer('step_id');
$table->text('entry_json', 600000);
$table->timestamps();
});
The code that receives the ajax from the sites.fill_site_form view
public function update_site_ajax($id, Request $request){
$entry = FormEntry::find($id);
$entry->entry_json = json_encode($request->form_json);
$entry->save();
return $request->all();
}
Front end AJAX code:
$('#submit_button').click((e)=>{
$.ajax({
type:'PATCH',
url:'/site/' + document.getElementById('form_id').value,
data: {'form_json' : renderer.userData},
success:function(data){
$.notify("Form successfully Updated!",
{
position:"top center",
className: 'success'
}
);
console.log('Response: ', data)
}
});
});
I couldn't get it working with Model::create or Model->save, So I resorted to Model::firstOrCreate which looks more stable, still would like to know why only on that model it creates two entries
I'm trying to return a view from a sub-directory however when using the code below I get the error "Undefined variable: folder1"
Route::get('/', function () {
return view("folder1/page1");
});
or
Route::get('/', function () {
return view("/folder1/page1");
});
or
Route::get('/', function () {
return view("folder1.page1");
});
The view "page1" is located in a folder called folder1, for example...
How do you return a view that's not located in the same directory?
In laravel, by default views are stored in resources/views directory. Your view, page1.blade.php file is in resources/views/folder1 directory. To return the view, we can use the global view helper as follows,
return view('folder1.page1');
For your case above, you can do this
Route::get('/',function(){
return view('folder1.page1');
});
If you want to pass data into the view, there are many methods to do that,
you can use this
$data1= 'Sample data 1';
return view('folder1.page1',['data1'=>$data1]);
Or
$data1 = 'Sample data 1';
returnn view('folder1.page1')->with('data1',$data1);
Or
$data1 = 'Sample data 1';
return view('folder1.page1')->compact('data1');
Or
$data1 = 'Sample data 1';
return view('folder1.page1',compact('data1'));
you can try as below
Route::get('/', function () {
return view("folder1.page1",compact('products'));
});
The problem is not the view itself, the problem is that you're not passing the view the $product variable it's using within the view to render data from a product / products.
Try something like this:
Router::get('/', function() {
return view('folder1.page1', ['products' => App\Product::all()]);
}
I have a Route as below that will display a profile depending on the data in the url:
Route::get('/{region}/{summonername}', function () {
return 'Summoner Profile';
});
I have a Form on the Home page which consists of a Input Box and Region Selector. I am posting this data to:
Route::post('/summoner/data');
The problem is that i don't know how i can convert the form data eg. Summoner Name and Region into the url format where the user will be displayed with the profile page and the url would be /{region}/{summonername}. Am i supposed to use a Redirect::to inside my controller? I feel like that is a crappy way of doing it. Any Suggestions?
Right now when i post the data the url displays as '/summoner/data'.
I hope this makes sense, let me know if you need more clarification.
Routes :
Route::post('/summoner/data','ControllerName#FunctionName');
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Controller:
public function FunctionName()
{
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{$Region}/{$SummonerName}');
}
Hope this will work. Try it!
Using Routes:
Route::post('/summoner/data',function () {
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{'.$Region.'}/{'.$SummonerName.'}');
});
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Yes, you will need to redirect:
Route::post('/summoner/data', function (Request $request) {
return redirect()->url($request->region .'/'. $request->summonername);
});
If you want to take the data from URL, just do the following
use Illuminate\Http\Request;
Route::post('/summoner/data', function (Request $request) {
echo $request->segment(1); // gives summoner
echo $request->segment(2); // gives data
});
I've wrote a controller to have it's index to output the DataTables plugin data.
A excerpt:
public function index() {
return Datatable::collection(\App\Slip::where('paid', '=', false)->get())
...
->make();
}
and the route:
Route::resource('api/slip', 'SlipsController');
everything works fine, the problem is that this index return only items with paid = false that's right for one view, but for the other view I need all items/rows.
so what's the best practice to make index function cover both cases (all and those with paid = false)?
A post param is the first thing that comes to my mind, but the data is loaded by the DataTables plugin.
Why not?. You need detect your specified view and send some extra param in ajax-request. Like:
$('...').DataTable({
....
"ajax": {
'type': 'GET',
'url': "....",
'data': {paid: false},
},
....
});
Now in action:
public function index(Request $request) {
$paid = $request->input('paid');
$items = [];
if ($paid){
$items = \App\Slip::all()->get();
}else{
$items = \App\Slip::where('paid', '=', false)->get();
}
return Datatable::collection($items)
...
->make();
}
How can I categorise routes in Slim Framework?
I have these basic/ front routes in my public dir,
$app->get('/about', function () use ($app, $log) {
echo "<h1>About ", $app->config('name'), "</h1>";
});
$app->get('/admin', function () use ($app, $log) {
echo 'admin area';
require dirname(__FILE__) . '/../src/Admin/index.php';
});
// To generic
$app->get('/', function () use ($app, $log) {
echo '<h1>Welcome to ', $app->config('name'), '</h1>';
});
// Important: run the app ;)
$app->run();
As you can see that when the route is on /admin, it will load the index.php in Admin directory.
Admin/index.php,
// API group
$app->group('/admin', function () use ($app) {
// Contact group
$app->group('/contact', function () use ($app) {
// Get contact with ID
$app->get('/contacts', function () {
echo 'list of contacts';
});
// Get contact with ID
$app->get('/contacts/:id', function ($id) {
echo 'get contact of ' . $id;
});
// Update contact with ID
$app->put('/contacts/:id', function ($id) {
echo 'update contact of ' . $id;
});
// Delete contact with ID
$app->delete('/contacts/:id', function ($id) {
echo 'delete contact of ' . $id;
});
});
// Article group
$app->group('/article', function () use ($app) {
// Get article with ID
$app->get('/articles', function () {
echo 'list of articles';
});
// Get article with ID
$app->get('/articles/:id', function ($id) {
echo 'get article of ' . $id;
});
// Update article with ID
$app->put('/articles/:id', function ($id) {
echo 'update article of ' . $id;
});
// Delete article with ID
$app->delete('/articles/:id', function ($id) {
echo 'delete contact of ' . $id;
});
});
});
Let's say I have article, contact, etc modules in my admin area. In each of these modules I have routes for get, put, delete. So I group them by module as in Admin/index.php. But I get 404 page not found, when I request these modules on my url, for instance http://{localhost}/admin/contact I should get list of articles on my browser but I get a 404.
I don't have this problem if I put the grouped routes in public/index.php but I don't want to clutter this index as in time I have more modules to add in. I prefer splitting the routes into different indexes.
So is it possible to split the grouped routes into different index.php in different locations (directories).
Or maybe this is not how I should do it in Slim? if so, what is Slim's way for solving this problem?
In your code /admin/contact is the group for the routes that handle the contacts' GET/PUT/DELETE
// see here v
$app->group('/contact', function () use ($app) {}):
If you want to have a route with this URL segment then you should replace group with get
maybe you can remove the groups within the admin
// API group
$app->group('/admin', function () use ($app) {
// Contact group
// $app->group('/contact', function () use ($app) {
// Get All Contacts
$app->get('/contacts', function () {
echo 'list of contacts';
});
// Get contact with ID
$app->get('/contacts/:id', function ($id) {
echo 'get contact of ' . $id;
});
// Update contact with ID
$app->put('/contacts/:id', function ($id) {
echo 'update contact of ' . $id;
});
// Delete contact with ID
$app->delete('/contacts/:id', function ($id) {
echo 'delete contact of ' . $id;
});
// });
});
Then you can access the routes as follow
Get All -> admin/contacts
Get One -> admin/contacts/:id
Update -> admin/contacts/:id