How to save the csv when i import it in Laravel - 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.

Related

Testing 'factory' undefined

Hi im trying to implement a test_user_can_login_with_correct_credentials test and i cant figure out why there is a 'factory' undefined error.
I've searched online and people seem to be getting this because they haven't imported the user model but i have
here is the code
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;
class LoginTest extends TestCase
{
/**
* A basic feature test example.
*
* #return void
*/
public function test_user_can_view_a_login_form()
{
$response = $this->get('/login');
$response->assertSuccessful();
$response->assertViewIs('auth.login');
}
public function test_user_can_login_with_correct_credentials()
{
$user = factory(User::class)->create([ // Error with 'factory' on this line
'first_name' =>('John'),
'last_name' => ('Smith'),
'email' => ('john#example.com'),
'date_of_birth' => ('16/02/2001'),
'password' => Hash::make('test'),
'join_date' => Carbon::now()
]);
$response = $this->from('/login')->post('/login', [
'email' => $user->email,
'password' => 'test',
]);
$response->assertRedirect('/login');
$response->assertSessionHasErrors('email');
$this->assertTrue(session()->hasOldInput('email'));
$this->assertFalse(session()->hasOldInput('password'));
$this->assertGuest();
}
}
The exact error is 'Undefined function 'Tests\Feature\factory'.intelephense(1010)'
Any help would be appreciated im unsure of how to resolve this

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 define action inside form in laravel?

I simply want to add an action to a form and I am trying as follows:
{{ Form::open(['action'=> ['AuthController#login'], 'method'=>"POST",'class'=>'login-form']) }}
But I am getting the following error:
Action App\Http\Controllers\AuthController#login not defined. (View: D:\server\htdocs\PMS\resources\views\custom_auth\login.blade.php)
I configure laravel collective Html. Whats wrong in my code?
Update:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
class AuthController extends Controller
{
function show(){
return view('custom_auth.login');
}
public function login(Request $request){
print_r($request); exit;
$this->validate($request,[
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
]);
$user_data = array(
'email' => $request->get('email'),
'password' => $request->get('password')
);
if(Auth::attempt($user_data)){
return redirect('/dashboard');
}else{
return back()->with('error','Wrong Credential');
}
}
}
You don't need to put your action inside an array when using Form helper so try:
{{ Form::open(['action'=> 'AuthController#login', 'method'=>"POST",'class'=>'login-form']) }}
And of course, make sure that a public login() method exists inside your AuthController
Also, do not forget to add this in your routes file, routes/web.php:
Route::post('login', 'AuthController#login');
I hope it helps

Validate method not found - Laravel

Laravel Framework 5.4.35
Contacts Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactEmail;
class ContactsController extends Controller
{
public function index() {
return view('contact.index');
}
public function sendContact (Request $request) {
$request->validate([
'name' => 'required|min:3',
'email' => 'required|email',
'message' => 'required|min:5',
]);
Mail::to('bump#bumpy.net')
->send(new ContactEmail($request));
return redirect('/contact/success');
}
public function success() {
return view('contact.success');
}
}
The Controller that extends:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
When it goes here:
$request->validate([
'name' => 'required|min:3',
'email' => 'required|email',
'message' => 'required|min:5',
]);
I get this output:
(1/1) BadMethodCallException Method validate does not exist
I have the namespace, the classes to be used. The call to the method seems to be ok.
What am I missing?
Care to advise?
If I create a validator instance manually using the Validator facade.
It seems to validate.
You mention your using version 5.4. The method you're using to validats via the request is only from version 5.5.
So you will need to do it like...
$this->validate($request, [
'name' => 'required|min:3',
'email' => 'required|email',
'message' => 'required|min:5',
]);
Hope this helps. Check out the 5.4v docs rather than the, aster/5.5v
https://laravel.com/docs/5.4/validation#validation-quickstart
Laravel 5.4
$this->validate($request, [
Laravel 5.5
$request->validate([

How to insert multiple rows in database using Eloquent in Laravel5

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..

Resources