0

just started using Laravel but want to make sure I am using it correctly.

Most of my work is CMS based so read / write / update etc to a database.

An example of what I have done so far is an insertion into the DB:

On the view I have a form with a URL of 'addNewUser'.

In my routes I then do:

Route::post('addnewuser', array('uses' => 'UserController@addNewUser'));

My user controller 'addNewUser' method is (simplified):

public function addNewUser() {
    $data = Input::all();
    $rules = array(
        'username' => 'required|alpha_dash|max:16|unique:users,username',
        );

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

    if ($validator->fails())
    {
        Input::flash();
        $errors = $validator->messages();
        return Redirect::to('/register')->withErrors($validator)->withInput();
    }

    $user = new User;
    $user->save();

    return Redirect::to('/login')->with('successLogin', '1');
}

Is this correct? I have read somewhere that all DB interaction should be in the model?

Likewise when reading from the DB to display a foreach for example, I do the following directly in the view:

$builds = DB::table('blogs')->orderBy('id', 'desc')->get();

if ($builds) {

    foreach ($builds as $build)
    {
      $safeURLSlug = stringHelpers::safeURLSlug($build->blogtitle);
      echo "
        // stuff
      ";
    }

} else {
    // no stuff
}

Should I be doing these sort of queries and showing of data directly in the view? or in a model / controller function etc?

Want to check im doing things 100% correct / the standard way of doing things before I get too involved.

1
  • No, it shouldn't be done in the controller if you wish the code to be reusable. Just imagine you have another reason to add an user, eg. /users/add_batch, then you need to rewrite all this stuff for this new controller. Or you wish to do it in the command line (artisan cron job or whatever) - you need to rewrite that stuff again. Instead better create a service, a method on the model (whatever suits you) that will handle this very task and reuse it in your controller(s)/cli. Commented Dec 2, 2014 at 16:27

3 Answers 3

1

I can see a few things that I personally would have done differently.

For example I usually put $rules as a class variable so it can be used in different functions related to your Users.

Have you tested your code yet? Any errors?

In your addNewUser function does it save any data? I know you have "simplified" above the code snippet but there should be $user->username = $data['username']; etc. in between creating your $user variable and running $user->save();, so if you excluded this on purpose then I don't see anything else with your model.

In your view code, $builds = DB::table('blogs')->orderBy('id', 'desc')->get(); should be done in your controller and passed to your view like so return View::make('example', array('builds' => $builds))

I'd also change

$builds = DB::table('blogs')->orderBy('id', 'desc')->get();

to

$builds = Blog::orderby('id','desc')->get(); if you have a Blog model, otherwise your code is fine.

Sign up to request clarification or add additional context in comments.

Comments

1

You could move:

$rules = array(
        'username' => 'required|alpha_dash|max:16|unique:users,username',
        );

to User model as static variable, and instead of:

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

you could use:

 $validator = Validator::make($data, User::$rules, $messages);

But definitely you shouldn't get data from database in your View, this code should be in controller, for example:

$builds = DB::table('blogs')->orderBy('id', 'desc')->get();
return View::make('someview')->with('builds', $builds);

of course if you have Blog model, you should use here:

$builds = Blog::orderBy('id', 'desc')->get();
return View::make('someview')->with('builds', $builds);

It's also unclear what the following code does:

$safeURLSlug = stringHelpers::safeURLSlug($build->blogtitle);

but probably you could move it to your Blog model and use accessor to make the change:

public function getSafeSlugAttribute($value) {
   return stringHelpers::safeURLSlug($this->blogtitle);
}

and now your view could look like this:

@foreach ($builds as $build)
      {{{ $build->title }}} {{{ $build->safeSlug }}}
@endforeach

2 Comments

Okay im slowly getting the picture. I should still be doing saving / validation etc in the controller but defining the rules in the model?
@user2921557 Well, you don't make validation in controller, you use ` Validator` model and validation is being made in this model, you only need to do something with its result in controller. You can of course also create separate method in your model for validation - for example in my current project I have validateEdit, validateAdd methods because I need to use different validation rules depending on actions or other data
0

I suggest you take a look on Laravel Generators.

https://github.com/JeffreyWay/Laravel-4-Generators

Install and then run:

php artisan generate:scaffold customer

Laravel line command generator create a basic CRUD for you with controller, model, views and database migrations. That's good to safe time and keep your project with some default organization.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.