how to display single value use arrayshit or other thing (without loop) in Laravel - laravel

I use display value or data. In case of a single value use loop, but I know this is a bad habit. How can I solve this? for example I use this:
#foreach($result as $result)
{{$result->data}}
#endforeach

First of all, your code doesn't tell anything, and also you have this code all wrong.
You can't name a pointer as the same name of the array, ($result as $result ???) you will have wrong results or errors.
Also inside the froeach you are referencing a variable that doesn't exists (?).
In my opinion "foreach" is necessary to loop through arrays.
I really don't know what are you trying to do, so that would be great if you expand your question and provide more information.

You can replace that with some code like this:
#if($result)
{{$data}}
#endif

You can try code below see
//example in file ExampleController.php
use App\Posts;
public function showAll(){
$data = Posts::all();
return view('showall',['result'=>$data]);
}
//file web.php
Route::get('/show-all','ExampleController#showAll');
//show-all.blade.php
#foreach($result as $value)
{{$value.title_name}}
#endforeah

Related

Construct routes(urls) with slugs separated by dash in laravel

I am about to make more SEO-friendly URLs on my page and want a pattern looking like this for my products:
www.example.com/product-category/a-pretty-long-seo-friendly-product-name-12
So what are we looking at here?
www.example.com/{slug1}/{slug2}-{id}
The only thing I will care about from the URL in my controller is the {id}. The rest two slugs are just of SEO purpose. So to my question. How can I get the 12 from a-pretty-long-seo-friendly-product-name-12?
I have tried www.mydomain.com/{slug}/{slug}-{id} and in my controller to try and get $id. Id does not work. I am not able to able to separate it from from a-pretty-long-seo-friendly-product-name. So in my controller no matter how I do I get {slug2} and {id} concatenated.
Coming from rails it is a piece of cake there but can't seem to figure out how to do that here in laravel.
EDIT:
I am sorry I formulated my question very unclear. I am looking for a way to do this in the routes file. Like in rails.
You're on the right track, but you can't really logically separate /{slug}-{id} if you're using dash-separated strings. To handle this, you can simply explode the chunks and select the last one:
// routes/web.php
Route::get('/{primarySlug}/{secondarySlugAndId}', [ExampleController::class, 'example']);
// ExampleController.php
public function example($primarySlug, $secondarySlugAndId){
$parts = collect(explode('-', $secondarySlugAndId));
$id = $parts->last();
$secondarySlug = $parts->slice(0, -1)->implode('-');
... // Do anything else you need to do
}
Given the URL example.com/primary-slug/secondary-slug-99, you would have the following variables:
dd($primarySlug, $secondarySlug, $id);
// "primary-slug"
// "secondary-slug"
// "99"
The only case this wouldn't work for is if your id had a dash in it, but that's another layer of complexity that I hope you don't have to handle.
Route::get('/test/{slug1}/{slug2}','IndexController#index');
public function index($slug1, $slug2)
{
$id_slug = last(explode('-',$slug2));
$second_slug = str_replace('-'.$id_slug,'',$slug2);
dd($slug1, $second_slug,$id_slug);
}

Get first letter of word in statement

I have a statement like "Animal Association" from the database. I want to get its short form. It means, only the first letter of each word like this "AA". In the blade file, I got the whole statement as follows,
<p>{{ $animal->user->club->name}}</p>
So, how can I get a short form of this name?
Thank You!
If you are using MySQL 8+, then a raw select with REGEXP_REPLACE should work here:
$users = DB::table('animals')
->select(DB::raw("SELECT REGEXP_REPLACE(name, '(\\w)\\w+\\s*', '$1')"))
->get();
This very common problem where we ran into, I can provide you a function that will solve your problem. I am sharing two solutions and you can use any of these solutions.
using function
You can use this function in your model and solve your problem.
public function getNameAbbreviate($string){
$abbreviation = "";
$string = ucwords($string);
$words = explode(" ", "$string");
foreach($words as $word){
$abbreviation .= $word[0];
}
return $abbreviation;
}
There is probably no one-line solution, the solution which I provided is readable and understandable.
using regex
This solution is easy to apply and in case you can't make the first method work then go with this.
<p>{{ preg_split("/\s+/", $animal->user->club->name) }}</p>
using regex we can get a direct solution but I personally don't like it or recommend it.

Laravel foreach loop

It might be a weird question but I need your help
I might have an array with values.
foreach ($users as $user)
{
$name_user = //condition
array_push($firstarray, $name_user );
}
Let's suppose that $firstarray has these values now ( example : 1 ,2 ,3)
Now
foreach ($firstarray as $t)
{
dd($t);
}
It shows me only the first value
Should it work like this ? I think it has to show the three values.
Of course it will only display 1 because dd() means Dump and Die
You're using DD in a loop, during the first loop, you used the dd(), after reading the dd(), it will kill all the next processes
I suggest you use the dump() so you could see all the contents
Please be aware that Laravel has dd() and dump().
dd() = dump and die, meaning that it will show (print/echo) you the variable but on the same time your script will stop executing when it reach that point on your code.
dump() = dump, simply means that it will show the variable you are interested in, your script will continue executing.
For your situation you should do it like so:
foreach ($firstarray as $t)
{
dump($t);
}
"dd" means "Dump and die".
It prints the first value of $firstarray, "t", and then dies without executing the rest of the loop.
You may wanna try with "echo" or "print_r".
Also, you could use var_dump($firstarray) if you are debugging and want to know the values of the array without having to use a foreach loop.
Foreach will iterate over your array. Since you're doing dump and die, your code will die on first iteration.
If you want to know your array value, you can dump your array outside the loop
dd($firstarray);
dd is a function to dump and die .lets use var_dump method to dump and not die:
foreach ($firstarray as $t)
{
var_dump($t);
}
You can use this to show the data in a nice view.
foreach ($data as $row){
echo '<pre>';
print_r($row);
echo '</pre>';
}

Get segment from url CodeIgniter but not first

I know i can get all segments from url like this
Lets say i have this example link
www.example.com/de/products.html
Using url_helper like this:
$data['url'] = $this->uri->uri_string();
I will get value like this
de/products
But i dont need first segment de, only products, the problem is that
i dont know how many segments it will be, i only need to remove the first
Is there possible to forget first segment with url helper in CI?
Try like this...
Use the php's explode() function to make the url string as array.Then apply array's array_shift() function which always removes the first element from array.
Code is looks like as below
$data= $this->uri->uri_string();
$arr=explode('/', $data);
array_shift($arr);
//print_r($arr);
Then use the php's implode() method to get the URI without first segment.Hope it will works...
$uri=implode('/',$arr);
echo $uri;
There is no URL helper in the CI to forget the first segment. However you can easily make a custom one and put #Hikmat's answer below it in the application/helpers/MY_url_helper.php in the Core folder.
e.g.
function my_forget_first_segment() {
$data= $this->uri->uri_string();
$arr=explode('/', $data);
array_shift($arr);
$uri=implode('/',$arr);
return $uri;
}
Before Edit answer.
You need to try this
$second_segment = $this->uri->segment(2);
From Codeigniter documentation -
$this->uri->segment(n);
Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this:
http://example.com/index.php/news/local/metro/crime_is_up
The segment numbers would be this:
1. news
2. local
3. metro
4. crime_is_up
The optional second parameter defaults to NULL and allows you to set the return value of this method when the requested URI segment is missing. For example, this would tell the method to return the number zero in the event of failure:
$product_id = $this->uri->segment(3, 0);
example:
<?php
$data=$this->uri->segment(2);
$val=explode('.', $data);
echo $val[0];
?>

Magento registry variables in controller

I have stored a variable in register by Mage::register('captcha', $var); in helper. And in the controller i tried to retrieve the variable by using Mage::registry('captcha'); But i dont getting any values here. Please help me to solve this.
In your helper file create a function like below :
public function getCaptcha(){
$var = 'myValue123';
Mage::register('varun', $var);
return Mage::registry('varun');
}
In your controller function:
$registryValue = Mage::helper('yourModule')->getCaptcha();
echo registryValue ; //prints myValue123
Hope it helps !!!
It's look like syntax is right.
Please first try to set some static value like $var="test"
Mage::register('captcha', $var);
after that got this value in controller.
Mage::registry('captcha');
if you got this value test then i think you have problem with $var in your helper.
Let me know if you have any problem
'captcha' is already in use, so magento never set your data in registry. Change the name, for example 'captcha1'
Mage::register('captcha1', $var);

Resources