Laravel 5 form with file - php

I have a table like this:
Schema::create('partners', function (Blueprint $table) {
$table->increments('id');
$table->binary('image');
$table->string('name');
$table->string('link');
$table->timestamps();
});
Then, after validation, I need to add data from forms, defined as this:
{{Form::file('image')}} I tried this way:
public function newPartner(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'link' => 'required'
]);
if ($validator->fails()) {
return redirect('partners/create')->withErrors($validator);
}
Partner::create($request->all());
return redirect('/');
}
But it doesn't fill the binary field with the uploaded image.
How can I achieve this?
Thank you for helping me.

Related

Change the default Authentification fields (email ,password ) in Laravel

By default, Laravel uses the email and password fields for authentication , I want to change the default fileds for authentication and set the code_massar , date_naissance fields as default
any help !!
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string("code_massar");
$table->date("date_naissance");
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
I use breez package as Authentification Method !
I found one method in laravel 5
Check this post. It's with ldap but it should be usefull i think https://ldaprecord.com/docs/laravel/v2/auth/database/laravel-breeze/#introduction
Go to authenticate method of your LoginController and modify it as your need
public function authenticate(Request $request)
{
$credentials = $request->validate([
'code_massar' => ['required'],
'date_naissance' => ['required'],
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->intended('dashboard');
}
return back()->withErrors([
'code_massar' => 'The provided code_massar do not match our records.',
'date_naissance' => 'The provided date_naissance do not match our records.',
]);
}
you can see more here https://laravel.com/docs/9.x/authentication#authenticating-users

validation.uploaded and call to a member function extension() on null

i'm building an API with laravel8 and want to upload image for posts , and when i don't send values for posts fields in postman , gives me this error :
call to a member function extension() on null
and when i send values for fields , gives this error :
"error": {
"images": [
"validation.uploaded"
]
},
i changed the size of uploaded files in php.ini but it wasn't fixed.
so as you can see , my validation doesn't work when i don't enter values for the fields
my codes :
post table :
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->longText('body');
$table->string('video')->nullable();
$table->string('study_time');
$table->string('images');
$table->integer('likes')->nullable();
$table->tinyInteger('status')->nullable()->comment('status is 1 when a post is active and it is 0 otherwise.')->nullable();
$table->text('tags')->nullable();
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('user_id')->references('id')->on('users');
});
}
and store() method in PostController :
public function store(Request $request )
{
$data = $request->all();
$validator = Validator::make($data, [
'user_id'=>'required',
'category_id'=>'required',
'title' => 'required|max:100|unique:categories',
'body' => 'required|max:500',
'study_time'=>'required',
'images' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.$request->images->extension();
$request->images->move(public_path('images'), $imageName);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'Validation Error']);
}
$post = Post::create($data);
return response()->json([
"success" => true,
"message" => "successfully",
"data" => $post
]);
}
thank you for you help .
It seems that your image is not being uploaded to Laravel, How do you sent your image file to Laravel server?
If you are using VueJS remember to use Formdata more info here.
If a natural form make sure that your image is being sent through by inspecting dev tools on your browser.

SQLSTATE[HY000]: General error: 1364 Field 'firstname' doesn't have a default value (SQL: insert into `users` (`email`) values (test#test.com))

I am new to Laravel framework.
I am facing an issue, with migration of User table.I added nullable to 'firstname' of my table, which works but displaying the same error for 'lastname'column. I have included nullable() to every column, which is not the right way to do it. How to solve this?? Can anyone please suggest.
User migration table, facing issue with the 'firstname' column.
create_user_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('firstname');
$table->string('lastname');
$table->string('email')->unique();
$table->date('dob');
$table->char('address',100);
$table->bigInteger('phonenumber');
});
}
UserController with store
UserController.php
public function store(Request $request)
{
$request->validate([
'firstname'=>'required',
'lastname'=>'required',
'email'=>'required',
]);
$user=new User([
$user->firstname=>$request->get('firstname'),
'lastname'=>$request->get('lastname'),
'email'=>$request->get('email'),
'dob'=>$request->get('dob'),
'address'=>$request->get('address'),
'phonenumber'=>$request->get('phonenumber')
]);
$user->save();
return redirect('/users')->with('success','user added');
}
The easiest way to achieve this is:
public function store(Request $request)
{
$request->validate([
'firstname'=>'required',
'lastname'=>'required',
'email'=>'required',
]);
$user=new User();
$user->firstname = $request->firstname;
$user->lastname = $request->lastname;
$user->email = $request->email;
$user->dob = $request->dob;
$user->address = $request->address;
$user->phonenumber = $request->phonenumber;
$user->save();
return redirect('/users')->with('success','user added');
}
Also in your model, you have to add this line for mass assignment
protected $fillable = ['firstname','lastname','email','dob','address','phonenumber'];
You may check out this link for mass assignment: https://laravel.com/docs/7.x/eloquent#mass-assignment
There is an errors in the code you posted,
Here is the fix:
public function store(Request $request)
{
$request->validate([
'firstname'=>'required',
'lastname'=>'required',
'email'=>'required',
]);
$user=new User([
'firstname' => $request->get('firstname'), // $user->firstname=>$request->get('firstname'),
'lastname'=> $request->get('lastname'),
'email' => $request->get('email'),
'dob' => $request->get('dob'),
'address' => $request->get('address'),
'phonenumber' => $request->get('phonenumber')
]);
$user->save();
return redirect('/users')->with('success','user added');
}
also here you are using mass assignment so you should add all used columns to your fillable array in your User model.
Here is a link on what is mass assignment

Save user data on click button

I'm working on laravel 5.4 and I have this code:
public function apply($id){
$user = User::where('id', $id)->get()->first();
$data = [
'name' => $user->first_name,
'family' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'gender' => $user->gender,
'birthday' => $user->birthday,
'cv' => $user->cv,
'about' => $user->about,
'education' => $user->education,
'experiences' => $user->experiences,
];
$company = Company::get()->first();
Mail::send('emails.apply', $data, function ($message) use ($company)
{
$message->from('noreply#gmail.com', 'Robert Nicjoo');
$message->subject('New Apply');
$message->to($company->email);
});
Mail::send('emails.uapply', $data, function ($message) use ($user)
{
$message->from('noreply#gmail.com', 'Robert Nicjoo');
$message->subject('You Applied successfully');
$message->to($user->email);
});
Session::flash('success', 'Your application was sent to company.');
return redirect()->back()->with('session', $data);
}
This will send email to company when user click on apply button and send user info to them, now I also want to save data of the user include user_id, ad_id and company_id in another table so both user and company owners can have access to their history of applied ads.
I also have this table to save data on:
public function up()
{
Schema::create('applies', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('ad_id')->unsigned();
$table->integer('company_id')->unsigned();
$table->timestamps();
});
Schema::table('ads', function($table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('ad_id')->references('id')->on('ads');
$table->foreign('company_id')->references('company_id')->on('ads');
});
}
but in my controller (first codes) I need to know how to save those information in new table (second codes)?
Update:
Ad Model >>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ad extends Model
{
protected $fillable = [
'company_id', 'title', 'slug', 'image', 'description', 'address', 'job_title', 'salary',
];
public function company(){
return $this->belongsTo(Company::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
public function location(){
return $this->belongsTo(Location::class);
}
public function employment(){
return $this->belongsTo(Employment::class);
}
}
since your blade is like this:
<a class="btn btn-info btn-round" href="{{ route('apply.btn', Auth::user()->id) }}">
your route should look like
Route::get('apply/{id}', 'ApplyController#apply')->name('apply.btn');
why id only ? because in the discussion we had, i found out that ad_id and company_id was taken from the controller .. then in your controller this should work
public function apply($id)
{
$ad = Ad::first();
$company = Company::first();
$apply = new Apply();
$apply->user_id = $id
$apply->ad_id = $ad->id;
$apply->company_id = $company->id;
$apply->save();
// some more codes //
}
to avoid duplicates using user_id .. add a validation function like
function validateApply(array $data)
{
return Validator::make($data, [
'user_id' => 'required|numeric|unique:apply,user_id,NULL,id,ad_id,'.$data->ad_id,
]);
}
unique:apply - it means it will check the apply table the user_id already applied ..
then in the code above just do
$validateApply= $this->validateApply(['user_id'=>$id,'ad_id'=>$ad->id]);
if(!$validateApply->fails())
{
// do the above code here
}
else
{
// duplicate !!! so do your code here
}
then to retrieve the data assuming apply is already belongsTo the user as well the user hasOne apply
Auth::user()->apply->first()->somefield;
// im not sure how the hasOne works but try
Auth::user()->apply->somefield;
Your Route should be:
Route::post('apply/{$user_id}/{company_id}/{ad_id}','ApplyController#apply');
I think you have created model for ads.
So, simply save data like this:
Your function be like
public function apply(Request $request){
// other code
$apply = new Apply();
$apply->user_id = $request->user_id;
$apply->ad_id = $request->ad_id;
$apply->company_id = $request->company_id;
$apply->save();
// other code
}
And one more thing, You should have ad_id in your post request.

Laravel 5.1 extra field for authentication

I'm making my first big project using Laravel 5.1 and I'd like to add an extra check during user login to see if the user has activated their account.
This is the schema of the users table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('username');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->boolean('is_admin')->default(true);
$table->boolean('is_active')->default(true);
$table->timestamps();
});
I've tried adding a $credentials['is_active'] = true; after $credentials = $this->getCredentials($request); in AutheticatesUser#postLogin and it works but I want to have a custom error if the user's account isn't active because the default one(These credentials do not match our records.) is not that intuitive for the user.
Any suggestions in achieving that?
Thank you!
You can override the postLogin method in your AuthController and check whether the user is active or not like this.
class AuthController extends Controller
{
public function postLogin(Request $request){
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $this->getCredentials($request);
// This section is the only change
if (Auth::validate($credentials)) {
$user = Auth::getLastAttempted();
if ($user->is_active) {
Auth::login($user, $request->has('remember'));
return redirect()->intended($this->redirectPath());
} else {
return redirect($this->loginPath()) // Change this to redirect elsewhee
->withInput($request->only('email', 'remember'))
->withErrors([
'active' => 'Please active your account'
]);
}
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
}
You can check following way
if(Auth::attempt(['email'=>$email,'password'=>$password,'is_admin'=>1]))
{
return redirect()->intended('admin/dashboard');
}

Categories