Laravel about Requests - laravel

i am new in programing laravel. so here I will not ask about my problems but I am here just want to ask how to use laravel. here I would like to ask how to use:
Determining If an Input Value Is Present in laravel. and what it does?
thanks ^^

Laravel is really a good MVC Framework.
I can suggest you some source from where you can get better understanding of Laravel Framework.
https://laravel.com/docs/5.2
https://laracasts.com/skills/laravel
For simple example - How to use Laravel after installation
Go to path using terminal ex. /var/www/laravel/project
Go to - /var/www/laravel/project/resources/views
Create a directory test and create a file index.php
Create a controller - php artisan make:controller TestController
Create a function testGet() and return view - return view('test.index'); //test is directory and index is file
Create a function testPost(Request $request) and to get data use $data = $request->all(); and then print this data.
Create a model with migration file - php artisan make:model Test --migration
Go to route file - /var/www/laravel/project/app/Http/routes.php
Add line Route::get('/test', 'TestController#testGet');
Add line Route::post('/test', 'TestController#testPost');
Now check GET request to your project http://project/test it will call testGet function.
POST request http://project/test?name=Adam will call testPost function and will print your name.

as said in the comments you better check laracasts! its the laravel school
anyway to anwser your question, its simple
View
<input type="text" name="fname">
Controller
public function doingstuff (Illuminate\Http\Request $request) {
if ($request->has('fname')) {
// a man gotta do what a man gotta do here
}
}
smooth huh? :3

Related

Best way share data across all view in Laravel

I have some data that I want to share across all views. I am using AppServiceProvider's boot method to share data.it is working fine with MySQL however with pgsql when I run composer or PHP artisan commands I am getting the following error,(i do fresh and seed database very often)
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "news" does not exist
it took me a while to understand where is the real issue. I m still unable to understand if it is pgsql related error or something else, bellow is code in AppServiceProvider. if I comment this code everything works fine except where I m using this.
public function boot()
{
$activeClubs = (new TournamentService())->getAllActiveClubs();
$activeNews = (new TournamentService())->getActiveNews();
$activeTournaments = (new TournamentService())->getActiveTournament();
View::share(['activeClubs' => $activeClubs, 'activeTournaments' => $activeTournaments, 'activeNews' => $activeNews]);
}
can you please help me that how can i share data across all views that i don't get this error in future.
you can determine if the app is running from console or not and prevent loading data in console
if ( !app()->runningInConsole() ){
// it's not console.
}
you mentioned you want to load this data in all views but sometimes, its one view that loaded in all of your views e.g. the layout.app view.
if its the case I recommend using view composers instead of View::share() as it will pass the data to that view before render and it will only run if that view is included in the page (so basically it will solve your problem even without app()->runningInConsole() condition required )
view composers doc
simple example:
View::composer('view-name', function ($view) {
$view->with('key', 'value');
});

Lumen: Using Models without Eloquent

Is it possible to have Eloquent disabled in lumen bootstrap file and still use Lumen (Eloquent) Models?
Short answer: Thanks to #El_Matella for his correct answer. It's impossible to use Lumen Models without having Eloquent enabled.
Description of problem I faced: I was unable to use lumen models while having eloquent disabled. I added a custom validator in AppServiceProvider boot method and boom! Lumen models works! What happens is that ValidationServiceProvider enables eloquent:
https://github.com/laravel/framework/blob/5.3/src/Illuminate/Validation/ValidationServiceProvider.php#L57
$this->app->singleton('validation.presence', function ($app) {
return new DatabasePresenceVerifier($app['db']);
});
$app['db'] causes following function calls:
./vendor/illuminate/validation/ValidationServiceProvider.php(57): Illuminate\Container\Container->offsetGet('db')
./vendor/illuminate/container/Container.php(1182): Laravel\Lumen\Application->make('db')
Which Application->make('db') is equal to $app->withEloquent()!

Search object by slug and not by id

I'm a relative beginner with Laravel (using version 5.2.3) and have been working through tutorials on Laracasts and then doing a bit of my own experimenting.
I successfully set up a route that fetches an item from a table by its ID, as shown below
Route::get('/wiseweasel/{id}', 'WiseweaselController#singleArticle');
For simplicity, the controller simply dd's the article
public function singleArticle($id)
{
$article = ww_articles::find($id);
dd($article);
}
This works absolutely fine - I visit eg /wiseweasel/2 and get the contents of the record with id2.
So, I then wanted to use the slug field from the record instead of the id. Since I know the ID method was working, I've tried just modifying this route and controller (also tried creating anew, neither worked) So I now have:
Route::get('/wiseweasel/{slug}', 'WiseweaselController#singleArticle');
and
public function singleArticle($slug)
{
$article = ww_articles::find($slug);
dd($article);
}
The slug for the second record is "secondarticle". So, visiting the url /wiseweasel/secondarticle, I would expect to see the same record as previously dd'd out. Instead, I end up with null.
Even more oddly, using the original id route (/wiseweasel/2) still returns the record... when I have removed all trace of this from the routes and controller, so I would expect this to fail...
This is making me wonder if this could be some odd caching issue? I've tried
php artisan route:clear
in case the route was being cached. I've also tried restarting both Apache and MySql (I'm using XAMMP for both).
Still no luck though... not sure if I've misunderstood how something works or what's going on... so if anyone has any suggestions as to what I might have done wrong, or anything to try, I would be very grateful! :)
You also have the option of using Route Model Binding to take care of this and inject the resolved instance into your methods.
With the new implicit Route Model Binding you can tell the model what key it should use for route binding.
// routes
Route::get('/wiseweasel/{article}', 'WiseweaselController#singleArticle');
// Article model
public function getRouteKeyName()
{
return 'slug';
}
// controller
public function singleArticle(Article $article)
{
dd($article);
}
Laravel Docs - Route Model Binding
Laravel won't automatically know that for slug it should search record in different way.
When you are using:
$article = ww_articles::find($slug);
you are telling Laravel - find record of www_articles by ID. (no matter you call this id $slug).
To achieve what you want change:
$article = ww_articles::find($slug);
into
$article = ww_articles::where('slug', $slug)->first();
This will do the trick (for slug put the name of column in table in database). Of course remember that in this case slug should be unique in all records or you won't be able to get all the slugs.
Maybe it's a bit late for the answer but there is another way to keep using find method and use slug as your table identifier. You have to set the protected $primaryKey property to 'slug' in your model.
class ww_articles extends Model
{
protected $primaryKey = 'slug';
...
}
This will work because find method internally uses the getQualifiedKeyName method from Model class which uses the $primaryKey property.
If you have both routes like this
Route::get('/wiseweasel/{id}', 'WiseweaselController#singleArticle');
Route::get('/wiseweasel/{slug}', 'WiseweaselController#singleArticle');
it will always use the first one. Obviously, there is no id 'secondarticle', so it returns null (although in this case it doesn't matter, they both point to the same method).
The reason is route will search through possible routes till it finds a matching, which is always the one with {id}. Why? You're not telling Route that {id} must match an integer!
You can make sure {id} is understood as an integer, however I suggest using urls like this is a better option
/wiseweasel/{id}/{slug?}
Another suggestion. Do not use names such as xx_articles for a model, but Article instead. This way you can use the new implicit route binding. So using implicit route binding your url would look like this (assuming your model is called Article)
Route::get('/wiseweasel/{article}', 'WiseweaselController#singleArticle');

How can I render a twig template in a custom controller in Silex?

I'm playing with Silex microframework to build a very simple app.
The Silex documentation briefly illustrates how to keep your code organised using controller as class and I've also found this useful article talking about the same practice:
https://igor.io/2012/11/09/scaling-silex.html
but still can't solve my problem
The issue:
in my app.php I'm using
$app->get('/{artist}', 'MyNamespace\\MyController::getAlbum');
This is working. MyController is a class correctly loaded through composer using psr-4.
At the moment the return method of getAlbum($artist) is return $player;
What I'd like to do instead, is returning a twig view from getAlbum, something like:
return $app['twig']->render('player.twig', $player);
To do so, what I've tried to do in my custom class/controller is:
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
[...]
public function getAlbum(Request $request, Application $app, $artist)
but this is generating the following error when I try to access the routed pages:
ReflectionException in ControllerResolver.php line 43:
Class MyNamespace\Request does not exist
Whic made me think that there's a namespace conflict between myNamespace and the Silex namespaces?!
What am I doing wrong?
Is this the right way to make $app visible in my custom controller in order to use return $app['twig']... ?
Thank you in advance!
EDIT
After several other tries still didn't get to the point (replies still welcome!) but I've found a workaround solution that could be useful to anyone will incur in a similar issue. Directly in my app.php I added this
$app->get('/{artist}', function (Silex\Application $app, $artist) use ($app)
{
$object = new MyNamespace\MyController();
$player = $object->getAlbum($artist);
return $app['twig']->render('player.twig',
array(
//passing my custom method return to twig
'player' => $player,));
});
then in my player.twig I added:
{{player | raw}}
And this basically means that I still need an anonymous function to get use of my custom method which is a working solution I'm not really happy with because:
I'm using 2 functions for 1 purpose.
The return value of getAlbum is dependent from the use of "raw" in twig.
SOLVED
The workflow described works fine. It was a distraction error: I've placed the namespace of my custom class after use Symfony\Component\HttpFoundation\Request;
namespace declaration in PHP needs always to be at the top of the file, Silex wasn't able to injects $app and $request for this reason.

Form open to controller method - "Unknown action"

New to Laravel 4. I've created a form within a blade template and I'm following the snippet from which says that you can point a forms action to a controller method by using 'Form::open(array('action' => 'Controller#method'))'. I've created a new controller called UsersController with artisan and have created a new method within the controller named userLogin(). When I point to that method when opening a form I get an "InvalidArgumentException, Unknown action" error. If I adjust the open action to point to UsersController#index, all is well. I've run composer dump-autoload, but the issue remains.
snippet of login.blade.php:
{{ Form::open(array('action' => 'UsersController#userLogin')) }}
snippet of UsersController.php:
public function userLogin()
{
//
}
Can anyone tell me if I'm missing something?
Thanks all. Adding the following to routes.php resolved the issue:
Route::post('login', 'UsersController#userLogin');
Looks like Laravel isn't registering the action you've added, likely because you're missing a route. Try adding something like this to app/routes.php:
Route::post('user/login', 'UsersController#userLogin');
After adding the route to your routes.php, did you also change Form::open()? If not, you can just have your Form post to /login or /user/login.
Also, just because I'm a bit of a stickler for these sort of things, it's common practise to have controllers and models as singular, so UsersController would be UserController, and since the login function is within User(s)Controller, it doesn't need the user prefix. May help your code be more readable :)
Now in laravel 4 you can use this :
Route::post('/signup', array('before' => 'csrf', 'uses' => 'UsersController#userLogin'));

Resources