Laravel validation for uniques value - laravel

I have multiple customers ,and each customers can have a list of names (customers_name) that can be "aka" or "previous" and for each type value must be unique. Message: "Call to a member function pluck() on array"
$customerPrevious = [];
if($customer_name['name_type'] == 'previous'){
// previous customer_names from server
$customerPrevious = $customer->customerNames()->where('name_type', '=', 'previous')->pluck('name')->toArray();
// previous customer_names from request
$customerPreviousRequest = $request->customer_names->where('name_type', '=', 'previous')->pluck('name')->toArray();
$duplicateValue = array_diff($customerPrevious,$customerPreviousRequest);
if($duplicateValue.length){
return response($exception->getMessage(), 404);
}
}

Your error is because inside $request->customer_names you get array.
->pluck() is for collections.
So you can change:
$request->customer_names->pluck('name')
with
Arr::pluck($request->customer_names, 'name')
More about Arr::pluck() you can find here.

Related

Get last N entries and order by ascending

I'm building a simple message box. Each message belongs to a conversation. What I'm trying to do is get the last 5 messages in the conversation and order them by ascending.
InboxController.php
public function messages($hashedId)
{
$conversation = Conversation::where('hashed_id', $hashedId)->first();
$messages = Message::where('conversation_id', $conversation->id)
->latest()
->take(5)
->get();
$messages->orderBy('created_at','asc');
return MessageResource::collection($messages);
}
Error
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.
Use sortBy function. Collection doesn;t have an function named orderBy.
$collection->sortBy('created_at');
Reference:- https://laravel.com/docs/5.8/collections#method-sortby
try this
public function messages($hashedId)
{
$conversation = Conversation::where('hashed_id', $hashedId)->first();
$messages = Message::where('conversation_id', $conversation->id)
->take(5)
->orderBy('created_at','desc')
->get();
return MessageResource::collection($messages);
}

How to get item from laravel eloquent collection by conditions?

I use laravel eloquent to get files of post that give me a collection
but I want an item from that collection by condition.
For example from that collection I want an item that type = 'product'.
I am using foreach and check every item that have my condition and return it, but isn't any better way?
I tested collection method like contain but it return null.
Files item have type filed that value is 'product' or 'blog'.
My code:
$post= Post::where('slug' , $slug)->first();
$cover = $post->files->contains(['type' , '=' , 'product']);
Use the collection filter method.
$cover = $post->files->filter(function($file) {
// show only the items that match this condition
return collect(['product', 'blog'])->contains($file->type);
});
The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:
$filtered = $post->files->filter(function ($value, $key) {
return $value->type == 'product';
});
$filtered->all();
Collections - filter()

How to remove item from laravel query result and get it?

In Laravel project I am making a database query
$addresses = DB::table('residences')->where('user_id', '=', Auth::user()->id)->get();
I want to get one address from that query result, if it exists, where 'id' field equals to 10 for example. But I want to remove that address from $addresses query result simultaneously. Is there a simple way to do that?
You can use the reject() method on the $addresses collection, i.e:
$my_result = false;
$addresses = $addresses->reject(function ($value, $key) use (&$my_result) {
if($value->id == 10){
$my_result = $value;
return true
}
return false;
});

Laravel simplePaginate() for Grouped Data

I have the following query.
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy(function ($project) {
return Carbon::parse($project->created_at)->format('Y-m-d');
})->simplePaginate(5);
When I try to paginate with the simplePaginate() method I get this error.
stripos() expects parameter 1 to be string, object given
How can I paginate grouped data in this case?
The created_at attribute is already casted as a Carbon Object (by default in laravel models). that's why you are getting that error. Try this:
$projects = Project::orderBy('created_at', 'desc')->get();
$data['sorted'] = $projects->groupBy(function ($project) {
return $project->created_at->format('Y-m-d');
})->simplePaginate(5);
this answer is just for the error you're getting. now if you want help with the QueryBuilder, can you provide an example of the results you're expecting to have and an example of the database structure ?
The pagination methods should be called on queries instead of collection.
You could try:
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy('created_at');
The problem was solved. I was create custom paginator via this example:
https://stackoverflow.com/a/30014621/6405083
$page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
$numPerPage = 15; // Number of results per page
$count = Project::count(); // Get the total number of entries you'll be paging through
// Get the actual items
$projects = Project::orderBy('created_at', 'desc')
->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($project) {
return $project->created_at->format('Y-m-d');
});
$data['sorted'] = new Paginator($projects, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
simplePaginate Method is exist in the path below:
Illuminate\Database\Eloquent\Builder.php::simplePaginate()

Laravel - Trying to get property of non-object in chained view

Having a small problem with retrieving a new object on my view. I keep getting the error 'Trying to get property of non-object'.
The field I am trying to display 'oil_gas_skillsgap' is a valid field and when I do a simple return it spits out...
[{"oil_gas_job_id":"4","industry_job_id":"43","oil_gas_skillsgap":"test text here"}]
CONTROLLER
public function showjob($slug)
{
$job = OilGasJob::where("slug", "=", $slug)->first();
if (is_null($job))
{
return Redirect::to('/');
} else {
$jobId = $job->id;
$roleId = Session::get('industryrole');
$skills = DB::table('industry_job_oil_gas_job')
->where('oil_gas_job_id', '=', $jobId)
->where('industry_job_id', '=', $roleId)
->get();
return View::make('job')
->with('job', $job)
->with('skills', $skills);
}
}
VIEW
{{ $job->job_title}}
{{ $skills->oil_gas_skillsgap }}
$skills is probably an array, not an object, even if the query has only one result.
If you know for a fact that your query will return one result, use first() and you'll get it as an object directly.
$skills = DB::table('industry_job_oil_gas_job')
->where('oil_gas_job_id', '=', $jobId)
->where('industry_job_id', '=', $roleId)
->first();
Otherwise, remember the following: when using the DB class for queries, Laravel will always return an array. If you use an Eloquent model, it will return an Illuminate\Support\Collection object. In both cases that is true even if no row is found (the array or Collection will be empty). The first() method, on the other hand, will either return an object (stdClass when using DB, or a model when using Eloquent) or null.
#user3189734,
job_title is not a part of $job collection, that is why it is throwing 'Trying to get property of non-object'.

Resources