LIKE %% not working in laravel 5.5 - php

I was trying to make a search in laravel but in laravel when I used
User::where('first_name', 'LIKE %', $name);
It Didn't work.
This is my user model.
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable {
use Notifiable;
protected $table = 'users';
protected $fillable = [
'first_name',
'last_name',
'email',
'bio',
'pic',
'location',
'password',
'is_e'
];
protected $hidden = [
'password', 'remember_token',
];
public function project() {
return $this->hasMany('App\Project');
}
}
I also tried not using like but then it was working properly. But not working at all with like. please help
thanx

You have to append % with value not with LIKE string. Try following code:
User::where('first_name', 'LIKE', $name."%"); // add % with $name
For match string from both side
User::where('first_name', 'LIKE', "%".$name."%");

User::where('first_name', 'LIKE', $name."%")->get();

Related

how to transform sql query to laravel query

I'm a beginner so I'm still struggling with this.
I need your help to convert this query to Laravel's query
but apperently this one doen't work even in PhpMyAdmin.
SELECT `candidats.id`
FROM `candidats`,
`candidatures`
WHERE `candidats.id` = `candidatures.candidat_id`
ORDER By `candidatures.date_depot`;
What I want to do is to display all the candidates ordred by etat but this etat that belongs to candidatures table
In Candidat Model :
class Candidat extends Model
{
use HasFactory;
protected $table = 'candidats';
protected $fillable = [
'id_service',
'demande',
'nom',
'prenom',
'email',
'adresse',
'date_naissance',
];
public function candidatures()
{
return $this->hasMany(Candidature::class);
}}
In Candidature Model :
class Candidature extends Model
{
use HasFactory;
protected $table = 'candidatures';
protected $fillable = [
'candidat_id',
'date_depot',
];
public function candidat()
{
return $this->belongsTo(Candidat::class, 'candidat_id');
}
}
Thank you in advance.
Try to get like this
$Candidat = Candidat::with(['candidatures' => function ($query) {
$query->orderBy('date_depot', 'ASC');
}]);
well I've tried
$candidat = Candidat::join('candidatures','candidatures.candidat_id', '=', 'candidats.id')
->where('date_depot','=', $motcle)
->get();
and it works

laravel boot methods not working in the model

hi im using laravel 8 and im trying to do some code after create or update
like if model has create set created_by = Auth::user()->id ect
and this is my model code
<?php
namespace App\Models;
use Helper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Auth;
use App\Models\User;
use Spatie\Activitylog\Traits\LogsActivity;
class Account extends Model
{
use Notifiable,SoftDeletes,LogsActivity;
protected static $logAttributes =
[
'number',
'name',
'foreign_name',
'main_account_id',
'user_id',
'account_state_id',
'note',
'balance_limit',
'approved_state_id'
];
protected static $logName = 'accounts';
protected static $logAttributesToIgnore = [ 'updated_at'];
protected $table = 'accounts';
protected $fillable =
[
'number',
'name',
'foreign_name',
'main_account_id',
'user_id',
'account_state_id',
'note',
'approved_state_id',
'balance_limit',
'created_by','deleted_by'
];
public static function boot()
{
parent::boot();
self::creating(function($model){
$model->created_by = Auth::user()->id; // this code work
});
static::updating(function ($model) {
dd('asdf'); // this not working
});
self::deleting(function($model){
dd($model); // this not working
});
self::restoring(function($model){
dd($model); // this not working
});
}
}
now the code in
static::updating(function ($model) {
dd('asdf'); // this not working
});
is not working when i update any account also in delete and restore
the dd('asdf'); not working
any help here thanks ..
Please try to override the booted method instead of boot. It is an update from laravel 7.
protected static function booted()
{
static::created(function ($user) {
//
});
}
Check the official documentation on Using Closures

Laravel not picking up my table columns? - Laravel 5.5

i'm trying to retrieve a column from my database with laravel.. i've confirmed the column actually exists but apparently laravel doesn't think the same.. any help? thanks!
The error is the following..
"Property [Salt] does not exist on this collection instance."
accounts model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class accounts extends Authenticatable
{
protected $table = "accounts";
public $pkey = 'id';
protected $salt = 'Salt';
protected $fillable = ['id', 'Username', 'Key'];
public $timestamps = false;
}
CustomAuthController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Auth;
class CustomAuthController extends Controller
{
//Login
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$this->validate($request, [
'username' => 'required|max:255',
'Key' => 'required|max:255',
]);
$user= User::where('Username', '=', $request->username)->get();
$hashedpw = hash('whirlpool', $request->Key);
if(Auth::attempt(['Username' => $request->username, 'Key' => $request->Key]))
{
return 'Logged in successfully';
}
else
{
return 'error'. $request->username. ' '. $user->Salt; #problematic variable <-
}
}
}
Thanks!
Jack
Hi, Again.. I've narrowed down the problem although i cant figure out how to fix it.. If my account isn't logged in on my website i cant seem to access the salt column. But, if i'm logged into the site i can select it?..
use first() instead of get() -
$user= User::where('Username', '=', $request->username)->first();
As mentioned in #Sohel0415 answer, your query returns collection not a single user model. You should use first() instead of get()
Also your salt property visibility identifier is protected, you should change this to public for access property from outside.
You have Salt defined as protected $salt
so try $user->salt;
and it should work fine.

Laravel : How to update data in one to one Eloquent relationship

I have two tables:
1. User.
2. Post.
In post table i have saved the user information. So when I click on update, it should load the particular user data. It's get loaded but when i click on the save button to update save.It's showing the following Error.
FatalErrorException in PostController.php line 78: Call to undefined
function App\Http\Controllers\fill()
I think i have problem with my postUpdate controller. But I couldn't find the problem.
Here is my User model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function post()
{
return $this->hasOne('App\Post'); //Profile is your profile model
}
}
Here is my Post Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'first_name', 'middle_name', 'last_name','gender', 'dob','nationality','nid','email','phone_no','about_me'
];
public function user()
{
return $this->belongsTo('App\User'); //Profile is your profile model
}
}
And here is my post Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Post;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
class PostController extends Controller
{
public function getDashboard()
{
$posts = Post::all();
return view('dashboard',['posts'=>$posts]);
}
public function postCreate(Request $request){
$this->validate($request,[
'first_name'=> 'required|max:120',
'middle_name'=> 'required|max:120',
'last_name' => 'required|max:120',
'gender'=> 'required',
'dob'=>'required',
'nationality'=>'required',
'nid'=>'required',
'email' => 'required|email|unique:users',
'phone_no'=>'required',
'about_me'=>'required',
]);
$post = new Post();
$post->first_name = $request['first_name'];
$post->middle_name = $request['middle_name'];
$post->last_name = $request['last_name'];
$post->gender = $request['gender'];
$post->dob = $request['dob'];
$post->nationality = $request['nationality'];
$post->nid = $request['nid'];
$post->email = $request['email'];
$post->phone_no = $request['phone_no'];
$post->about_me = $request['about_me'];
$message='There was an Error';
if( $request->user()->post()->save($post)){
$message = "Profile Created successfully";
}
return redirect()->route('dashboard')->with(['message' => $message]);
}
public function postUpdate(Request $request)
{
$this->validate($request,[
'first_name'=> 'required|max:120',
'middle_name'=> 'required|max:120',
'last_name' => 'required|max:120',
'gender'=> 'required',
'dob'=>'required',
'nationality'=>'required',
'nid'=>'required',
'email' => 'required|email|unique:users',
'phone_no'=>'required',
'about_me'=>'required',
]);
$request->user()->post()->update(fill($request->all())) ;
return redirect()->route('dashboard');
}
}
Here, you're getting a collection of posts:
$data=Post::all();
But you need to pass an array. Try to replace it with:
$data = $request->only('first_name', 'middle_name', 'last_name', 'gender', 'dob', 'nationality', 'nid', 'email', 'phone_no', 'about_me');

Laravel 5 : MassAssignmentException in Model.php

I am getting this error:
MassAssignmentException in Model.php line 448: _token
When I am using create method. Please review code below:
Contacts.php (Model):
class Contacts extends Model
{
protected $table = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at'];
}
ContactsController.php (Controller):
public function store(Request $request)
{
$inputs = $request->all();
$contacts = Contacts::Create($inputs);
return redirect()->route('contacts.index');
}
For the Mass Assignment Exception: you should specify all the fields of the model that you want to be mass-assignable through create or update operations on the property $fillable:
protected $fillable = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at'];
Besides, the field $table should contain only the model's table name:
protected $table = 'your_table_name';
This might happen in case if you have used the wrongly imported the class. if you are using the User Model.
Wrong Import
// mostly IDE suggestion
use Illuminate\Foundation\Auth\User;
Correct Model Import
use App\User;
i have gone through this. might help someone.
You can all column fillable:
protected $guarded = array();
Add your model.
You need only to add the following to your Model (Contact):
protected $fillable = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at'];
For example:
class Contacts extends Model {
protected $table = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at'];
protected $fillable = [ 'name', 'mobile', 'email', 'address', 'created_at', 'updated_at' ];
}
If all of the above fails, you can try following.
Put following after namespace.
use Eloquent;
Put following at the start of your store method.
Eloquent::unguard();
like:
public function store(Request $request)
{
Eloquent::unguard();
$inputs = $request->all();
$contacts = Contacts::Create($inputs);
return redirect()->route('contacts.index');
}
This is not recommended though, as this makes things vulnerable to attacks. But if you need a quick fix this might help.
Check Model you have Imported or Not. If not then use this.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
Make sure you are putting the $fillable or $guarded in the app\Contacts.php file and not the app\Http\Controllers\ContactsController.php file. It should be obvious, but it can be overlooked.

Categories