EzDev.org

laravel

A PHP Framework For Web Artisans Laravel - The PHP Framework For Web Artisans laravel - the php framework for web artisans.


Can I Install Laravel without using Composer?

I'd like to know if I can install or use the Laravel PHP framework on any webserver without using Composer (PHP package/dependency manager) every time?

  • I am learning PHP and frameworks and I am working on a CMS based on Laravel for practice.
  • I would like to be able to drop it onto any webserver without having to use composer every time.

If I run $ composer install the first time (locally), then all the dependencies should be present, correct?

Then, I should be able to drop it onto any server with all of the files (including the vendor directory)?


Source: (StackOverflow)

Passing data to a closure in Laravel 4

I'm trying to use the Mail Class in Laravel 4, and I'm not able to pass variables to the $m object.

the $team object contains data I grabbed from the DB with eloquent.

Mail::send('emails.report', $data, function($m)
{
   $m->to($team->senior->email, $team->senior->first_name . ' '. $team->senior->last_name );
   $m->cc($team->junior->email, $team->junior->first_name . ' '. $team->junior->last_name );
   $m->subject('Monthly Report');
   $m->from('info@website.com', 'Sender');
});

For some reason I get an error where $team object is not available. I suppose it has something to do with the scope.

Any ideas ?


Source: (StackOverflow)

Laravel 4: how to "order by" using Eloquent ORM [duplicate]

This question already has an answer here:

Simple question - how do I order by 'id' descending in Laravel 4.

The relevant part of my controller looks like this:

$posts = $this->post->all()

As I understand you use this line:

->orderBy('id', 'DESC');

But how does that fit in with my above code?


Source: (StackOverflow)

Laravel unexpected error "class user contains 3 abstract methods..."

While programming my Authentication app on Laravel, I came across to an error I've never seen before. I've been brainstorming for almost an hour for the cause of this problem but yet I can't find a solution.

Error:

Class User contains 3 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\Auth\UserInterface::getRememberToken, Illuminate\Auth\UserInterface::setRememberToken, Illuminate\Auth\UserInterface::getRememberTokenName)

User.php Model:

<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

protected $fillable = [
    "email",
    "username",
    "password",
    "password_temp",
    "code",
    "active",
    "created_at",
    "updated_at",
    "banned"
];

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = array('password');

/**
 * Get the unique identifier for the user.
 *
 * @return mixed
 */
public function getAuthIdentifier()
{
    return $this->getKey();
}

/**
 * Get the password for the user.
 *
 * @return string
 */
public function getAuthPassword()
{
    return $this->password;
}

/**
 * Get the e-mail address where password reminders are sent.
 *
 * @return string
 */
public function getReminderEmail()
{
    return $this->email;
}

}

And the RegisterController.php

<?php

class RegisterController extends BaseController {

public function getRegister()
{
    return View::make('template.home.register');
}

public function postRegister()
{
    $rules = [
        "email"         => "required|email|max:50|unique:users",
        "username"      => "required|max:50|min:5|unique:users",
        "password"      => "required|max:50|min:6",
        "password_again"=> "required|same:password",
    ];

    $messages = ["required" => "This field is required." ];

    $validator = Validator::make(Input::all(), $rules, $messages);

    if($validator->fails())
    {
        return Redirect::route('register')->withErrors($validator)->withInput();
    } else {
        $email      = Input::get('email');
        $username   = Input::get('username');
        $password   = Input::get('password');
        $code       = str_random(60);

        $user = User::create([
            'email'         => $email,
            'username'      => $username,
            'password'      => Hash::make($password),
            'code'          => $code,
            'activated'     => 0,
            'banned'        => 0
        ]);

        if ($user)
        {
            Mail::send('template.email.activate', ['link' => URL::route('activate', $code), 'username' => $username], function($message) use ($user)
            {
                $message->to($user->email, $user->username)->subject('Account Registration');
            });

            return Redirect::route('register')->with('homeError', 'There was a problem creating your account.');
        }
    }
    return Redirect::route('register')->with('homeError', 'Account could not be created.');
}
}

Your help is appreciated.


Source: (StackOverflow)

Managing relationships in Laravel, adhering to the repository pattern

While creating an app in Laravel 4 after reading T. Otwell's book on good design patterns in Laravel I found myself creating repositories for every table on the application.

I ended up with the following table structure:

  • Students: id, name
  • Courses: id, name, teacher_id
  • Teachers: id, name
  • Assignments: id, name, course_id
  • Scores (acts as a pivot between students and assignments): student_id, assignment_id, scores

I have repository classes with find, create, update and delete methods for all of these tables. Each repository has an Eloquent model which interacts with the database. Relationships are defined in the model per Laravel's documentation: http://laravel.com/docs/eloquent#relationships.

When creating a new course, all I do is calling the create method on the Course Repository. That course has assignments, so when creating one, I also want to create an entry in the score's table for each student in the course. I do this through the Assignment Repository. This implies the assignment repository communicates with two Eloquent models, with the Assignment and Student model.

My question is: as this app will probably grow in size and more relationships will be introduced, is it good practice to communicate with different Eloquent models in repositories or should this be done using other repositories instead (I mean calling other repositories from the Assignment repository) or should it be done in the Eloquent models all together?

Also, is it good practice to use the scores table as a pivot between assignments and students or should it be done somewhere else?


Source: (StackOverflow)

Error in exception handler. - Laravel

It's a Laravel-install related question. I have a public-facing Unix server setup:

<VirtualHost *:80>
ServerAdmin webmaster@mydomain.org
DocumentRoot "/var/www/mydomain"
ServerName mydomain.org
ServerAlias www.mydomain.org
ErrorLog "/var/log/mydomain.org-error_log"
CustomLog "/var/log/mydomain.org-access_log" common
</VirtualHost>

I can serve documents fine out of /var/www/mydomain i.e. http://mydomain.org/test.php with test.php containing:

<?php echo 'test';

works fine.

In bash, with Laravel installed through Composer and looking at the files:

# ls /var/www/mydomain/my-laravel-project

.gitattributes  CONTRIBUTING.md artisan         composer.json   phpunit.xml readme.md       vendor
.gitignore      app             bootstrap       composer.lock   public          server.php

So when I browse to:

http://mydomain.org/my-laravel-project/public/

why does my application report:

Error in exception handler. 

in the browser - on a blank white screen? I'm expecting to see the Laravel splash screen.

Moreover, the log files don't reveal anything either.


Source: (StackOverflow)

Proper Repository Pattern Design in PHP?

Preface: I'm attemping to use the repository pattern in a MVC architecture with relational databases.

I've recently started learning TDD in PHP, and I'm realizing that my database is coupled much too closely with the rest of my application. I've read about repositories, and using an IoC container to "inject" it into my controllers. Very cool stuff. But now have some practical questions about repository design. Consider the follow example.

<?php

class DbUserRepository implements UserRepositoryInterface
{
    protected $db;

    public function __construct($db)
    {
        $this->db = $db;
    }

    public function findAll()
    {
    }

    public function findById($id)
    {
    }

    public function findByName($name)
    {
    }

    public function create($user)
    {
    }

    public function remove($user)
    {
    }

    public function update($user)
    {
    }
}

Issue #1: Too many fields

All of these find methods use a select all fields (SELECT *) approach. However, in my apps I'm always trying to limit the number of fields I get, as this often adds overhead and slows things down. For those using this pattern, how do you deal with this?

Issue #2: Too many methods

While this class looks nice right now, I know that in a real world app I need a lot more methods. For example:

  • findAllByNameAndStatus
  • findAllInCountry
  • findAllWithEmailAddressSet
  • findAllByAgeAndGender
  • findAllByAgeAndGenderOrderByAge
  • Etc.

As you can see, there could be very, very long list of possible methods. And then if you add in the field selection issue above, the problem worsens. In the past I'd normally just put all this logic right in my controller:

<?php

class MyController
{
    public function users()
    {
        $users = User::select('name, email, status')->byCountry('Canada')->orderBy('name')->rows()

        return View::make('users', array('users' => $users))
    }

}

With my repository approach, I don't want to end up with this:

<?php

class MyController
{
    public function users()
    {
        $users = $this->repo->get_first_name_last_name_email_username_status_by_country_order_by_name('Canada');

        return View::make('users', array('users' => $users))
    }

}

Issue #3: Impossible to match an interface

I see the benefit in using interfaces for repositories, so I can swap out my implementation (for testing purposes or other). My understanding of interfaces is that they define a contract that an implementation must follow. This is great until you start adding additional methods to your repositories like findAllInCountry(). Now I need to update my interface to also have this method, otherwise other implementations may not have it, and that could break my application. By this feels insane...a case of the tail wagging the dog.

Specification Pattern?

This leads me to believe that repository should only have a fixed number of methods (like save(), remove(), find(), findAll(), etc). But then how do I run specific lookups? I've heard of the Specification Pattern, but it seems to me that this only reduces an entire set of records (via IsSatisfiedBy()), which clearly has major performance issues if you're pulling from a database.

Help?

Clearly I need to rethink things a little when working with repositories. Can anyone enlighten on how this is best handled?


Source: (StackOverflow)

Add new methods to a resource controller in Laravel 4

I want to know if it is possible to add new methods to a resource controller in Laravel 4 and how you do it.

I know that this methods are the default ( index, create, store, edit, update, destroy ).

I am confused, any ideas, examples ?


Source: (StackOverflow)

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

 SELECT * FROM  `games` LIMIT 30 , 30 

And with Eloquent ?


Source: (StackOverflow)

Safely remove migration In Laravel 4

In Laravel 4, there appears to be a command for creating a migration, but not removing.

Create migration command:

php artisan migrate:make create_users_table

If I want to delete the migration, can I just safely delete the corresponding migrations file within the database/migrations folder?

Migrations file:

2013_05_31_220658_create_users_table

Source: (StackOverflow)

Laravel 4 migrate rollback problems

I can easily run the artisan migrate etc, but when i try to roll it back, with migration:rollback i keep getting this error,

c:\xampp\htdocs\laravel>php artisan migrate:rollback
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'CreateCodesnippetsTable' not found","file":"C:\\xampp\\htdocs\\laravel\\vendor\\laravel\\framework\\src\\Illum
inate\\Database\\Migrations\\Migrator.php","line":301}}

Is this a bug? or how should i debug this?


Source: (StackOverflow)

Laravel's Blade: how can I set variables in a template?

I'm reading Laravel Blade's templating docs and I can't find how I can assign variables inside a template for use later in the template. I can't do {{ $old_section = "whatever" }} because that will echo "whatever" and I don't want that.

I see that I can do <?php $old_section = "whatever"; ?>, but that's not elegant.

Is there an elegant way to do that in Blade?


Source: (StackOverflow)

How do I get the query builder to output its raw SQL query as a string?

Given the following code:

DB::table('users')->get();

I want to get the raw SQL query string that the query builder above will generate, so in this example it would be SELECT * FROM users.

How do I do this?


Source: (StackOverflow)

Laravel 4 eloquent WHERE with OR AND OR?

How do I say WHERE (a=1 OR b=1) AND (c=1 OR d=1)

For more complicated queries am I supposed to use raw SQL?


Source: (StackOverflow)

What are differences between "php artisan dump-autoload" and "composer dump-autoload"

I am pretty new to Laravel4 and Composer. While I do laravel 4 tutorials, I couldn't understand between those two commands; php artisan dump-autoload and composer dump-autoload What are difference between them ??


Source: (StackOverflow)