How to insert multiple rows in database using Eloquent in Laravel5 - laravel

My controller looks something like this
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Middleware\Role;
use Illuminate\Support\Facades\Input;
use App\Http\Requests\PaymentRequest;
use App\User;
use App\Invoice;
use App\comments;
use Session;
use Validator;
class CollectionController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function __construct(){
$this->middleware('role:collector'); // replace 'collector' with whatever role you need.
}
public function postPayment(PaymentRequest $request){
$insertPayment=Input::get();
$payment= new paymentrecieved();
$comment= new comments();
$payment->invoice_id=$insertPayment['invoiceid'];
$payment->recieved_amount=$insertPayment['recieved_amount'];
$payment->refno=$insertPayment['ref_no'];
$payment->date=$insertPayment['date'];
if($insertPayment['adjustmentmode']=='Option')
$payment->adjust_mode='NONE';
else
$payment->adjust_mode=$insertPayment['adjustmentmode'];
$payment->save();
$request->session()->flash('alert-success', 'Payment Has Been inserted Successfully');
return redirect('collection/payment/1');
//dd($insertPayment);
}
}
So in my form the Payment related details are in an array I want to know how I can create multiple row ? and save it all together once .
Thanks & Regards

Try this,
$result = Banner::create([
'name' => $name,
'status' => $status,
'description' => $description,
'category_id' => $category_id,
'ordering' => $ordering,
'link' => $link,
]);
$result = Banner::create($data);
You can pass a multidimensional array in that case you have to use insert
for(..){
$data[] = [
'name' => $name,
'status' => $status,
'description' => $description,
'category_id' => $category_id,
'ordering' => $ordering,
'link' => $link,
];
}
$result = Banner::insert($data)
note: this will not update/create timestamps, so you have to pass that too with insert array.
Hope it helps..

Related

Make register manual laravel with user picture error in file form

Error when I submit form to insert to database. The problem is why picture does not exist?
Method Illuminate\Http\Request::picture does not exist.
This is my Controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\User;
use File;
class UsersController extends Controller
{
public function registeract(Request $request)
{
$this->validate($request,[
'name' => 'required|alpha',
'email' => 'required|email',
'level' => 'required|alpha',
'picture' => 'required|file|image|mimes:jpeg,jpg,png|max:1048',
'password' => 'required'
]);
// Menyiapkan data gambar yg diupload ke variable $file
$picture = $request->picture('picture');
$file_name = time()."_".$picture->getClientOriginalName();
// Isi dengan nama folder tempat kemana file diupload
$upload_directory = 'p_users';
$picture->move($upload_directory, $file_name);
User::create([
'name' => $request->name,
'email' => $request->email,
'level' => $request->level,
'picture' => $file_name,
'password' => bcrypt($request->password),
'remember_token' => Str::random(60)
]);
return redirect('/ec-admin/users')->with('usrsinsertno', 'Data Inserted Successfully!');
}
}
I don't know therefore can use as Model but I see on youtube that there some people use as model.
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'level', 'picture', 'password'
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Picture method doesn't exist on Laravel's request class.
You need to use $picture = $request->file('picture');
Any methods that appear in your head cannot be used.
There is no method like picture in Laravel, as #amirrezam75 mentioned.
Firstly, you need to check if the file exists. You can then save the file and its name.
Try below code:
if ($request->hasFile('picture')) {
$picture = $request->picture('picture');
$file_name = time()."_".$picture->getClientOriginalName();
}else{
$file_name = null;
}

fill method not working in register controller

after creating my model with model::create facade I use fill method to change the value of "card_tb_name" property but new value doesnt record i should say the "card_tb_name" is declared fillable property .
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
/*------------------------------*/
class RegisteredUserController extends Controller
{
public function store(Request $request)
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'card_tb_name' => 'table_name',
]);
$user->fill(array('card_tb_name' => 'Amsterdam to Frankfurt'));
}
}
Try to save() after fill()
$user->fill(array('card_tb_name' => 'Amsterdam to Frankfurt'))->save();

How to save the csv when i import it in Laravel

i am new in Laravel, and i have an import list page (this page work very good), this import some list to put on database. But i want to save this list too.
Heres my code (CsvImport.php):
<?php
namespace App\Imports;
use App\Product;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Auth;
class CsvImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
return Product::query()->forceCreate([
'name' => $row["name"],
'description' => $row["description"],
'category' => $row["category"],
'price' => $row["price"],
'image' => 'no-image.jpg',
'user_id' => Auth::user()->id,
]);
}
}
Some Ideas? :)
i did not find, but i think is better not save.

Request Data to Model Function

I'm trying to find out why when I dd($request->all()) in the store method of my controller everything is correct, however when I send it to the model function register() its no where to be seen.
I'm not quite sure what I'm doing wrong.
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
public function store(Request $request, User $user)
{
$this->authorize('delete', $user);
$this->validate($request, [
'firstName' => 'required|min:3',
'lastName' => 'required|min:3',
'displayName' => 'required|min:3',
'emailAddress' => 'required|email|unique:users,email',
'password' => 'required|min:3',
'role' => 'required|exists:roles,id'
]);
$userRegistered = $user->register(
new User($request->all())
);
if ($userRegistered) {
flash()->success('Success', 'The user has been successfully created!');
} else {
flash()->error('Error', 'The user could not be successfully created!');
}
return redirect()->to(route('users'));
}
}
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use SoftDeletes;
/**
* Fillable fields for a user.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'display_name',
'email',
'password',
'role_id'
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function register(User $user)
{
return $user->create([
'first_name' => $user->firstName,
'last_name' => $user->lastName,
'display_name' => $user->displayName,
'email' => $user->emailAdress,
'password' => $user->password,
'role_id' => $user->role
]);
}
}
You've mixed up the formatting of your variables between your request data and your User model.
According to your validation logic, the request data is coming is as camelCase. Yet, according to your $fillable array, the fields on your User model are snake_case. But, even then, in your register method, you're attempting to access the fields on the User model using camelCase.
You haven't given enough information for a definitive answer, but you need to fix the formatting of your variables. For example, change your request fields names from camelCase to snake_case, and make sure you access your fields on the model using snake_case.
You have to pass a list of attributes to "validate" method.
//...
$this->validate($request->all(), [
'firstName' => 'required|min:3',
'lastName' => 'required|min:3',
'displayName' => 'required|min:3',
'emailAddress' => 'required|email|unique:users,email',
'password' => 'required|min:3',
'role' => 'required|exists:roles,id'
]);
One more thing..check if you are using "web" middleware. (Kernel.php => MiddlewareGroups). Add that middleware to your route.

Laravel 5.1 validation

when I use validation in my controller or in a separate request file to validate request of form , it just redirect to itself. But when i remove the validation form just normally update the information please help me.
Here is the route:
Route::group(['prefix' => '{university}'], function() {
Route::Resource('instructor', 'university\univInstructorController');
});
Controller:
<?php
namespace App\Http\Controllers\university;
use App\Http\Requests\university\instructor\instructorUpProfileReq;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\instructor;
use App\university;
use Illuminate\Support\Facades\Redirect;
class univInstructorController extends Controller
{
public function update($university,$id, Request $request)
{
if($universities=university::whereuniversityName($university)->first()){
if($instructors = instructor::find($id)){
$this->validate($request, [
'name' => 'required|alpha|min:3',
'lName' => 'required|alpha|min:3',
'gender' => 'required|alpha',
'birth_date' => 'date',
'degree_type' => 'required|alpha',
'academic_degree' => 'required|alpha',
'phone' => 'max:15',
'address' => 'alpha_dash|min:4',
]);
$input = $request->all();
$instructors->update($input);
return Redirect::action('university\univInstructorController#show',['universities'=>$university,'id'=>$id]);
}
else{
return view('errors.404');
}
}
else{
return view('errors.404');
}
}
}

Resources