Mostafa Norzade
Mostafa Norzade

Reputation: 1766

laravel 5.7 how to pass request of controller to model and save

I am trying to pass $request from a function in controller to a function in model.

THis is my controller function:

PostController.php

public function store(Request $request, post $post)
{

    $post->title = $request->title;
    $post->description = $request->description;

    $post->save();

    return redirect(route('post.index'));

}

how save data in model Post.php?

I want the controller to only be in the role of sending information. Information is sent to the model. All calculations and storage are performed in the model

Thanks

Upvotes: 3

Views: 11797

Answers (5)

li bing zhao
li bing zhao

Reputation: 1418

 public function store(Request $request)
{
    $book = new Song();
    
    $book->title = $request['title'];
    $book->artist = $request['artist'];
    $book->rating = $request['rating'];
    $book->album_id = $request['album_id'];
    
    $result=  $book->save();
 }

Upvotes: 0

You can make it even easier. Laravel has it's own helper "request()", which can be called anywhere in your code.

So, generally, you can do this:

PostController.php

    public function store()
    {
        $post_model = new Post;
        // for queries it's better to use transactions to handle errors
        \DB::beginTransaction();
        try {
           $post_model->postStore();
           \DB::commit(); // if there was no errors, your query will be executed
        } catch (\Exception $e) {
            \DB::rollback(); // either it won't execute any statements and rollback your database to previous state
            abort(500);
        }
        // you don't need any if statements anymore. If you're here, it means all data has been saved successfully
        return redirect(route('post.index'));
    }

Post.php

    public function postStore()
    {
        $request = request(); //save helper result to variable, so it can be reused
        $this->title = $request->title;
        $this->description = $request->description;
        $this->save();
    }

I'll show you full best practice example for update and create:

web.php

    Route::post('store/post/{post?}', 'PostController@post')->name('post.store');

yourform.blade.php - can be used for update and create

    <form action='{{ route('post.store', ['post' => $post->id ?? null]))'>
       <!-- some inputs here -->
       <!-- some inputs here -->

    </form>

PostController.php

    public function update(Post $post) {
        // $post - if you sent null, in this variable will be 'new Post' result
        // either laravel will try to find id you provided in your view, like Post::findOrFail(1). Of course, if it can't, it'll abort(404)

        // then you can call your method postStore and it'll update or create for your new post.
        // anyway, I'd recommend you to do next

        \DB::beginTransaction();
        try {
          $post->fill(request()->all())->save();
          \DB::commit();
        } catch (\Exception $e) {
          \DB::rollback();
           abort(500);
        }
      return redirect(route('post.index'));
    }

Upvotes: 3

Mostafa Norzade
Mostafa Norzade

Reputation: 1766

I find to answer my question :

pass $request to my_method in model Post.php :

PostController.php:

    public function store(Request $request)
    {
        $post_model = new Post;
        $saved = $post_model->postStore($request);

        //$saved = response of my_method in model

        if($saved){
            return redirect(route('post.index'));
        }
    }

and save data in the model :

Post.php

we can return instance or boolean to the controller .

I returned bool (save method response) to controller :

    public function postStore($request)
    {
        $this->title = $request->title;
        $this->description = $request->description;

        $saved = $this->save();

        //save method response bool

        return $saved;

    }

in this way, all calculations and storage are performed in the model (best way to save data in MVC)

Upvotes: 0

kshitij
kshitij

Reputation: 710

You need to create new model simply by instantiating it:

$post = new Post;  //Post is your model

then put content in record

$post->title = $request->title;
$post->description = $request->description;

and finally save it to db later:

$post->save();

To save all data in model using create method.You need to setup Mass Assignments when using create and set columns in fillable property in model.

  protected $fillable = [ 'title', 'description' ];

and then call this with input

    $post = Post::create([ 'parametername'  => 'parametervalue' ]);

and if request has unwanted entries like token then us except on request before passing.

    $post = Post::create([ $request->except(['_token']) ]);

Hope this helps.

Upvotes: 0

Farooq Ahmed Khan
Farooq Ahmed Khan

Reputation: 4094

Based on description, not sure what you want exactly but assuming you want a clean controller and model . Here is one way

Model - Post

class Post {
    $fillable = array(
        'title', 'description'
    );
}

PostController

class PostController extend Controller {

    // store function normally don't get Casted Objects as `Post`
    function store(\Request $request) {

        $parameters = $request->all(); // get all your request data as an array

        $post = \Post::create($parameters); // create method expect an array of fields mentioned in $fillable and returns a save dinstance
        // OR
        $post = new \Post();
        $post->fill($parameters);
    }
}

I hope it helps

Upvotes: 2

Related Questions