Laravel - How to execute store resource? - php

I'm creating a CRUD app. But when I code in method store I have a problem: I'm trying to create a variable $contact = new Contact(). It's message: Undefined type 'App\Contact'.
This ContactController.php
use App\Contact;
....
public function store(Request $request)
{
$request->validate([
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required'
]);
$contact = new Contact([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'job_title' => $request->get('job_title'),
'city' => $request->get('city'),
'country' => $request->get('country')
]);
$contact->save();
return redirect('/contacts')->with('success', 'Contact saved!');
}
I made it with this link: https://medium.com/techiediaries-com/laravel-7-crud-tutorial-build-a-crud-app-with-mysql-and-bootstrap-4-4ed8e94f2db0

Here are your option to create:
Option 1:
$contact = Contact::create([
'first_name' => $request->get('first_name')
]);
Option 2:
$contact = new Contact();
$contact->first_name = 'test';
$contact->save();
Also in your contact class, check your namespace. And, use the namespace in the controller as:
use App\Models\Contact; //since you said your contact.php is inside models folder

you keep controller simple and clean to use this
use App\Contact; // if use laravel 7
use App\Models\Contact // if use laravel 8
....
public function store(Request $request, Contact $contact)
{
$request->validate([
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required'
]);
$contact->create($request->all());
return redirect('/contacts')->with('success', 'Contact saved!');
}
in function update
use App\Contact;
....
public function update(Request $request, Contact $contact)
{
$id = $contact->id; // if use Route resource
$id = $request->id; // if use Route Post
$request->validate([
'first_name'=> 'required',
'last_name'=>'required',
'email'=>'required'
]);
$date = $request->except(['_token','_method']);
$contact->where('id', $id)->update($date);
return redirect('/contacts')->with('success', 'Contact updated!');
}

Related

Laravel passport doesn't create User

I'm trying to register a user via HTTP POST request with PHP Laravel.
Here is my AuthController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public $successStatus = 200;
public function register(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->save();
$message['success'] = 'Created Account Successfully';
return response()->json([
'message' => $message
], 201);
}
public function login(Request $request){
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = request(['email', 'password']);
if(Auth::attempt($credentials)){
$user = Auth::user();
$message['token'] = $user->createToken('MyApp')->accessToken;
$message['token_type'] = 'Bearer';
$message['experies_at'] = Carbon::parse(Carbon::now()->addWeeks(1))->toDateTimeString();
$message['success'] = 'Logged in successfully';
return response()->json(['message' => $message], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
}
And my routes/api.php:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
Route::post('/users', [AuthController::class, 'register']);
When I send a POST request to http://localhost:8080/api/users/ with name,email and passport parameters, it returns 200 response instead of 201. And it's showing the index page of Laravel, not the response. I checked the database, and user is not created.
Can you help me with what I'm missing?
You could try to change the way you do the route. For exemple:
Route::post('users', 'App\Http\Controllers\UsersController#register');
I dont really get why you do: public $successStatus = 200;
Maybe try to remove this line.

i have a problem with saving data to database using LARAVEL

this is all my codes after cliking on button doesn't save to database i try to change method of saving but not work
use App\makereservations;
use Illuminate\Http\Request;
class reservationController extends Controller
{
public function hreservation()
{
return view('hreservation');
}
public function reserve (Request $request)
{
$this->validate($request ,[
'name' => 'required',
'email' => 'required',
'phone' => 'required|email',
'date' => 'required',
'time' => 'required',
]);
$reservation = new makereservations();
$reservation = $request->input('name');
$reservation = $request->input('email');
$reservation = $request->input('phone');
$reservation = $request->input('date');
$reservation = $request->input('time');
$reservation = $request->input('personne');
$reservation -> statu = false;
$reservation -> save();
return redirect()->back();
}
}
this is the roote
route::post('reserve', 'reservationController#reserve' )->name('reserv.sent');
You missed the -> arrow sign.
$reservation = new makereservations();
$reservation->name = $request->input('name');
$reservation->email = $request->input('email');
$reservation->phone = $request->input('phone');
$reservation->date = $request->input('date');
$reservation->time = $request->input('time');
$reservation->personne = $request->input('personne');
$reservation-> statu = false;
$reservation-> save();
return redirect()->back();
If in the MakeReservations model you have massively assignable fields
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class makereservations extends Model
{
protected $table = "your_table_name"
...
protected $fillable = [
'name', 'email', 'phone', 'date', 'time', 'personne', 'status'
];
...
}
Your reserve method in reservationController it may be so:
<?php
namespace App\Http\Controllers;
use App\makereservations;
use Illuminate\Http\Request;
class reservationController extends Controller
{
...
public function reserve (Request $request)
{
$this->validate($request ,[
'name' => 'required',
'email' => 'required|email',
'phone' => 'required',
'date' => 'required',
'time' => 'required',
]);
$inputs = $request->all();
$inputs['status'] = false;
$reservation = makereservations::create($inputs);
return redirect()->back();
}
}
I have detected that in your validation method you are trying to validate that the phone is an email
You can do it more shortly and in a clean way, to optimize your code.
public function reserve (Request $request)
{
$attributes = $this->validate($request ,[
'name' => 'required',
'email' => 'required|email',
'phone' => 'required',
'date' => 'required',
'time' => 'required',
'personne' => ''
]);
$attributes['statu'] = false;
makereservations::create($attributes);
return redirect()->back();
}
In your model make sure these things
class makereservations extends Model
{
protected $table = 'reservation';
protected $guarded = []; //it means all data from request will be mass assignable
}

Laravel saving data to two locations

I'm working on a larvel project where the user can create appointments. In addition I've created another model called clients so when a user creates an appointment the users "client" data is saved.
In my appointments controller I have the following: -
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
//create appointment
$apt = new Appointment;
$apt->name = $request->input('name');
$apt->user_id = auth()->user()->id;
$apt->save();
//create client
$client = new Client;
$client->first_name = $request->input('name');
$client->user_id = auth()->user()->id;
$client->save();
return redirect('/appointments')->with('success', 'Appointment created');
}
When saving the data it works and stores the data in the clients table however I know this isn't the cleanest way of saving the data, but what is the "laravel" way of doing this?
There's nothing wrong with your code. It's totally fine keeping it that way.
I prefer to say Model::create() to create models in one statement.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
Appointment::create([
'name' => request('name'),
'user_id' => auth()->id()
]);
Client::create([
'first_name' => request('name'),
'user_id' => auth()->id,
]);
return redirect('/appointments')->with('success', 'Appointment created');
}
You can also use tap() function:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
tap(Appointment::create(['name' => request('name'), 'user_id' => auth()->id()]), function ($newAppoinment) {
Client::create([
'first_name' => $newAppoinment->name,
'user_id' => auth()->id,
]);
});
return redirect('/appointments')->with('success', 'Appointment created');
}
Or the best approach could be using model events:
class Appointment extends Model
{
public static function boot()
{
parent::boot();
static::created(function ($appointment) {
Client::create([
'user_id' => $appoinment->user_id,
'first_name' => $appoinment->name,
])
});
}
}

how to make same function for create and update in laravel controller file for create and update operation?

I already have same form for both.
my controller below shows two separate function for create and update
i am new to Laravel framework, and i am working on Address book project.
for creating new:
public function store(Request $request) // for creating new member
{
request()->validate([
'name' => 'required',
'email' => 'required',
'address'=>'required',
'phone'=>'required',
]);
Member::create($request->all());
return redirect()->route('members.index')
->with('success','Member created successfully');
}
public function update(Request $request,Member $member) //for updating member info
{
request()->validate([
'name' => 'required',
'email' => 'required',
'address'=>'required',
'phone'=>'required',
]);
$member->update($request->all());
return redirect()->route('members.index')
->with('success','Member updated successfully');
}
I need to make only one function for both of the operations.thank you in advance.
Define your route
Route::post('createanddelete/{id?}','YourController#yourFunction');
By giving ? in route means that optional parameters
In your controller
public function yourFunction($id = null, Request $request)
{
request()->validate([
'name' => 'required',
'email' => 'required',
'address'=>'required',
'phone'=>'required',
]);
// write update code
if($id)
{
$member = Member::find($id);
if($member)
{
$member->update($request->all());
return redirect()->route('members.index')
->with('success','Member updated successfully');
}
}
// write create code
else
{
Member::create($request->all());
return redirect()->route('members.index')
->with('success','Member created successfully');
}
}
In the view provider the action of form accordingly.
Hope this will help, but you should write separate function for modular code

How to customize redirect url after request validation fails in laravel 5?

I am using use Illuminate\Http\Request to access form request. For example if my form request is coming from http://localhost:8012/test_project/public after validating it is automatically redirecting to http://localhost:8012/test_project/public with error messages but i want it to redirect to http://localhost:8012/test_project/public#myform because my form is visible in #myform section. So how can we do it. I am using Laravel 5.0
Following is my method code in controller that handles my request
public function add_user(Request $request){
$this->validate($request, [
'name' => 'required|min:3',
'email' => 'required|email|unique:users,email',
'mobile' => 'required|regex:/^[789]\d{9}+$/|unique:users,mobile',
'pass' => 'required|min:6',
'cpass' => 'required|same:pass'
]);
$user = new Myuser;
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->mobile = $request->input('mobile');
$user->pass = md5("EEE".$request->input('pass'));
$user->register_on = date('Y-m-d');
$user->user_type = 'Free';
$user->last_login = date('Y-m-d H:i:s');
$user->status = 'Active';
$user->save();
$insertedId = $user->sno;
$uid = "UID".$insertedId;
Myuser::where('sno', $insertedId)
->update(['uid' => $uid]);
//echo $insertedId;
return redirect('')->with('message', 'Registered Successfully');
}
If you make your own Validator instead of using $this->validate(), you can have more control over what happens on a failed validation. Here is an example from the laravel documentation. Make sure you add use Validator; to the top of your php file. https://laravel.com/docs/5.3/validation
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}

Categories