Where to process data in Laravel - laravel

Back when I was using CodeIgniter I had functions in my models like
public function GetArticlesFormatted($inactive = FALSE)
and then in my controller I could have had
$articles->GetArticlesFormatted(true);
And so on.
How should I achieve the same with Laravel 5.4? The database of the app I'm building is already built and full and is a mess so most of the "automated" super-restrictive things that Laravel has don't work out of the box.
For example there is a Country Code that I'm retrieving and I need it as is, but in some instances I need it converted in a Country Name which I had in another table.
Right now I just have in my controller wherever I am retrieving data from the model:
$countryResult = Country::where('country_code', $item['country_code'])->first();
$countryArray = $countryResult->toArray();
$item['country'] = $countryArray['country_name'];
Can I somehow achieve that in a more elegant way?
I tried accessors but for some reason couldn't get anything to work for my purposes.

A select query can be used to limit selection to a particular column.
$countryName = Country::select('country_name')
->where('country_code', $item['country_code'])
->first();

Related

Can this block of code of mine can be improved

[This is to populate data from two tables that one has two foreign keys from the same column as reference on the other table]
https://i.stack.imgur.com/D8fiv.png
[This is my schema for the table with the foreign key]
https://i.stack.imgur.com/eYDL0.png
This is written in laravel and it is working however i have an itchy feeling that this is wrong
As someone else has commented, you should put the code in your question. More context might also be necessary as it's not clear what you are trying to return from your view(). Are you returning $citizen, $family, or both? It would also be helpful to include what version of Laravel you are using. I'll assume you are using the latest Laravel 8.
Your code should work but you are making more work for yourself if you don't utilize Laravel's relationships. If you do, all the query stuff you have in your code can be reduced to just a few short lines of code such as this:
public function view(Citizen $citizen)
{
$citizen->load('family');
return $citizen;
}
Database Migration
You can shorten your migration by using foreignId(). See docs for details
https://laravel.com/docs/8.x/migrations#foreign-key-constraints
Before:
$table->integer('client_id')->unsigned();
$table->foreign('client_id')->references('id')->on('citizens');
After:
$table->foreignId('client_id')->constrained();
Route Model Binding
I'm assuming your view() method is in your controller and is called from a route. Since the one parameter required is the client's id, you can use Route Model Binding and skip fetching the client from the database.
https://laravel.com/docs/8.x/routing#route-model-binding
public function view(Citizen $citizen)
{
// your code
}
Relationships
You seem to have relationships set up but you aren't using them to load data. You should be able to load the related objects without any manual queries.
If you have a belongsTo(One to Many) relationship on the Citizen model to the Family model, you can load it like this:
$citizen->load('family');
or just use it like this
$relationship = $citizen->family->relationship;
I don't know what the relationships between your models are but you should read up on the different relationship types in the docs.
https://laravel.com/docs/8.x/eloquent-relationships

Laravel Search Model

Im new to laravel and have completed a project on the latest version laravel 5.6
However, the only thing that is pending to learn and implement is the search functionality which is the core of every application. The application i have coded is a huge project and i do not want to mess it up so would like to learn how search functionality works in order to implement in multiple sections of the project.
Let's say i have a the following models 1.Country 2.State 3.City 4.Professional_Categories 5.Professionals and i have added the relations in the models accordingly
I fetch the records normally using the following code
public function index()
{
$categories = ProfessionalCategory::all();
$topprofessionals = Professional::where('status', 1)->limit(12)->get()->sortByDesc('page_views');
$professionals = Professional::where('status', 1)->latest()->paginate(9);
return view('professionals.index',compact('professionals', 'categories', 'topprofessionals'));
}
I can pull up Countries, States and Cities as i pulled in categories and with foreach i can display them in the select box. Or i could use pluck('name', 'id') that works good too. But i have never tried search queries.
I want a search form on the professionals page where a user can select country, state, city, category and type keywords in locality and professional name to find the professionals. My next step would be to learn dependent dropdown for country, state and city.
And how the results can be displayed on the view file where im currently fetching records with foreach($professionals as $professional)
I do not need code, but just a basic example on how these kind of things work in laravel. Once i learn the basics i want to implement auto suggest from database and things like that. And a single form to search all the models.
It sounds like you'll need full text searching across a number of tables and associated columns. I'd recommend using Laravel Scout or a similar service (such as elastisearch) for this.
These will index your records in a way to allow for fast and efficient fuzzy searching. Using Scout as an example, you can directly query on your models like:
$orders = App\Order::search('Star Trek')->get();
Searching with Scout
This will save you from writing numerous queries using LIKE which becomes very slow and inefficient quite quickly.
Using Eloquent you might do something like this in your Controller:
public function search(Request $request)
{
$countries = Country::where('name', 'like', '%' . $request->search_value . '%')->get();
}
This will return the countries whose name contains the search_value provided by the user.

laravel 5.2 work with belongs to with two different queries

I have write down this query
Controller
$data = User::where('name',$name)->with('country');
In User model
function country () {
return $this->belongsTo('App\Country');
}
In view
echo $data->country->name;
It is working fine but it run 2 queries :(
Select * from user where name = "xyz"
Select * from country where id = "745"
I want to stop this, I want to fetch data with one query only. Join is the solution, Is any other solution for this?
Unfortunately this is the way Eloquent works. It uses two queries because it's a simpler task to initialise your models and to avoid column naming conflicts.
If you are concerned about performance but still want some sort of querying tool, use the Query Builder shipped with Laravel.
To answer your question, joins will be your best bet.
$data=user::with('country')->where('id',745)->where('name','xyz')->get();
i hope that will help you

update view after ajax form post and consequent DB query in laravel 5

I have a database containing products. I want the user to be able to select some filters in a form and return the relative data from the database in the same view. How do you do that in Laravel 5.1?
Your form should/could send the data to your controller and return the view based on those fields they filled in on the form.
Your controller might end up looking something like this.
$srch_val = Input::get('srch_val');
$return_query = Model_Name::where('dbColumn', 'LIKE', $srch_val . '%')
return View::make('your_view')->with('return_query', $return_query);
At least something to get you started, I hope.
Also might be a little different as that last time I did something like this was in 4.2 lol
Code fixed, thanks Kiran.

How to get M:1 relation in Yii2

I am trying to get related model however i cannot seem to find correct documention. In yii 1.x i can do $jobsprocess->category0, but yii 2.x tell me to do $jobsprocess->getCategory(). This does not return a model but an ActiveQuery. How can I return a model object?
In your query use $model = YourModel::find()->with(['category])->all().
All relations using the getRelation() functions can be access with the with() function, but without the get and lowercase first letter.
You can then access the relational data with $model->category.

Resources