I am new to laravel and creating my first controller in this , i have created a file in directory app/controllers/ContactController.php and the code is
class ContactController extends BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
echo "hieeeeeeeeeeeeeeeee";
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
but if i hit url http://localhost:8000/contact it is showing me the error We need a map. am i missing something???please help me.
update
i also tried to add Route::get('contact', "contact#index"); in my routes.php.
i setup an user log in and register module through git-hub and it is working perfectly if i hit url http://localhost:8000/user/login
Update
my laravel version is laravel 4
output in console is 39023 Invalid request (Unexpected EOF)
I fully agree with the things #Raviraj Chauhan already pointed out. in addition, i want to add that your file seems to have a typo which can cause this kind of issue:
Rename your controller-class to ContactController and the containing file to ContactController.php (not contactCtroller.php).
Then add a route to your routes.php-file
Route::get("contact", "ContactController#index");
Generally pay attentions to common conventions and codings-practices, since laravel heavyly depends on concepts such as Convention over Configuration.
As Lukas also pointed out it might be smart to think about switching to Laravel 5 if you are just getting startet.
Anyway, let me finish by recommending laracasts, which is how i learned using laravel. It will only take you a couple of hours to dive deeply into the laravel-universe without to much knowledge needed in advance:
Laravel 4 From Scratch
Laravel 5 Funcamentals (no need to go through L4 from Scratch before)
Yes, There is a problem with your route.
If you want to point to a single method from a controller, then you have to specify a fullControllerName#methodName convention.
Fix your route in routes.php as:
Route::get('contact', "contactController#index");
Also please follow good class naming convention while using OOP.
Controller class name shold start with capital letter.
It should contain Controller at end.
So do fix by renaming your controller class name as well as controller file name, and do:
Route::get('contact', "ContactController#index");
And by easy way, do it by command line by running:
php artisan make:controller ContactController
Related
I am wondering how to register custom method within:
Illuminate/Foundation/Application.php
Like:
/**
* Get the current application name.
*
* #return string
*/
public function getName()
{
return $this['config']->get('app.name');
}
Taken from:
/**
* Get the current application locale.
*
* #return string
*/
public function getLocale()
{
return $this['config']->get('app.locale');
}
Where should I put this, instead of vendor file ofc?
Thanks
You maybe able to extend the Illuminate/Foundation/Application.php
example:
<?php
namespace app\Custom;
class Application extends \Illuminate\Foundation\Application
{
}
for more details, please refer this click here .
Note: Adding your code under vendor files, may lost during the composer update command. So its not advisable to actually add your custom codes there.
I'm teaching myself Symfony. And the routing doesn't make any sense.
I have a postController class with a few actions. Originally the crud generator from the command line gave me this;
/**
* Post controller.
*
* #Route("/post")
*/
class PostController extends Controller
{
/**
* Lists all Post entities.
*
* #Route("/", name="post_index")
* #Method("GET")
*/
public function indexAction()
{
//
}
//
}
What I want to achieve is to remove the #Route from the class itself. Thus I want my indexAction to be the the homepage, and all other actions in my class to still start with /post. For example, this is what I want;
class PostController extends Controller
{
/**
* Lists all Post entities.
*
* #Route("/", name="homepage")
* #Method("GET")
*/
public function indexAction()
{
//
}
/**
* Finds and displays a Post entity.
*
* #Route("post/{id}", name="post_show")
* #Method("GET")
*/
public function showAction(Post $post)
{
//
}
// what I want for the showAction should count for all other Actions as well
}
When I make the change I get an error;
No route found for "GET /post/"
Can somebody please explain to me what I'm doing wrong and how to fix this. I don't think it is something major, it's probably something small that I just don't see. I want to make that indexAction my main action, the action when the website opens after a user logged in. Thank you
Your route specification requires {id} parameter which is obligatory so there's no "GET /post/" route indeed. You need to do one of the following
Pass id value and access /post/1 for example
Remove {id} from route specification and then you can access /post/
Pass default value for id so you can access both /post/ and /post/1. To do that your route specification should look like #Route("post/{id}", name="post_show", defaults={"id" = 1})
No route found for "/post/" is correct
because there is no route "/post/"
in your example theres only "/" and "/post/{id}"
so it makes perfect sense, i prefer to use the yml notation and prefixes so its not bound to a class
check the "YAML" tabs in the DOCS
I am attempting to add a function to my site that shows the number of logged in guests and registered users(displaying the names of the registered users as well but I can figure out that part). Presently, I have read that I need to change the /config/Session.php file 'driver' to use database instead of file ('driver' => env('SESSION_DRIVER', 'database'),). I found an article that uses Sentry to accomplish this (http://laravel.io/forum/03-03-2014-sentry-3-users-online), however, I would prefer to do this without requiring third party files. I have, nonetheless, used his information as a starting point for now utilizing a model for the session.
As for the issues, first off, I am unable to actually get the session to start saving in my database 'sessions' table even after modifying Session.php, creating the table and migrating it. It is still saving in files in /storage/framework/session/ (I can still log in and display the session information using Session::all()).
mysql> select * from sessions;
Empty set (0.00 sec)
Second issue, I don't know how I am to create the session if one does not already exist given in his file, there is no way to create (if someone just opens up the site and are thus, a guest) nor unregister a user when they log out (remove their logged-in status as well as their user_id so they are seen as guest).
Here is my current OnlineUser.php file:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
// use Sentry;
use Session;
use Auth;
class OnlineUser extends Model {
/**
* {#inheritDoc}
*/
public $table = 'sessions';
/**
* {#inheritDoc}
*/
public $timestamps = false;
/**
* Returns all the guest users.
*
* #param \Illuminate\Database\Eloquent\Builder $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeGuests($query)
{
return $query->whereNull('user_id');
}
/**
* Returns all the registered users.
*
* #param \Illuminate\Database\Eloquent\Builder $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeRegistered($query)
{
return $query->whereNotNull('user_id')->with('user');
}
/**
* Updates the session of the current user.
*
* #param \Illuminate\Database\Eloquent\Builder $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeUpdateCurrent($query)
{
return $query->where('id', Session::getId())->update(array(
'user_id' => !empty(Auth::user()) ? Auth::user()->id : null
));
}
/**
* Returns the user that belongs to this entry.
*
* #return \Cartalyst\Sentry\Users\EloquentUser
*/
public function user()
{
return $this->belongsTo('\App\User');
//return $this->belongsTo('Cartalyst\Sentry\Users\EloquentUser'); # Sentry 3
// return $this->belongsTo('Cartalyst\Sentry\Users\Eloquent\User'); # Sentry 2
}
}
If anyone has any information to assist me in solving these problems, I would be much obliged. If you need more information, let me know and I will respond when I am able to.
Thanks.
In response to the first issue where Laravel still save the session in /storage/framework/session/
if you updated your session.php file as follows:
env('SESSION_DRIVER', 'database')
make sure you also update your .env file
SESSION_DRIVER=database
Is it possible to store data in one private variable of a controller (Symfony2)?
One example:
/**
* Class CatsController
*
* #Route("cats")
* #Cache(expires="+600 seconds", public=true)
* #package oTeuGato\AppBundle\Controller
*/
class CatsController extends Controller {
/**
* #var $advertisements Advertisement[]
*/
private $advertisements;
/**
* Index advertisements page
*
* #Route("", name="oTeuGato_Cats")
* #Method("GET")
* #return Response
*/
public function indexAction()
{
$this->advertisements = ....(Use a service for gets advertisements)
}
/**
* Index advertisements by page
*
* #Route("/{id}", requirements={"id" = "\d+"}, defaults={"id" = 1}, name="oTeuGato_Cats_ByPage")
* #Method("GET")
* #return Response
*/
public function indexByPageAction(){
....
}
In this example whenever someone calls the URL: cats/1 in the controller I need them to have all advertisements of the previously called method (/cats).
Is this possible?
Note:
I enabled the cache in the app.php file and app_dev.php.
Thanks for help and sorry for my English ;)
Symfony doesn't provide a mechanism for what you are describing. But any solution that would work for PHP more generally, will work for Symfony.
It depends if you want to remember advertisements for each user or for all users. If you want to remember it for each user, use sessions as Gareth Parker suggested. If you want to remember it for all users, then you would need APC user caching, memcache or another memory-based key-value store.
You may also have luck using Doctrine result cache. See http://doctrine-orm.readthedocs.org/en/latest/reference/caching.html
No, it's not. Not like that, anyway. What you want is to use sessions instead. Sessions are what you use to store variables between requests. Here are some examples
I was developing codeigniter app for last 2 years and since i started my mvc pattern styling from codeigniter itself, now i'm not a heavy command line user so at first i did had some learning curve with codeigniter but i crossed it and started developing apps with code igniter because we don't need to configure a lot and everything was inside one zip file but now as unfortunately codeigniter is dead and i'm just one person in my team i have to rely on other third party tools which are trusted by others so i decided to switch to laravel, now at starting it was way way tough to migrate from codeigniter because composer and every other stuff, but somehow i crossed that too, but i'm now confused with routing and other stuff and i've tried many tutorials but i'm still not able to see how can i migrate from application where i'm managing students, where they can change email, change phone number updated stuff, in codeigniter it was easy but i don't how to approach this stuff in routing of laravel, now this question sounds way to dumb for community who is already working on laravel but if you see from my point of view it is going to affect my bread and butter. This is how i use to approach in codeigniter
class Student extends CI_Controller{
// usual piece of code of constructor
function update_email()
{
// piece of code to update email
}
}
but now with laravel routing system and all i've no idea how to approach this a resource controller looks like this
<?php
class StudentController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
now every part is okay but how can i approach things where i've to update only email address or only phone number and stuff
Actually, in your question you have a RESTful controller which could be confusing for you at this time because you are new to Laravel and used CI, so probably you are very so much used with automating URL mapping without route. In this case, for ease, I suggest you to use a plain controller and that is almost same thing that you've did in CI but here in Laravel you have to declare route for every action. So, just create two routes like these:
Rouite::get('something/edit/{id}', array('uses' => 'StudentController#edit', 'as' => 'edit.record'));
Rouite::post('something/update/{id}', array('uses' => 'StudentController#update', 'as' => 'update.record'));
Then create a class/Controller and declare these methods:
class StudentController extends baseController {
// URL: http://example.com/something/edit/10 and it'll listen to GET request
public function edit($id) {
// $record = Load the record from database using the $id/10
// retuen View::make('editform')->with('record', $record);
}
// URL: http://example.com/something/update/10 and it'll listen to POST request
public function update($id) {
// Update the record using the $id/10
}
}
In your form, you need to use http://example.com/something/update/10 as action and you may use route('update.record') or url('something/update/10') to generate the action in the form. Read more on Laravel Documentation.
What you have created (or maybe rather generated) here is called Restful controller. It is some 'standard way' to manage CRUD actions (create/read/update/delete). However there is no need to do it this way. You can add in your controller whatever methods you want and not use Restful Controllers at all. That's your choice.
You can create in your function new method
function updateEmail()
{
// do here whatever you want
}
and in your routes.php file add new route:
Route::match(array('GET', 'POST'), '/changegemail', 'StudentController#updateEmail');
Now you can write your code for this method and it will work.