How to rewrite field in Laravel? - laravel

I tried to rewrite a primary key in laravel like as:
public function setIdAttribute($value)
{
$this->attributes['id'] = $value; // or instead $value $this->attributes['idCity']
}
So I need to replace value of id field on value of idCity field

Rename a columns you should create a new migration
To create migration for this change write on console
php artisan make:migration swapKeyId
then go to database->migrations->...swapkey....php
in method called function up() write the code below but replace your table name in my case i use users
Schema::table('users', function ($table) {
$table->renameColumn('id', 'userId');
});
now its time to push migrates to database
php artisan migrate
and its done. this method is renamin it via laravel, also you can change it directly to the database(MySQL,MariaDB,SQL Server etc)

Setting an attribute in your model to define how php should store a value is something entirely different from creating a primary key in MySQL. Setup your migrations following the documentation and there isn't a lot that can go wrong:
Migrations in Laravel 5.2

Related

Creating new table in octobercms

I must create new table in octobercms project and I followed documentation and added new migration file inside plugin update file I have create_currency_rates_table.php file and it has this codes
<?php namespace RainLab\User\Updates;
use Schema;
use October\Rain\Database\Updates\Migration;
class CreateCurrencyRateTable extends Migration
{
public function up()
{
Schema::create('currency_rates', function($table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('currency');
});
}
public function down()
{
Schema::drop('currency_rate');
}
}
when I used php artisan october:up it is not detecting new migration. How can I create new table?Can anyone help me?
You also need to update plugins\<author>\<plugin_name>\updates\version.yaml this file and add your file name there as well.
So, in your case, you added a file like create_currency_rates_table.php then you need to add details of your file in version.yaml
for ex:
1.0.1: First version of Demo
1.0.2:
- Description About what is this update about?
- create_currency_rates_table.php
now when you next time just login to backend this table will be created automatically.
if any doubt please comment.

Laravel 8 - Disable migrations for specific package

Scenario is the following:
I'm building a software where the frontend and the programm that does the work are separated from each other. To have the frontend be able to use the models of the worker-programm, I've build a package that holds them. The package has the following code to it's provider:
public function boot()
{
if($this->app->runningInConsole()){
$this->loadMigrationsFrom(__DIR__ . '/MyPackageMigrations');
}
}
Now my problem is that I want those migrations to be run when the artisan migrate command is run in the worker-programm, but not in the UI-programm, since both databases are separated from each other aswell. Is there a way to supress those migrations in the UI-programm?
Greetings
Rather than using loadMigrationsFrom() in the boot() method of your ServiceProvider, you can use $this->puiblishes() which gives you control over publishing migrations rather than having them load automatically.
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../database/migrations/create_models_table.php.stub'
=> database_path('migrations/' . date('Y_m_d_His', time()) . 'create_models_table.php'),
// you can add any number of migrations here
], 'migrations');
}
}
Then all you need to do is publish the migrations in the projects you want to use the migrations in:
php artisan vendor:publish --provider="Husky110\Husky110Package\Husky110PackageServiceProvider" --tag="migrations"
Update
You can check for the existence of migration by doing something like:
if (!class_exists('CreateModelsTable')) {
// perform migration
}
If you have migrations which alter the structure of a table, you might do:
if (!class_exists('AlterModelsTableAddField')) {
// perform migration
}

How will I identify resource default url in laravel?

I am running this command for model, migration, resource controller.
`php artisan make:model QuestionAnswer -mc -r` ..
Laravel give me in Resource Controller
public function show(QuestionAnswer $questionAnswer) {
// return $questionAnswer;
}
public function edit(QuestionAnswer $questionAnswer) {
// return $questionAnswer;
}
public function update(Request $request, QuestionAnswer $questionAnswer){
// return $questionAnswer;
}
if I write in web.php
Route::resource('question-answer','QuestionAnswerController'); or
Route::resource('questionAnswer','QuestionAnswerController'); or
Route::resource('question_answer','QuestionAnswerController'); laravel resolve route model binding...
that means....
Example as a
public function edit(QuestionAnswer $questionAnswer)
{
return $questionAnswer;
}
$questionAnswer return object for this url {{route('admin.question-answer.edit',$questionAnswer->id)}}
but if I write in web.php Route::resource('faq','QuestionAnswerController');
laravel can not resolve route model binding...
that means.. $questionAnswer return null for this url {{route('admin.faq.edit',$questionAnswer->id)}}
also in show and update function $questionAnswer; return null...
for working as a faq url.. i need change in edit function variable($faq) . or Route::resource('faq','QuestionAnswerController')->parameters(['faq' => 'questionAnswer']);I
But These three url questionAnswer,question-answer,question_answer by default work...
I check it on "laravel/framework": "^6.0" (LTS)
Question
is there possible way to find out what exact url I will write ? .. like question-answer.. or is there any command line ...
after running auth command .. php artisan route:list command give us all route list.. and when I make model Category laravel create table name categories and follow grammar rules
Actually Laravel has got Naming Convection Rules In its core.
These Convictions make it to default binding database_tables to model, model to controllers ....
if you want, you can tell your custom parameters but if you dont, The Laravel uses its own default and searching for them.
for example: if you have a model named bar, laravel look for a table named plural bars . and if you dont want this behave, you can change this default by overriding the *Models* $table_name` attribute for your custom parameter.
There are some Name Convection Rules Like :
tables are plural and models are singular : its not always adding s (es) in trailing.
sometimes it acts more complicate. like : model:person -> table: people
pivot table name are seperate with underline and should be alphabetic order: pivot between fooes and bars table should be bar_foo (not foo_bar)
table primary key for Eloquent find or other related fucntion suppose to be singular_name_id : for people table : person_id
if there are two-words name in model attribute, all of these are Alias :
oneTwo === one_two == one-two
check this out:
class Example extends Model{
public function getFooBarAttribute(){
return "hello";
}
}
all of this return "hello" :
$example = new Example();
$example->foo_bar();
$example->fooBar();
// $example->foo-bar() is not working because - could be result of lexical minus
there is a page listing laravel naming conventions :
https://webdevetc.com/blog/laravel-naming-conventions/
Name Conventions : is The Language Between The Laravel and Developer
it made it easy to not to explicitly mention everything
like Natural Language we can eliminate when we think its obvious.
or we can mention if its not (like ->parameter(...)).
How will I know I need to write question-answer this ? by default it works... when i write faq i need to change in edit function variable($faq) .
How will I know by default url (question-answer) will work ..when php
artisan route:list command give us all route list.. and when I make
model Category laravel create table name categories and follow grammar
rules
think about i will create 20 model ,migration & controller by cmd... i will not change edit,show and update function variable ...how i will know the default url for 20 model and controller ?
Laravel is an opinionated framework. It follows certain conventions
Let us understand a route parts
Route::match(
['PUT', 'PATCH'],
'/question-answer/{questionAnswer}',
[QuestionAnswerController::class, 'update']
)->name('question-answers.update')
In the above route:
1st argument: ['PUT', 'PATCH'] are the methods which the route will try to match for an incoming request
2nd argument: '/question-answer/{questionAnswer}' is the url wherein
/question-answer is say the resource name and
{questionAnswer} is the route parameter name
3rd argument: [QuestionAnswerController::class, 'update'] is the controller and the action/method which will be responsible to handle the request and provide a response
When you create a model via terminal using
php artisan make:model QuestionAnswer -mc -r
It will create a resource controller for the 7 restful actions and take the method parameter name for show, edit, update and delete routes as camel case of the model name i.e. $questionAnswer
class QuestionAnswerController extends Controller
{
public function show(QuestionAnswer $questionAnswer){}
public function edit(QuestionAnswer $questionAnswer){}
public function update(Request $request, QuestionAnswer $questionAnswer){}
public function delete(QuestionAnswer $questionAnswer){}
}
Which means if you don't intend to change the parameter name in the controller methods then you can define the routes as below to get the benefit of implicit route model binding
//Will generate routes with resource name as questionAnswer
//It would not be considered a good practice
Route::resource('questionAnswer', QuestionAnswerController::class);
//OR
Route::resource('question-answer', QuestionAnswerController::class)->parameters([
'question-answer' => 'questionAnswer'
]);
//OR
Route::resource('foo-bar', QuestionAnswerController::class)->parameters([
'foo-bar' => 'questionAnswer'
]);
RFC 3986 defines URLs as case-sensitive for different parts of the URL. Since URLs are case sensitive, keeping it low-key (lower cased) is always safe and considered a good standard.
As you can see, you can name the url resource anything like foo-bar or question-answer instead of questionAnswer and yet keep the route parameter name as questionAnswer to match the Laravel convention when generating controller via php artisan make:model QuestionAnswer -mc -r and without having to change the parameter name in controller methods.
Laravel is an opinionated framework which follows certain conventions:
Route parameter name ('questionAnswer') must match the parameter name in controller methods ($questionAnswer) for implicit route model binding to work
Controller generated via artisan commands, have parameter name as camelCase of the model name
Routes generated via Route::resource('posts', PostController::class) creates routes with resource name equal to the first argument of the method and route parameter name as the singular of the first argument
Route::resource() provides flexibility to use a different name for route resource name and route parameter name
Read more at Laravel docs:
https://laravel.com/docs/8.x/controllers#restful-naming-resource-route-parameters
https://laravel.com/docs/8.x/controllers
https://laravel.com/docs/8.x/routing#route-model-binding
If you want to know how the php artisan make:model works you can study the code in vendor/laravel/framework/src/Illuminate/Foundation/Console/ModelMakeCommand.php and have a look at the various stubs these commands use to generate the files.
For almost all artisan commands you will find the class files with code in
vendor/laravel/framework/src/Illuminate/Foundation/Console and the stubs used by the commands to generate files in vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs folder.
If you study these command classes properly then you will get an idea of the various conventions Laravel follows when generating files via the artisan commands
I think its becuse of dependency injection which you used in youre method.
Try this
public function edit($id)
{
// return $questionAnswer;
return view('backend.faq.edit',get_defined_vars());
}

Impementing global app settings for Laravel API?

I wish to implement a few global app settings, e.g. App name, first day of the week, and other feature flags. The end goal is to have these be fetched and edited by administrators through the API.
What might be the most convenient way of doing this? I've experimented with using a Settings model to store key-value pairs, but this doesn't make sense to me since the desired settings should be hard coded and won't change, and seeding the Settings table doesn't sound ideal. Thanks in advance!
You can access App name from Laravel provided config function.
$appName = config('app.name');
// This value is retrieved from .env file of APP_NAME=
If you have to store multiple values related with the week, you can create a new config file week.php
//config/week.php
return [
...
'first_day_of_the_week' => 0
];
In order to retrieve the first_day_of_the_week, you can use the same function config
$firstDayOfTheWeek = config('week.first_day_of_the_week')
Similar to other essential flags, you can create a new config file.
You can later cache your config variables using the following command.
php artisan config:cache
You can also create a Helper class inside any preferred location inside the laravel project. I keep my helper class inside App\Helpers.
<?php
namespace App\Helpers;
use Carbon\Carbon;
class DateHelpers
{
public const DATE_RANGE_SEPARATOR = ' to ';
public static function getTodayFormat($format = 'Y-m-d')
{
$today = Carbon::now();
$todayDate = Carbon::parse($today->format($format));
return $todayDate;
}
....
}
If you need to retrieve the method value in the Laravel project, you can access by
$getTodayDateFormat = App\Helpers\DateHelpers::getTodayFormat();
EDIT 1:
Based on the question description. You need to create one row in the settings table.
//create_settings_table.php Migration File
public function up()
{
// Create table for storing roles
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->string('app_name')->default("My App Name");
$table->unsignedInteger('first_day_of_the_week')->default(1);
....
$table->timestamps();
});
}
You only need one row of the settings table to retrieve/update the default value.
//Retrieving the first day
$first_day_of_the_week = App\Setting::first()->first_day_of_the_week;
//Updating the first day
...
$first_day_of_the_week = request('first_day_of_the_week');
App\Setting::first()->update([
'first_day_of_the_week' => $first_day_of_the_week
]);

How to add relations to notifications? And get the related data in json

I am trying to create relations, and when notifications are fetched via $user->unreadNotifications I want to control which fields are shown, and fetch the relations. I cannot figure out where to do this.
I did the following:
php artisan notifications:table
php artisan make:migration add_relations_to_notifications_table
In this new migration I added requester_id.
$table->integer('requester_id')->unsigned()->nullable();
$table->foreign('requester_id')->references('id')->on('users')->onDelete('cascade');
php migrate
php artisan make:notification AnInviteWasRequested
Then in AnInviteWasRequested I removed the toArray and replaced it with toDatabase:
public function toDatabase($notifiable)
{
return [
'requester_id' => Auth::guard('api')->user()->id
];
}
However this does not set the requester_id field, it just put json into the data column that looks like this: {"requester_id":1}.
Is there anyway to get this to update the requester_id field instead of updating data?
And also is it possible somewhere, like a Model file (not in vendor dir) to control which fields are displayed when $user->unreadNotifications is done?
Actually to define which field to show/save, and then you need it to display, you only need to modify the toDatabase method. Example:
public function toDatabase($notifiable)
{
$user = Auth::guard('api')->user();
return [
'requester_id' => $user->id,
'requester_name' => $user->name,
// and more data that you need to show
];
}
So for relational data or any other data, just define it inside this method. Hope it helps. :)

Resources