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

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

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'));
}

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

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.

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)

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();
}

Related

Method Illuminate\Database\Eloquent\Collection::attach does not exist error in laravel 8

I was trying to add categories to products. I want to do it with a couple table between items and categories. I made a function in my controller to send it to the database. However, when I want to send it, I get the following error, and I don't know I can fix it. Method Illuminate\Database\Eloquent\Collection::attach does not exist.
Controller:
public function store(ItemsValidatorRequest $request)
{
if ($files = $request->image) {
$destinationPath = 'images';
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
}
else {
return redirect()->back()->with('warning', 'Mislukt');
}
$user = Auth::user()->id;
Item::create([
'user_id' => $user,
'item_title' => $request->titel,
'item_img' => $profileImage,
'item_description' => $request->beschrijving,
'item_price' => $request->prijs,
'item_slug' => $this->slugify($request->titel)
]);
$items = Item::latest()->get();
// line where it goes wrong
$items->each->categories()->attach($request->categories);
return redirect()
->route('admin.items.index')
->with('success', 'Het item is toegevoegd aan je verlanglijst');
}
My model :
public function categories()
{
return $this->belongsToMany('App\Models\Category');
}
Laravels higher order function calls, take a single method call, not multiple. Therefor if you create an helper method on the Item class, it will solve your problem.
class Item {
public function attachCategories($categories) {
$this->categories()->attach($categories);
}
}
Which will make it possible to assign categories like so.
$items->each->attachCategories($request->categories);

How do I loop over json data

I am using FlutterWave as my payment gateway, I want to loop through a transaction whenever a customer finish making payment and check for the chargeamount which the user paid. the return data is in json format. Here is my code.
public function callback(Request $request)
{
$resp = $request->resp;
$body = json_decode($resp, true);
$txRef = $body['data']['data']['txRef'];
$data = Rave::verifyTransaction($txRef);
dd($data);
return redirect()->route('success');
}
I want to loop and check for the chargedamount but I couldn't. Thanks for your help
Seems like you are dumping an object. I don't think you need a loop to access the data you need. According to your image dump, to access the chargedamount attribute:
dd($data->data->chargedamount);
The data name here repeats, perhaps $payload in this case, its a better name.
public function callback(Request $request)
{
$resp = $request->resp;
$body = json_decode($resp, true);
$txRef = $body['data']['data']['txRef'];
$payload = Rave::verifyTransaction($txRef);
dd($payload->data->chargedamount);
return redirect()->route('success');
}
Some clean up:
public function callback(Request $request)
{
$json = json_decode($request->resp);
$payload = Rave::verifyTransaction($json->data->data->txRef);
dd($payload->data->chargedamount);
return redirect()->route('success');
}
Again that data->data repeating stuff, but in this case, nothing we can do, its in the API.

How to remove or unfriend through API

This is database structure
This is API
Route::post('/friend', 'FriendController#index');
Route::post('/removerequest/{id}', 'FriendController#removerequest');
This is controller code which into friend request method and remove method, but error in remove friend method..
public function index(Request $request) {
$sender = Friend::where('sender_id', $request->sender_id)->where('receiver_id',$request->receiver_id)->first();
if(empty($sender)){
Friend::create(['sender_id'=>$request->sender_id,'receiver_id'=>$request->receiver_id, 'approved'=>'pending']);
$response = ['message'=>'Friend Request has been sent','status'=>200];
return response()->json($response);
}else{
$response = ['message'=>'Request has been sent already','status'=>200];
return response()->json($response);
}
}
public function removerequest($id){
$friends = Friend::all()
->where('receiver_id')
->where('sender_id')
->approved('accept')
->delete();
}
Error is
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::approved does not exist. in file /home/ynvih0l26evc/public_html/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php on line 104
enter code here
Update your Route to
Route::delete('/removerequest/{id}', 'FriendController#removerequest');
//change
->approve('approved', 'accept')
to
->where('approved', 'accept')
Update your controller method to
public function removerequest($id){
$friends = Friend::Find($id)->delete(); //see update here
//->where('receiver_id')
//->where('sender_id')
//->where('approved', 'accept')
//->delete();
}
OR
public function removerequest($id){
Friend::where( ['id' => $id, 'approved' => 'accept'])->delete();
}

can't store when using [IF] in eloquent din't work

I need to Store when have data in [Booking] but din't store anything to [scan]
public function store(Request $request, $id){
$event = event::findOrFail($id);
$booking = booking::where('student_id',Auth::user()->student_id)
->where('name',Auth::user()->name)
->where('event_id',$event->id);
if($booking!=NULL){
$requestData = $request->all();
scan::create($requestData);
return redirect('event/' . $event->id .'/scan');
return view('event.scan', compact('event','scan','booking'));
}else{
return redirect('event/' . $event->id .'/scan');
}
}
but when using $booking==null
it store anything can't check in booking
Your query is incomplete. It lacks of any final query method like get(), first() or exists()
Also you have two return statements inside the if block. Only the first will be executed, the second one will be ignored.
The correct code should be like this:
public function store(Request $request, $id){
$event = event::findOrFail($id);
$booking = booking::where('student_id',Auth::user()->student_id)
->where('name',Auth::user()->name)
->where('event_id',$event->id)
->get(); // look this line
if($booking!=NULL){
$requestData = $request->all();
scan::create($requestData);
return redirect('event/' . $event->id .'/scan'); // I think this should not be here, right?
return view('event.scan', compact('event','scan','booking')); // this is being ignored.
}else{
return redirect('event/' . $event->id .'/scan');
}
}
you can update your method like so. its much clearer and readable (i think anyway).
public function store(Request $request, $id)
{
//use first to get a booking or use get() for collections of booking
$booking = Booking::where('student_id', auth()->user()->student_id)
->where('event_id', $id)
-first();
if (is_null($booking)) {
return redirect('event/' . $id . '/scan');
}
return view('event.scan', [
'event' => Event::findOrFail($id),
'scan' => Scan::create($request->all()),
'booking' => $booking
]);
}
Hope this helps
Cheers

Creating edit function in the same controller laravel

So I have a create function in my controller as shown below and my routes is as such, my question is is there a way for me to put a condition to different create and edit in the same function as both have quite similar coding. Can someone enlighten me pls?
class ManageAccountsController extends Controller
{
public function index() {
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function update()
{
// process the form here
// create the validation rules ------------------------
$rules = array(
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the user table
'password' => 'required|min:8|alpha_num',
'password_confirm' => 'required|same:password', // required and has to match the password field
'mobile' => 'required',
'role_id' => 'required'
);
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(Input::all(), $rules);
// check if the validator failed -----------------------
if ($validator->fails()) {
// redirect our user back to the form with the errors from the validator
$input = Input::except('password', 'password_confirm');
$input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
return redirect()
->back()
->withInput($input)
->withErrors($validator);
} else {
// validation successful ---------------------------
// user has passed all tests!
// let user enter the database
// create the data for our user
$user = new User;
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->mobile = Input::get('mobile');
$user->role_id = Input::get('role_id');
// save our user
$user->save();
// redirect ----------------------------------------
// redirect our user back to the form so they can do it all over again
Session::flash('flash_message', 'User successfully added!');
return redirect()->back();
}
}
}
routes.php
Route::get('manage_accounts', 'ManageAccountsController#index');
Route::post('manage_accounts', 'ManageAccountsController#update');
UPDATE OR CREATE
Try the updateOrCreate() in Eloquent to create or update a record matching the attributes.
Read API docs udateOrCreate()
Your code will be like:
Model::updateOrCreate( ['id' => $id], ['firstField' => 'value', 'secondField' => 'value'] );
Note: first parameter is the match to be found and second the data's to be saved.
Hope this is helpful.
Why don't you try moving some of this code out of your controller. If you were to use Repositories, then you would be able to encapsulate some of your logic in order to use it for both functions.
Also you can handle all this validation without writing all the extra code into your controller - see http://laravel.com/docs/5.0/validation#form-request-validation.
This may all seem a bit overkill at first, but once you get the hang of it, your code will be much more manageable and extendable.
(for more on these I would thoroughly recommend Jeffery Way's Laracasts https://laracasts.com/ - this helped me a lot when I was learning Laravel)
// routes.php
// http://laravel.com/docs/5.0/controllers#restful-resource-controllers
Route::resource('manage_accounts', 'ManageAccountsController');
// ManageAccountsController.php
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class ManageAccountsController extends Controller
{
public $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index() {
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function store(StoreUserRequest $request)
{
// validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
$this->userRepository->upsert($request)
Session::flash('flash_message', 'User successfully added!');
return redirect()->back();
}
public function update(StoreUserRequest $request, $id)
{
// validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
$this->userRepository->upsert($request, $id)
Session::flash('flash_message', 'User successfully updated!');
return redirect()->back();
}
}
// UserRepository.php
class UserRepository {
public function upsert($data, $id = null)
{
// You will also need something like this
if(isset($data['id']))
{
$user = $this->user->find($data['id']);
}
else {
$user = new User;
}
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->mobile = $data['mobile'];
$user->role_id = $data['role_id'];
// save our user
$user->save();
return $user;
}
}
}
Please use the code here as a guide (I have written this in a hurry and it will certainly contain errors). Have a quick read up on repositories and I think it should all make sense.
The basic premise here is to separate out code that you want to re-use rather than squashing it all into the same function.
Hope this helps!

Resources