Alex
Alex

Reputation: 59

class name as argument in a public function

What's the difference between:

class PostController extends \BaseController {
      public function delete($id) {
        $deletePost = Post::findOrFail($id);
        return View::make('backend.delete')->with('post', $deletePost);
      }
}

and

class PostController extends \BaseController {
      public function delete(Post $post) {
        return View::make('backend.delete')->with('post', $post);
      }
}

Can somebody explain to me: public function delete(Post $post)

we are taking a Class named "Post" as a variable $post?

UPDATE1.

in routes.php:

Route::model('post', 'Post');

Route::get('delete/{post}', array('uses' => 'PostController@delete'));
Route::post('delete', array('uses' => 'PostController@doDelete'));

and in PostController.php:

public function delete(Post $post) {
    return View::make('backend.delete')->with('post', $post);
}

public function doDelete() {
    $post = Post::findOrFail(Input::get('id'));
    $post->delete();

    return Redirect::action('PostController@home');
}

but anyway i get an error: No query results for model [Post]. with the 2nd method.

Upvotes: 1

Views: 83

Answers (2)

Alexander Kim
Alexander Kim

Reputation: 18402

It's just a type hinting:

"Type hinting means that whatever you pass must be an instance of (the same type as) the type you're hinting."

In your example it's Post:

public function delete(Post $post) { /* code */ }

It's just checks $post variable whether instance it or not. So everything looks good in your code. And it should work.

Upvotes: 2

Laurence
Laurence

Reputation: 60048

They both achieve the same thing of giving you the model (if it exists).

The second way is called Route Model binding. Route model binding provides a convenient way to inject model instances into your routes.

To bind a model to a route:

Route::model('post', 'Post');

Next, define a route that contains a {user} parameter:

Route::get('delete/{post}', array('uses' => PostController@delete));

So we have bound the {post} parameter to the Post model, a Post instance will be injected into the route.

This means if someone reaches your delete() function - they have already provided a valid Post model - which is the equivalent of Post::findOrFail($id)

Upvotes: 2

Related Questions