【问题标题】:How to add method to model in Laravel?如何在 Laravel 中为模型添加方法?
【发布时间】:2013-08-19 09:39:33
【问题描述】:

我有一个看起来像这样的模型:

<?php

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

class Post extends Eloquent {
}

然后我尝试添加这样的方法:

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

class Post extends Eloquent {
    public static function create($type, $postid, $url, $author, $content)
    {
        $post = new Post;
        $post->type = $type;
        $post->postid = $postid;
        $post->url = $url;
        $post->author = $author;
        $post->content = $content;
        try
        {
        $post->save();
        echo $post;
        }catch(Exception $e){
            throw new Exception( 'Already saved', 0, $e);
        } 
    }
}

在控制器中,我尝试像这样引用该方法:

public function savepostController($type, $postid, $url, $author, $content)
{
    Post::create($type, $postid, $url, $author, $content);
}

当我运行控制器时,我得到Controller method not found.

【问题讨论】:

  • 您能否提供更多堆栈跟踪信息?这个错误似乎根本不是来自您的模型。

标签: php laravel laravel-4


【解决方案1】:

尝试使用,这里有一个例子

class Exports extends Eloquent {

    public static function my_exports($user)
    {
         // DB call here
    }
}

那么在你的路线上你可以做

Route::post('export/(:number)', function($user)
{

    $user_exports = Export::my_exports($user);

    // Do stuff here
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    相关资源
    最近更新 更多