I have 2 tables: User and demands. A User can have as many demands as he wants. Inside the demands table, there is the User foreign key.
When the User completes the form, I put the User & demands information inside those 2 tables.
But I do not know how to have the User id to put it inside the demands table.
Here is the function inside my Controller:
public function store(Request $request){
$demand = new Demand;
$user = new user ;
$user ->numStudent= $request->NumStudent;
$user ->role_id = "3";
$user ->Lastname = $request->LastName;
$user ->FirstName= $request->FirstName;
$user ->numero_etudiant = "12345678";
$user ->email = $request->Email;
$user ->password = bcrypt('idk');
$user ->adress= $request->Adress;
$user ->phone = $request->Phone;
$user ->parcours = $request->Parcours;
$demand->status_id= "3";
//problem below
$demand->User_id= $User;
//
$demand->time_id = $request->LoanTime;
$demand->creation_date = $request->CreationDate;
$demand->comments = "";
$user ->save();
$demand->save();
return redirect('/demands_list');
}
But it says "Can't use method return value in write context".
Cordially
You have to save first the instance of your user before using its properties. Your code should look like this.
public function store(Request $request){
$demand = new Demand;
$user = new user ;
$user->numStudent= $request->NumStudent;
$user->role_id = "3";
$user->Lastname = $request->LastName;
$user->FirstName= $request->FirstName;
$user->numero_etudiant = "12345678";
$user->email = $request->Email;
$user->password = bcrypt('idk');
$user->adress= $request->Adress;
$user->phone = $request->Phone;
$user->parcours = $request->Parcours;
$user->save();
$demand->status_id= "3";
//problem below
$demand->User_id= $user->id;
//
$demand->time_id = $request->LoanTime;
$demand->creation_date = $request->CreationDate;
$demand->comments = "";
$demand->save();
return redirect('/demands_list');
}
Assuming by your tags that you are looking for an Eloquent (i.e. Laravel) way of doing this.
The short answer: use route model binding and keep your controller methods organized and single-focused.
As already answered, your User needs to be saved first. I would recommend you do this step in its own controller:
// UsersController.php
public function store(Request $request) {
$attributes = $request->validate([
// validation rules
]);
$user = User::create($attributes);
return redirect('/users/' . $user->id);
}
Now that you have a User created, you can then attach related models. Create a separate set of routes pointing to a separate controller for handling the relationship:
// routes/web.php
Route::get('/user/{user}/demands', 'UserDemandsController#index');
Route::post('/user/{user}/demands', 'UserDemandsController#store');
// ^^^^^^
// used with route model binding
Here's where route model binding comes into play, loading the model straight from the route parameters ({user}):
// UserDemandsController.php
public function store(Request $request, User $user) { // <-- ROUTE MODEL BINDING
$attributes = $request->validate([
// validation rules
]);
$user->demands()->create($attributes);
}
The result is very clean, simple code.
Related
how i have to write redirect rout for redirect after save tournament to my new tournament site.
Thanks
This doesnt work
return redirect()->route('tournaments.show', $tournament->slug);
Controller
public function store(Request $request)
{
$tournament = new Tournament();
$tournament->title = $request->title;
$tournament->city = $request->city;
$tournament->street = $request->street;
$tournament->game_room = $request->game_room;
$tournament->email = $request->email;
$tournament->registration_link = $request->registration_link;
$tournament->text = $request->text;
$tournament->phone = $request->phone;
$tournament->time_registration_at = $request->time_registration_at;
$tournament->date_registration_at = $request->date_registration_at;
$tournament->time_starter_at = $request->time_starter_at;
$tournament->date_starter_at = $request->date_starter_at;
$tournament->user_id = Auth::user()->id;
$tournament->region_id = $request->region_id;
$tournament->slug = SlugService::createSlug(Tournament::class, 'slug', $request->title);
$tournament->save();
return redirect()->back();
}
This is incorrect if using resource controller,
return redirect()->route('tournaments.show', $tournament->slug);
it should be
return redirect()->route('tournaments.show', ['tournament'=>$tournament->slug]);
provided that your routeKeyName for your route model binding is set to use a slug and not an id in the model or using the new laravel route model binding in web.php
Route::resource('tournaments',TournamentController::class)->parameters([
'tournament'=>'tournaments:slug'
]);
I am new to Laravel so here goes:
I am creating a page for a user to register an account for his company and enter the payment method and her own login credentials. So this one page will create a Company, a User and a Payment record. The page calls the RegisterController method in Laravel.
However, each of the three objects' create methods are defined within their own controllers. Is it valid (or even good practice) to call other controller methods from within a controller like so (some boilerplate code is missing below...I just want to get my point across)
class RegisterController extends Controller {
//boilerplate code.....
protected function create(Request $request) {
//Create the company
$objCompany = CompanyController->create($request); //gets created first since it is 'top level'
//now create the user:
$objUser = UserController->create($request,$objCompany->id); //Company ID is FK in User
//Create the paymentMethod
$objPaymentMethod = PaymentMethodController->create($request,$objCompany->id); //Company ID is FK in PaymentMethod
}//end create()
}
See rather than calling distinct controllers for table creation try to store the data directly to distinct tables from one controller itself.
like this
public function store(Request $request)
{
$data = request()->validate([
...
]);
$users = new User;
$users->name = $request->name;
$users->ltname = $request->lname;
$users->dob = $request->dob;
$users->bgroup = $request->bgroup;
$users->email = $request->email;
$users->phone = $request->phone;
$users->district = $request->district;
$users->country = $request->country;
$users->state = $request->state;
$users->city = $request->city;
$users->add = $request->add;
$users->pincode = $request->pincode;
$users->password = Hash::make(request('password'));
$users->type = 'Service Center';
$users->save();
$posts = new Post;
$posts->user_id = $users->id;
$posts->fname = $request->fname;
$posts->phone1 = $request->phone1;
$posts->email1 = $request->email1;
$posts->add2 = $request->add2;
$posts->pincode1 = $request->pincode1;
$posts->district1 = $request->district1;
$posts->city1 = $request->city1;
$posts->state1 = $request->state1;
$posts->country1 = $request->country1;
$posts->cmp_id = $request->cmp_id . $users->id;
$posts->gst = $request->gst;
$posts->badd = $request->badd;
$posts->badd2 = $request->badd2;
$posts->save();
$subscribe = new Subscription;
$subscribe->user_id = $users->id;
$subscribe->post_id = $posts->id;
$subscribe->offer_id = $request->m_option_1;
$subscribe->trial_start_date = $offers->of_start_date;
$subscribe->trial_end_date = $offers->of_end_date;
$subscribe->pck_name = $offers->pck_id;
$subscribe->valid_to = $offers->validity;
$subscribe->type = $offers->of_type;
$subscribe->save();
$transactions = new Transactions;
$transactions->user_id = $users->id;
$transactions->post_id = $posts->id;
$transactions->ddl_payment = $request->ddl_payment;
$transactions->txt_ac = $request->txt_ac;
$transactions->txt_amount = $request->txt_amount;
$transactions->txt_dat = $request->txt_dat;
$transactions->txt_ref = $request->txt_ref;
$transactions->save();
return redirect('/show');
}
Here the data which I'm accepting from the form is been stored in four tables users, post, subscription & transaction.
I am having trouble understanding and knowing how to create a one to one relationship with CRUD and file upload together, is it possible to give me a simple example on how to do it? Because when I tried to do it, for some reason my id and user_id doesn't match at all
Example, in user_info table (jack with id 1) has one userImage table(image uploaded with a user_id = 1).
This is the part that I am having trouble with in my controller:
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($file = $request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalExtension() ;
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
//dd($UserImage);
return redirect('/home');
}
Sample of one to one relationship. I wish it can help you.
Example of table of Column of user table:
id
name
email
password
Example of table of Column of userimage table:
id
user_id
image_link
uploaded
User Model
public function userImage()
{
return $this->hasOne(App\UserImage::class);
}
UserImage Model
public function user()
{
return $this->hasOne(App\User::class);
}
CRUD in controller
public function store(Request $request)
{
$user = new App\User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
$user->userImage->create([
'image_link' => $request->image,
'uploaded' => $request->date,
]);
return back();
}
public function update(Request $request, $id)
{
$user = App\User::find($id);
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
$user->userImage->image_link = $request->image;
$user->userImage->uploaded = $request->date;
$user->userImage->save();
return back();
}
public function destroy($id)
{
$user = App\User::find($id)->delete();
return back();
}
Create a foreign key in your user_info table referencing userImage table.
Create unique constraint on the foreign key.
i'm doing a project where ALL user can create a post and pubblic it!
if user not logged blade enable a section with email and password to create account and post.
I would like do:
Creation user
Log user in session auth ( HERE IS MY PROBLEM, HOW CAN I DO THIS? )
Create Post (last point because i need user_id)
CONTROLLER
// if user NOT registered my form will enable email and password field --
if(!null($request->input('email') && request->input('password'))) {
// create user
$user = new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = bcrypt($request->input('name'));
$user->save();
// login user after create user
HOW CAN I LOG USER AFTER CREATED ACCOUNT ???
Thank you for your help!
// Get ID of user created
$get_user_id = User::where('email', '=', $request('email'))->first();
// create post
$post = new Post();
$post->title = $request->input('title');
$post->slug = str_slug($request->input('title'),'-');
$post->country = $request->input('country');
$post->zone = $request->input('zone');
$post->phone = $request->input('phone');
$post->address = $request->input('address');
$post->user_id = $get_user_id->id;
$post->save();
return redirect('/')->with('message-success', 'Post creato con successo!');
// IF USER LOGGED
}else{
$post = new Post();
$post->title = $request->input('title');
$post->slug = str_slug($request->input('title'),'-');
$post->country = $request->input('country');
$post->zone = $request->input('zone');
$post->phone = $request->input('phone');
$post->address = $request->input('address');
$post->user_id = $request->input('user_id');
$post->save();
return redirect('/')->with('message-success', 'Post creato con successo!');
}
The answer is:
Auth::login($user);
Check out the doc.
Is not so clear what you want to do here, the way you get the user id is insecure.
I'll recommend you to use $user = Auth::user(); instead to get the user id, ($user->id).
to check the login manually use
if (Auth::attempt(['email' => $email, 'password' => $password])) {}
so in your example I'll do something like:
if (!Auth::attempt(['email' => $email, 'password' => $password])) {
// create User
} else {
// $userId = Auth::user()->id;
}
// finally create post
Add a __construct() method to your class, and add following code:
public function __construct() {
$this->middleware('auth', ['except' => ['index', 'show']]);
}
And it must actually work
Am having problem updating data into pivot tables.
users[id->autoincrement,username,password,firstname,lastname,lga,email]
class User extends Eloquent
{
public function lga()
{
return $this->HasMany('LGA');
}
}
userslga[id->autoincrement,user_id,lga_id]
public function user()
{
return $this->belongsTo('user');
}
public function lga()
{
return $this->belongsTo('lga');
}
lga[id->autoincrement,lg_name]
class LGA extends Eloquent
{
public function lga()
{
return $this->belongsTo('User');
}
}
When i tried querying relationship,like User::find($id)->lga i could not figure that out.but i eventually made it work using this:
$U_LGA = UserLga::where('user_id',$id)->lists('lga_id');
Now my problem is that i can store data into related tables from my controller like this:
if ($validation->passes())
{
$user = new User;
$user->email = Input::get('email');
$user->username = Input::get('username');
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->type = Input::get('type');
$user->phone = Input::get('phone');
$user->password = Hash::make(Input::get('password'));
$user->save();
//save each users lga
foreach(Input::get('LGA') as $LGS)
{
$userlga = new UserLga;
$userlga->user_id = $user->id;
$userlga->lga_id = $LGS;
$userlga->save();
}
//end
return Redirect::to('/')->with('success','New user profile successfully created');
}
//return json error
return Response::json($validation->messages());
But Updating would be a problem as UserLga::find($id) would not be valid because it the same as select from userlga where id = $id,where as am suppose to be updating all teh row where the user_id is the present user id am editing and add additional lga if more lga was checked.
I need help on how to do this am confused.Or am i getting the concept wrong or is Eloquent relationship query what am suppose to do,
please someone help?
EDIT
I WOULD LIKE TO RUN THE FOLLOWING QUERIES
UserLga::where('user_id',$uid)->lists('lga_id');
I WOULD LIKE TO DO BELOW IN ABETTER WAY TO
$statement2 = "SELECT * FROM facility where LGA_id = '$fulga' ";
//loop through lga id to build query
foreach($LGA_id as $fax)
{
$statement2.= " "."OR"." "."LGA_id=". "'".$fax."'";
}
//FACILITY for User assigned LGA
$facility = DB::Select($statement2);
///////////////////////////////////////////////////////////
//generate all lgaid covered by user
///////////////////////////////////////////////////////////////////////
$ulga = UserLga::where('user_id',$uid)->lists('lga_id');
//remove the first lgaid in array to build query and avoid repetition
$sulga = array_shift($ulga);
// query
$statement = "SELECT * FROM lga where id = '$sulga' ";
//loop through lga id to build query
foreach($ulga as $lga)
{
$statement.= " "."OR"." "."id=". "'".$lga."'";
}
//user assigned lga
$LGA = DB::Select($statement);
AM SORI THIS LOOKS ROUGH A BIT BUT I WANT TO ACHIVE BETTER USING ELOQUENT RELATION QUERY