How to validate and create on laravel 5.2 on controller? - php

Hello I'm trying to create a code generator to invite a user from input email, I want to save on the database the user id who send the invite, the code, and the email who is going to recive the invite, but I can't get the id of my auth user doing $request->user('id') (not working) also I know there is other method to do this easier than using DB::table something like
$request->user()->invites()->create... my controller looks like
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class invitacionController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
return view('administrar');
}
public function invitacion(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255|unique:invites',
]);
/*$request->user()->invites()->create([
'code' => str_random(40),
]);*/
DB::table('invites')->insert([
['usuId' => $request->user('id'), 'code' => str_random(40), 'email' => $request->input('email')],
]);
return redirect('/administrar');
}
}

If the relationship is properly configured, the first (commented) method should be working.
As for the second method, I think you are adding extra brackets:
DB::table('invites')->insert([
'usuId' => $request->user()->id, // <---
'code' => str_random(40),
'email' => $request->input('email')
]);
That hasMany method can take additional parameters. By default it expects the column to be named user_id, but you called it usuId. The documentation gives this example:
return $this->hasMany('App\Comment', 'foreign_key');
So I think you should do
public function invites()
{
return $this->hasMany(Invite::class, 'usuId');
}

Related

How to return a selection in a laravel 5.5 api using a resource

I want to return a selection from my database whenever a user specifies an id.
I have a laravel 5.5 API with in the api.php the following route.
Route::get('companytasks/{id}','TaskController#showOfCompany');
In my TaskController i have the following function:
public function showOfCompany($id)
{
// Get tasks with the specifiec company id
$companytasks = Task::findOrFail($id);
// Return single task as a resource
return new TaskResource($companytasks);
}
And my resource looks like this:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Task extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'TaskCompanyId' => $this->TaskCompanyId,
'TaskName' => $this->TaskName,
'TaskDescription' => $this->TaskDescription,
'Branche' => $this->Branche,
'Budget' => $this->Budget,
'TaskFinishDate' => $this->TaskFinishDate,
'PaydFor' => $this->PaydFor,
'PublicTask' => $this->PublicTask,
'created_at' => $this->created_at
];
}
}
I want to make a selection from the database where the 'TaskCompanyId' equals the $id.
I can do this with the following line in my controller:
$companytasks = Task::where('TaskCompanyId','=',$id)->get();
But this does not work for me, I can however add ->first() to it so it only returns the first occurrance but I want all ocurrances to be returned. How do I achieve this?
You are using 'CompanyTaskId' instead of 'TaskCompanyId' in where clause
Look OK but try with this.
$companytasks = App\Task::where( 'TaskCompanyId' , $id )->get();
If you want you can order or paginate
$companytasks = App\Task::where( 'TaskCompanyId' , $id )
->orderBy('CompanyTaskId', 'desc')
->paginate(15);
I managed to fix it by changing the resource code to:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\ResourceCollection;
class Task extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection
];
}
}
Making a selection returns a collection instead of an object and therefore needs a ResourceCollection instead of a JsonResource.

Can I remove Request from Laravel Controller

Can I remove the following line of code
use Illuminate\Http\Request;
form laravel Controller? Is this a good practice?
For example, my HomeController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$totals = [
'customers' => \App\Customer::count(),
'jobs' => \App\Job::count(),
'invoices' => \App\Invoice::count(),
];
$data = [
'page_title' => 'Dashboard',
'totals' => $totals
];
return view('home', $data);
}
}
Here I don't need the "Request", because none of the functions doesn't use that parameter.
To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller method. The incoming request instance will automatically be injected by the service container.
So if you don't want To obtain an instance of the current HTTP request then remove it.
Yes if you are using just select data query you can go ahead and remove this line. It's need where you will use any get or post form in your class function.

using different table to authenticate user in laravel 5

I have created separate table called subscribers in mysql changed config/auth.php settings to 'model' => App\Subscribers::class, 'table' => 'subscribers'.
I have login form on home page, that submits to the home page.
so in routes i have below
Route::get('/', function () {
return view('home');
});
Route::post('/', 'LoginController#validate');
my LoginController
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function validate()
{
// attempt to do the login
$auth = Auth::attempt(
[
'email' => strtolower(Input::get('email')),
'password' => Hash::make(Input::get('password'))
]
);
if ($auth) {
return Redirect::to('dashboard');
}
}
}
when i login i get below error
Declaration of App\Http\Controllers\LoginController::validate() should be compatible with App\Http\Controllers\Controller::validate(Illuminate\Http\Request $request, array $rules, array $messages = Array, array $customAttributes = Array)
You can't use 'validate' as a name for a function. It will conflict with:
App\Http\Controllers\Controller::validate
Also add an 'else' to your if statement so if your authentication fails you can redirect the user back to the login screen for example.

Laravel 5.1 auth attempt with extra parameters using default auth controller and middleware

How to override Laravel 5.1 auth attempt with extra parameters using default auth controller and middleware?
suppose I have an extra field with status =active or inactive.
How can I write that attempt method?
As specified in the documentation you can pass an array of variables, with their keys being the columns you want to verify the values against in the database.
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Routing\Controller;
class AuthController extends Controller {
public function authenticate(Request $request)
{
$attempt = Auth::attempt([
'email' => $request->get('email'),
'password' => $request->get('password'),
'active' => $request->get('active')
]);
if ($attempt) {
return redirect()->intended('dashboard');
}
}
}

Error on insert data into database using laravel5

I am new in laravel5 Framework. when I insert data into database using laravel5 at that time I get error like....
FatalErrorException in ClientFormRequest.php line 10:
Cannot make static method Symfony\Component\HttpFoundation\Request::create() non static in class App\Http\Requests\ClientFormRequest
my all files are below...
app/Http/Controller/RegisterController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientFormRequest;
use Illuminate\Http\Request;
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}
app/Http/Requests/ClientFormRequest.php
<?php namespace App\Http\Requests;
use Stringy\create;
use App\User;
use Validator;
use App\Http\Requests\ClientFormRequest;
class ClientFormRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
}
public function validator(array $data)
{
return Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
}
public function create(array $data)
{
return client::create([
'fullname' => $data['fullname'],
'email' => $data['email'],
]);
}
}
Routes
Route::get('client', 'RegisterController#create');
Route::post('contact_store', 'RegisterController#store');
First of all, i would suggest you to watch Laravel 5 Fundamentals repeatedly since it is free. Other series also give great information.
Secondly, I would suggest you to use at least Sublime Text and some useful packages to be able to inspect the depth nested relations of system files (Namespaces, Interfaces, Inheritance Tree etc...). If you can't/might not, this friend will serve you anytime Laravel API
Third, AFAIK, Laravel Request is build onto the Symfony' Request Component. Since you are trying to overload one of its core function as non static, you are getting this error.
In addition, to be honest, i wouldn't put my user/client model creation logic into the requests. Laravel provides an good example for this kind of misconception. In the App\Services folder, you will find a registrar service for Laravel oem user model.
Let's inspect the problem with different cases.
but first, basic...
Lets assume that all logic should be put inside the controller.
RegisterController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store()
{
$data = Request::all(); //requested data via Facade
//prepare validatation
$validation = Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
//validate
if ($validation->fails())
{
return redirect()->back()->withErrors($v->errors());
}
// create the client
Client::create([
'fullname' => Request::input('fullname'),
'email' => Request::input('email'),
]);
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}
Second Solution
You might be willing to separate the validation logic and apply some dependency injection.
RegisterController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientFormRequest;
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
// create the client
Client::create([
'fullname' => $request->input('fullname'),
'email' => $request->input('email'),
]);
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}
ClientFormRequest.php
use Stringy\create;
use App\User;
use Validator;
use App\Http\Requests\ClientFormRequest;
class ClientFormRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
return [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users'
];
}
}
Third Solution
You might be willing to take things further and even separate the object creation logic as an service to use it anywhere. Now your request file would stay the same. However,
RegisterController.php
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientFormRequest;
use App\Services\ClientRegistrar;
class RegisterController extends Controller {
private $registrar;
public function __construct(ClientRegistrar $registrarService)
{
$this->registrar = $registrarService;
}
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
$newClient = $this->registrar->create($request->all());
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!')->compact('newClient');
}
}
App\Services\ClientRegistrar.php
use App\Client;
use Validator;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
class ClientRegistrar implements RegistrarContract {
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
return Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
}
/**
* Create a new client instance after a valid registration.
*
* #param array $data
* #return Client
*/
public function create(array $data)
{
// create the client
return Client::create([
'fullname' => $data['fullname'],
'email' => $data['email'],
]);
}
}
To My Conclusion
There is no correct and best way to solve a problem. Stay with the best applicable and appropriate way for you and your project scale.
You also might be interested in;
Jeffrey Way's Laravel Auto Validate on Save
The error message tells you that you are overriding the create method in the ClientFormRequest class. So remove the method there. Instead create the new Client in your Controller.
Below I updated your classes to reflect the changes.
ClientFormRequest
class ClientFormRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
}
public function validator(array $data)
{
return Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
}
}
RegisterController
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
// ClientFormRequest was valid
// create the client
Client::create([
'fullname' => $request->input('fullname'),
'email' => $request->input('email'),
]);
return Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}

Categories